source
stringlengths
3
92
c
stringlengths
26
2.25M
GB_unaryop__lnot_uint8_uint16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_uint8_uint16 // op(A') function: GB_tran__lnot_uint8_uint16 // C type: uint8_t // A type: uint16_t // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ uint16_t #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, x) \ uint8_t z = (uint8_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_UINT8 || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_uint8_uint16 ( uint8_t *restrict Cx, const uint16_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_uint8_uint16 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
task-create.c
/* * task-create.c -- Archer testcase */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // // See tools/archer/LICENSE.txt for details. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // RUN: %libarcher-compile-and-run | FileCheck %s #include <omp.h> #include <stdio.h> #include <unistd.h> #include "ompt/ompt-signal.h" int main(int argc, char *argv[]) { int var = 0, a = 0; #pragma omp parallel num_threads(2) shared(var, a) #pragma omp master { var++; #pragma omp task shared(var, a) { var++; OMPT_SIGNAL(a); } // Give other thread time to steal the task. OMPT_WAIT(a, 1); } fprintf(stderr, "DONE\n"); int error = (var != 2); return error; } // CHECK-NOT: ThreadSanitizer: data race // CHECK-NOT: ThreadSanitizer: reported // CHECK: DONE
cg.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "globals.h" #include "randdp.h" #include "timers.h" #include <omp.h> //--------------------------------------------------------------------- #define CACHE_LINE_SIZE_PAD 16 #define INT_PAD_SIZE CACHE_LINE_SIZE_PAD/sizeof(int) #define DOUBLE_PAD_SIZE CACHE_LINE_SIZE_PAD/sizeof(double) /* common / main_int_mem / */ static int colidx[NZ]; static int rowstr[NA+1]; static int iv[NA]; static int arow[NA]; static int acol[NAZ]; /* common / main_flt_mem / */ static double aelt[NAZ]; static double a[NZ]; static double x[NA+2]; static double z[NA+2][DOUBLE_PAD_SIZE] = {0}; static double p[NA+2][DOUBLE_PAD_SIZE] = {0}; static double q[NA+2][DOUBLE_PAD_SIZE] = {0}; static double r[NA+2][DOUBLE_PAD_SIZE] = {0}; /* common / partit_size / */ static int naa; static int nzz; static int firstrow; static int lastrow; static int firstcol; static int lastcol; /* common /urando/ */ static double amult; static double tran; /* common /timers/ */ static logical timeron=true; //--------------------------------------------------------------------- //--------------------------------------------------------------------- static void conj_grad(int colidx[], int rowstr[], double x[], double z[][DOUBLE_PAD_SIZE], double a[], double p[][DOUBLE_PAD_SIZE], double q[][DOUBLE_PAD_SIZE], double r[][DOUBLE_PAD_SIZE], double *rnorm); static void makea(int n, int nz, double a[], int colidx[], int rowstr[], int firstrow, int lastrow, int firstcol, int lastcol, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int iv[]); static void sparse(double a[], int colidx[], int rowstr[], int n, int nz, int nozer, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int firstrow, int lastrow, int nzloc[], double rcond, double shift); static void sprnvc(int n, int nz, int nn1, double v[], int iv[]); static int icnvrt(double x, int ipwr2); static void vecset(int n, double v[], int iv[], int *nzv, int i, double val); //--------------------------------------------------------------------- int main(int argc, char *argv[]) { omp_set_num_threads(omp_get_num_procs()); int i, j, k, it; double zeta; double rnorm; double norm_temp1, norm_temp2; double t, mflops, tmax; //char Class; logical verified; double zeta_verify_value, epsilon, err; char *t_names[T_last]; for (i = 0; i < T_last; i++) { timer_clear(i); } timer_start(T_init); firstrow = 0; lastrow = NA-1; firstcol = 0; lastcol = NA-1; zeta_verify_value = VALID_RESULT; printf("\nCG start...\n\n"); printf(" Size: %11d\n", NA); printf(" Iterations: %5d\n", NITER); printf("\n"); naa = NA; nzz = NZ; //--------------------------------------------------------------------- // Inialize random number generator //--------------------------------------------------------------------- tran = 314159265.0; amult = 1220703125.0; zeta = randlc(&tran, amult); //--------------------------------------------------------------------- // //--------------------------------------------------------------------- makea(naa, nzz, a, colidx, rowstr, firstrow, lastrow, firstcol, lastcol, arow, (int (*)[NONZER+1])(void*)acol, (double (*)[NONZER+1])(void*)aelt, iv); //--------------------------------------------------------------------- // Note: as a result of the above call to makea: // values of j used in indexing rowstr go from 0 --> lastrow-firstrow // values of colidx which are col indexes go from firstcol --> lastcol // So: // Shift the col index vals from actual (firstcol --> lastcol ) // to local, i.e., (0 --> lastcol-firstcol) //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(i,j,k) { #pragma omp for nowait for (j = 0; j < lastrow - firstrow + 1; j++) { for (k = rowstr[j]; k < rowstr[j+1]; k++) { colidx[k] = colidx[k] - firstcol; } } //--------------------------------------------------------------------- // set starting vector to (1, 1, .... 1) //--------------------------------------------------------------------- #pragma omp for nowait for (i = 0; i < NA+1; i++) { x[i] = 1.0; } #pragma omp for nowait for (j = 0; j < lastcol - firstcol + 1; j++) { q[j][0] = 0.0; z[j][0] = 0.0; r[j][0] = 0.0; p[j][0] = 0.0; } } zeta = 0.0; //--------------------------------------------------------------------- //----> // Do one iteration untimed to init all code and data page tables //----> (then reinit, start timing, to niter its) //--------------------------------------------------------------------- for (it = 1; it <= 1; it++) { //--------------------------------------------------------------------- // The call to the conjugate gradient routine: //--------------------------------------------------------------------- conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm); //--------------------------------------------------------------------- // zeta = shift + 1/(x.z) // So, first: (x.z) // Also, find norm of z // So, first: (z.z) //--------------------------------------------------------------------- norm_temp1 = 0.0; norm_temp2 = 0.0; #pragma omp parallel for default(shared) private(j) reduction(+:norm_temp1,norm_temp2) for (j = 0; j < lastcol - firstcol + 1; j++) { norm_temp1 = norm_temp1 + x[j] * z[j][0]; norm_temp2 = norm_temp2 + z[j][0] * z[j][0]; } norm_temp2 = 1.0 / sqrt(norm_temp2); //--------------------------------------------------------------------- // Normalize z to obtain x //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j) for (j = 0; j < lastcol - firstcol + 1; j++) { x[j] = norm_temp2 * z[j][0]; } } // end of do one iteration untimed //--------------------------------------------------------------------- // set starting vector to (1, 1, .... 1) //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(i) for (i = 0; i < NA+1; i++) { x[i] = 1.0; } zeta = 0.0; timer_stop(T_init); printf(" Initialization time = %15.3f seconds\n", timer_read(T_init)); timer_start(T_bench); //--------------------------------------------------------------------- //----> // Main Iteration for inverse power method //----> //--------------------------------------------------------------------- for (it = 1; it <= NITER; it++) { //--------------------------------------------------------------------- // The call to the conjugate gradient routine: //--------------------------------------------------------------------- if (timeron) timer_start(T_conj_grad); conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm); if (timeron) timer_stop(T_conj_grad); //--------------------------------------------------------------------- // zeta = shift + 1/(x.z) // So, first: (x.z) // Also, find norm of z // So, first: (z.z) //--------------------------------------------------------------------- norm_temp1 = 0.0; norm_temp2 = 0.0; #pragma omp parallel for default(shared) private(j) reduction(+:norm_temp1,norm_temp2) for (j = 0; j < lastcol - firstcol + 1; j++) { norm_temp1 = norm_temp1 + x[j]*z[j][0]; norm_temp2 = norm_temp2 + z[j][0]*z[j][0]; } norm_temp2 = 1.0 / sqrt(norm_temp2); zeta = SHIFT + 1.0 / norm_temp1; if (it == 1) printf("\n iteration ||r|| zeta\n"); printf(" %5d %20.14E%20.13f\n", it, rnorm, zeta); //--------------------------------------------------------------------- // Normalize z to obtain x //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j) for (j = 0; j < lastcol - firstcol + 1; j++) { x[j] = norm_temp2 * z[j][0]; } } // end of main iter inv pow meth timer_stop(T_bench); //--------------------------------------------------------------------- // End of timed section //--------------------------------------------------------------------- t = timer_read(T_bench); printf("\nComplete...\n"); epsilon = 1.0e-10; err = fabs(zeta - zeta_verify_value) / zeta_verify_value; if (err <= epsilon) { verified = true; printf(" VERIFICATION SUCCESSFUL\n"); printf(" Zeta is %20.13E\n", zeta); printf(" Error is %20.13E\n", err); } else { verified = false; printf(" VERIFICATION FAILED\n"); printf(" Zeta %20.13E\n", zeta); printf(" The correct zeta is %20.13E\n", zeta_verify_value); } printf("\n\nExecution time : %lf seconds\n\n", t); return 0; } //--------------------------------------------------------------------- // Floaging point arrays here are named as in spec discussion of // CG algorithm //--------------------------------------------------------------------- static void conj_grad(int colidx[], int rowstr[], double x[], double z[][DOUBLE_PAD_SIZE], double a[], double p[][DOUBLE_PAD_SIZE], double q[][DOUBLE_PAD_SIZE], double r[][DOUBLE_PAD_SIZE], double *rnorm) { int j, k; int cgit, cgitmax = 25; double d, sum, rho, rho0, alpha, beta; //--------------------------------------------------------------------- // Initialize the CG algorithm: //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { #pragma omp for for (j = 0; j < naa+1; j++) { q[j][0] = 0.0; z[j][0] = 0.0; r[j][0] = x[j]; p[j][0] = r[j][0]; } //--------------------------------------------------------------------- // rho = r.r // Now, obtain the norm of r: First, sum squares of r elements locally... //--------------------------------------------------------------------- #pragma omp for reduction(+:rho) for (j = 0; j < lastcol - firstcol + 1; j++) { rho = rho + r[j][0]*r[j][0]; } } //--------------------------------------------------------------------- //----> // The conj grad iteration loop //----> //--------------------------------------------------------------------- for (cgit = 1; cgit <= cgitmax; cgit++) { //--------------------------------------------------------------------- // q = A.p // The partition submatrix-vector multiply: use workspace w //--------------------------------------------------------------------- // // NOTE: this version of the multiply is actually (slightly: maybe %5) // faster on the sp2 on 16 nodes than is the unrolled-by-2 version // below. On the Cray t3d, the reverse is true, i.e., the // unrolled-by-two version is some 10% faster. // The unrolled-by-8 version below is significantly faster // on the Cray t3d - overall speed of code is 1.5 times faster. rho0 = rho; d = 0.0; rho = 0.0; #pragma omp parallel default(shared) private(j, k, sum) { #pragma omp for for (j = 0; j < lastrow - firstrow + 1; j++) { sum = 0.0; for (k = rowstr[j]; k < rowstr[j+1]; k++) { sum = sum + a[k]*p[colidx[k]][0]; } q[j][0] = sum; } } //--------------------------------------------------------------------- // Obtain p.q //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { #pragma omp for reduction(+:d) for (j = 0; j < lastcol - firstcol + 1; j++) { d = d + p[j][0]*q[j][0]; } } //--------------------------------------------------------------------- // Obtain alpha = rho / (p.q) //--------------------------------------------------------------------- alpha = rho0 / d; //--------------------------------------------------------------------- // Save a temporary of rho //--------------------------------------------------------------------- //--------------------------------------------------------------------- // Obtain z = z + alpha*p // and r = r - alpha*q //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { #pragma omp for for (j = 0; j < lastcol - firstcol + 1; j++) { z[j][0] = z[j][0] + alpha*p[j][0]; r[j][0] = r[j][0] - alpha*q[j][0]; } } //--------------------------------------------------------------------- // rho = r.r // Now, obtain the norm of r: First, sum squares of r elements locally... //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { #pragma omp for reduction(+:rho) for (j = 0; j < lastcol - firstcol + 1; j++) { rho = rho + r[j][0]*r[j][0]; } } //--------------------------------------------------------------------- // Obtain beta: //--------------------------------------------------------------------- beta = rho / rho0; //--------------------------------------------------------------------- // p = r + beta*p //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { #pragma omp for for (j = 0; j < lastcol - firstcol + 1; j++) { p[j][0] = r[j][0] + beta*p[j][0]; } } } // end of do cgit=1,cgitmax //--------------------------------------------------------------------- // Compute residual norm explicitly: ||r|| = ||x - A.z|| // First, form A.z // The partition submatrix-vector multiply //--------------------------------------------------------------------- /* for (j = 0; j < lastrow - firstrow + 1; j++) { printf("j = %d, colidx[%d] = %d, z[%d] = %lf\n", j, j, colidx[j], colidx[j], z[colidx[j]][0]); } */ double d_tmp; sum = 0.0; #pragma omp parallel default(shared) private(j, d, d_tmp) shared(sum) { #pragma omp for for (j = 0; j < lastrow - firstrow + 1; j++) { d = 0.0; for (k = rowstr[j]; k < rowstr[j+1]; k++) { d = d + a[k]*z[colidx[k]][0]; } r[j][0] = d; } //--------------------------------------------------------------------- // At this point, r contains A.z //--------------------------------------------------------------------- #pragma omp for reduction(+:sum) for (j = 0; j < lastcol-firstcol+1; j++) { d_tmp = x[j] - r[j][0]; sum = sum + d_tmp*d_tmp; } } *rnorm = sqrt(sum); } //--------------------------------------------------------------------- // generate the test problem for benchmark 6 // makea generates a sparse matrix with a // prescribed sparsity distribution // // parameter type usage // // input // // n i number of cols/rows of matrix // nz i nonzeros as declared array size // rcond r*8 condition number // shift r*8 main diagonal shift // // output // // a r*8 array for nonzeros // colidx i col indices // rowstr i row pointers // // workspace // // iv, arow, acol i // aelt r*8 //--------------------------------------------------------------------- static void makea(int n, int nz, double a[], int colidx[], int rowstr[], int firstrow, int lastrow, int firstcol, int lastcol, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int iv[]) { int iouter, ivelt, nzv, nn1; int ivc[NONZER+1]; double vc[NONZER+1]; //--------------------------------------------------------------------- // nonzer is approximately (int(sqrt(nnza /n))); //--------------------------------------------------------------------- //--------------------------------------------------------------------- // nn1 is the smallest power of two not less than n //--------------------------------------------------------------------- nn1 = 1; do { nn1 = 2 * nn1; } while (nn1 < n); //--------------------------------------------------------------------- // Generate nonzero positions and save for the use in sparse. //--------------------------------------------------------------------- for (iouter = 0; iouter < n; iouter++) { nzv = NONZER; sprnvc(n, nzv, nn1, vc, ivc); vecset(n, vc, ivc, &nzv, iouter+1, 0.5); arow[iouter] = nzv; for (ivelt = 0; ivelt < nzv; ivelt++) { acol[iouter][ivelt] = ivc[ivelt] - 1; aelt[iouter][ivelt] = vc[ivelt]; } } //--------------------------------------------------------------------- // ... make the sparse matrix from list of elements with duplicates // (iv is used as workspace) //--------------------------------------------------------------------- sparse(a, colidx, rowstr, n, nz, NONZER, arow, acol, aelt, firstrow, lastrow, iv, RCOND, SHIFT); } //--------------------------------------------------------------------- // rows range from firstrow to lastrow // the rowstr pointers are defined for nrows = lastrow-firstrow+1 values //--------------------------------------------------------------------- static void sparse(double a[], int colidx[], int rowstr[], int n, int nz, int nozer, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int firstrow, int lastrow, int nzloc[], double rcond, double shift) { int nrows; //--------------------------------------------------- // generate a sparse matrix from a list of // [col, row, element] tri //--------------------------------------------------- int i, j, j1, j2, nza, k, kk, nzrow, jcol; double size, scale, ratio, va; logical cont40; //--------------------------------------------------------------------- // how many rows of result //--------------------------------------------------------------------- nrows = lastrow - firstrow + 1; //--------------------------------------------------------------------- // ...count the number of triples in each row //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j) for (j = 0; j < nrows+1; j++) { rowstr[j] = 0; } for (i = 0; i < n; i++) { for (nza = 0; nza < arow[i]; nza++) { j = acol[i][nza] + 1; rowstr[j] = rowstr[j] + arow[i]; } } rowstr[0] = 0; for (j = 1; j < nrows+1; j++) { rowstr[j] = rowstr[j] + rowstr[j-1]; } nza = rowstr[nrows] - 1; //--------------------------------------------------------------------- // ... rowstr(j) now is the location of the first nonzero // of row j of a //--------------------------------------------------------------------- if (nza > nz) { printf("Space for matrix elements exceeded in sparse\n"); printf("nza, nzmax = %d, %d\n", nza, nz); exit(EXIT_FAILURE); } //--------------------------------------------------------------------- // ... preload data pages //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j, k) for (j = 0; j < nrows; j++) { for (k = rowstr[j]; k < rowstr[j+1]; k++) { a[k] = 0.0; colidx[k] = -1; } nzloc[j] = 0; } //--------------------------------------------------------------------- // ... generate actual values by summing duplicates //--------------------------------------------------------------------- size = 1.0; ratio = pow(rcond, (1.0 / (double)(n))); for (i = 0; i < n; i++) { for (nza = 0; nza < arow[i]; nza++) { j = acol[i][nza]; scale = size * aelt[i][nza]; for (nzrow = 0; nzrow < arow[i]; nzrow++) { jcol = acol[i][nzrow]; va = aelt[i][nzrow] * scale; //-------------------------------------------------------------------- // ... add the identity * rcond to the generated matrix to bound // the smallest eigenvalue from below by rcond //-------------------------------------------------------------------- if (jcol == j && j == i) { va = va + rcond - shift; } cont40 = false; for (k = rowstr[j]; k < rowstr[j+1]; k++) { if (colidx[k] > jcol) { //---------------------------------------------------------------- // ... insert colidx here orderly //---------------------------------------------------------------- for (kk = rowstr[j+1]-2; kk >= k; kk--) { if (colidx[kk] > -1) { a[kk+1] = a[kk]; colidx[kk+1] = colidx[kk]; } } colidx[k] = jcol; a[k] = 0.0; cont40 = true; break; } else if (colidx[k] == -1) { colidx[k] = jcol; cont40 = true; break; } else if (colidx[k] == jcol) { //-------------------------------------------------------------- // ... mark the duplicated entry //-------------------------------------------------------------- nzloc[j] = nzloc[j] + 1; cont40 = true; break; } } if (cont40 == false) { printf("internal error in sparse: i=%d\n", i); exit(EXIT_FAILURE); } a[k] = a[k] + va; } } size = size * ratio; } //--------------------------------------------------------------------- // ... remove empty entries and generate final results //--------------------------------------------------------------------- for (j = 1; j < nrows; j++) { nzloc[j] = nzloc[j] + nzloc[j-1]; } for (j = 0; j < nrows; j++) { if (j > 0) { j1 = rowstr[j] - nzloc[j-1]; } else { j1 = 0; } j2 = rowstr[j+1] - nzloc[j]; nza = rowstr[j]; for (k = j1; k < j2; k++) { a[k] = a[nza]; colidx[k] = colidx[nza]; nza = nza + 1; } } #pragma omp parallel for default(shared) private(j) for (j = 1; j < nrows+1; j++) { rowstr[j] = rowstr[j] - nzloc[j-1]; } nza = rowstr[nrows] - 1; } //--------------------------------------------------------------------- // generate a sparse n-vector (v, iv) // having nzv nonzeros // // mark(i) is set to 1 if position i is nonzero. // mark is all zero on entry and is reset to all zero before exit // this corrects a performance bug found by John G. Lewis, caused by // reinitialization of mark on every one of the n calls to sprnvc //--------------------------------------------------------------------- static void sprnvc(int n, int nz, int nn1, double v[], int iv[]) { int nzv, ii, i; double vecelt, vecloc; nzv = 0; while (nzv < nz) { vecelt = randlc(&tran, amult); //--------------------------------------------------------------------- // generate an integer between 1 and n in a portable manner //--------------------------------------------------------------------- vecloc = randlc(&tran, amult); i = icnvrt(vecloc, nn1) + 1; if (i > n) continue; //--------------------------------------------------------------------- // was this integer generated already? //--------------------------------------------------------------------- logical was_gen = false; for (ii = 0; ii < nzv; ii++) { if (iv[ii] == i) { was_gen = true; break; } } if (was_gen) continue; v[nzv] = vecelt; iv[nzv] = i; nzv = nzv + 1; } } //--------------------------------------------------------------------- // scale a double precision number x in (0,1) by a power of 2 and chop it //--------------------------------------------------------------------- static int icnvrt(double x, int ipwr2) { return (int)(ipwr2 * x); } //--------------------------------------------------------------------- // set ith element of sparse vector (v, iv) with // nzv nonzeros to val //--------------------------------------------------------------------- static void vecset(int n, double v[], int iv[], int *nzv, int i, double val) { int k; logical set; set = false; for (k = 0; k < *nzv; k++) { if (iv[k] == i) { v[k] = val; set = true; } } if (set == false) { v[*nzv] = val; iv[*nzv] = i; *nzv = *nzv + 1; } }
util.c
/** @file @brief Ulitity funcitons for APPFS ex10. @author Tri-Peter Shrive */ #include "ex10.h" /** sets entry at index of prime numbers to 1 */ int get_primes( unsigned int* is_prime, /**< pointer to array of size ceiling, with memory set to zero */ unsigned int ceiling /**< only numbers below this value will be assessed for primality */ ) { unsigned int rest; is_prime[2] = 1; unsigned int count = 1; unsigned int last_div; unsigned int i; unsigned int j; #ifdef THREADS #pragma omp parallel for default(none) shared(is_prime, ceiling, count) private(i, j, rest, last_div) num_threads(THREADS) #endif for( i = 3; i < ceiling; i += 2 ) { last_div = ( unsigned int ) ceil( sqrt( i ) ); for( j = 2; j <= last_div; j++ ) { rest = i % j; if( 0 == rest ) break; else if(j == last_div ) { #ifdef THREADS # pragma omp atomic #endif count++; is_prime[i] = 1; } } } return count; } /** sifts entry up in binary heap */ int sift_up( unsigned int* heap, /**< heap entries */ unsigned int* heap_index, /**< nodes index in heap */ const unsigned long long int* const distance, /**< nodes distance from source */ unsigned int current /**< node to be sifted */ ) { unsigned int a = heap[current]; unsigned long long int dist = distance[a]; unsigned int parent; unsigned int b; while( 1 < current ) { parent = current / 2; b = heap[parent]; if( distance[b] <= dist ) break; heap[current] = b; heap_index[b] = current; current = parent; } heap[current] = a; heap_index[a] = current; return 0; } /** sifts entry down in binary heap */ int sift_down( unsigned int* heap, /**< heap entries */ unsigned int* heap_index, /**< nodes index in heap */ const unsigned long long int* const distance, /**< nodes distance from source */ unsigned int current, /**< node to be sifted */ const unsigned int heap_size /**< size of heap */ ) { unsigned int child = current + current; unsigned int a = heap[current]; unsigned long long int dist = distance[a]; unsigned int b; while( child <= heap_size ) { b = heap[child]; if( child + 1 <= heap_size ) { if( distance[ heap[ child + 1 ] ] < distance[b] ) { child++; b = heap[child]; } } if( distance[b] >= dist ) break; heap[current] = b; heap_index[b] = current; current = child; child += child; } heap[current] = a; heap_index[a] = current; return 0; } /** calculates steiner tree using dijkstra algorithm and additional heuristic @returns number of terminals connected to steiner tree */ int get_steiner_tree( const unsigned int* const is_prime, /**< if index is prime entry is one else zero */ const unsigned int* const terminals, /**< terminal nodes */ const unsigned int num_terminals, /**< number of terminal nodes */ const unsigned int num_nodes, /**< number of nodes */ const unsigned int num_edges, /**< number of edges */ const unsigned int* const first_neighbours_index, /**< index of tails first neighbour in sorted arrays */ const unsigned int* const num_neighbours, /**< number of neighbours for each node */ const unsigned long long int* const sorted_weights, /**< array of weights sorted by tail */ const unsigned int* const sorted_heads, /**< array of heads sorted by tail */ const unsigned int* const sorted_tails, /**< array of tails with an entry for each of their edges */ unsigned int* tree_edges, /**< entries will be set to 1 if sorted lists entries are part of steiner tree else 0*/ unsigned int* prev_edge_index, /**< nodes previous edge in dijkstra */ const unsigned int source /**< source terminal */ ) { assert( is_prime ); assert( terminals ); assert( first_neighbours_index ); assert( sorted_weights ); assert( sorted_heads ); assert( tree_edges ); assert( prev_edge_index ); assert( source < num_nodes ); unsigned int i; unsigned int* heap = NULL; unsigned int* heap_index = NULL; unsigned int* tree_nodes = NULL; unsigned long long int* distance = NULL; // heap[0] reserved for indicating empty heap heap = malloc( ( num_nodes + 1 ) * sizeof( unsigned int ) ); heap_index = malloc( ( num_nodes + 1) * sizeof( unsigned int ) ); tree_nodes = calloc( num_nodes, sizeof( unsigned int ) ); distance = malloc( num_nodes * sizeof( unsigned long long int ) ); assert( heap ); assert( heap_index ); assert( tree_nodes ); assert( distance ); for( i = 0; i < num_nodes; i++ ) { heap[i] = INT_MAX; heap_index[i] = INT_MAX; prev_edge_index[i] = INT_MAX; distance[i] = LLONG_MAX; } heap[num_nodes] = INT_MAX; heap_index[num_nodes] = INT_MAX; unsigned int heap_size = 0; distance[source] = 0; heap_size++; heap[heap_size] = source; heap_index[source] = heap_size; tree_nodes[source] = 1; unsigned int count = 1; unsigned int current; unsigned int tail; unsigned int head; unsigned int root; unsigned int edge_index; unsigned long long int dist; // loop while heap if not empty while( heap_size != 0 ) { // pop priority one node from heap tail = heap[1]; assert( tail < num_nodes ); heap_index[tail] = INT_MAX; root = heap[heap_size]; assert( root < num_nodes ); heap[1] = root; heap_index[root] = 1; heap_size--; sift_down( heap, heap_index, distance, 1, heap_size ); // steiner heuristic // is tail a terminal? if( 1 == is_prime[tail] ) { current = tail; // is this node aleady part of subtree? while( 0 == tree_nodes[current] ) { edge_index = prev_edge_index[current]; // add edge to steiner tree tree_edges[edge_index] = 1; tree_nodes[current] = 1; if( current == tail ) { count++; } // is current node on heap? if( INT_MAX == heap_index[current] ) { // add node with distance zero distance[current] = 0; heap_size++; assert( heap_size != num_nodes + 1 ); heap[heap_size] = current; heap_index[current] = heap_size; sift_up( heap, heap_index, distance, heap_size ); } else { // node already on heap // set distance to zero // and sift up from current position sift_up( heap, heap_index, distance, heap_index[current] ); } current = sorted_tails[edge_index]; } if( count == num_terminals ) break; } // dijkstra algorithm for( i = 0; i < num_neighbours[tail]; i++ ) { // get neighbour edge_index = first_neighbours_index[tail] + i; assert( edge_index < num_edges ); head = sorted_heads[edge_index]; assert( head < num_nodes ); // is node already part of steiner tree? if( 0 == tree_nodes[head] ) { dist = distance[tail] + sorted_weights[edge_index]; assert( dist < LLONG_MAX ); // have we beaten the current best distance? if( dist < distance[head] ) { distance[head] = dist; prev_edge_index[head] = edge_index; // is head already on heap? if( heap_index[head] == INT_MAX ) { // add head at bottom of heap and sift up // until at correct place in priority queue heap_size++; assert( heap_size != num_nodes + 1 ); heap[heap_size] = head; heap_index[head] = heap_size; sift_up( heap, heap_index, distance, heap_size ); } else { // find heap entry for head using heap_index // and sift up sift_up( heap, heap_index, distance, heap_index[head] ); } } } } } free( heap ); free( heap_index ); free( tree_nodes ); free( distance ); return count; } /** verifies steiner tree @returns 1 if steiner tree is connected else 0 */ int is_tree_valid( const unsigned int* const sorted_heads, /** array of heads sorted by tail */ const unsigned int* const sorted_tails, /** array of tails one for each edge */ const unsigned int* const prev_edge_index, /** nodes previous edge in dijkstra */ const unsigned int* const terminals, /**< terminal nodes */ const unsigned int num_terminals, /**< number of terminals */ const unsigned int num_nodes, /**< number of nodes */ const unsigned int num_edges /**< number of nodes */ ) { unsigned int i; unsigned int t; unsigned int prev; unsigned int current; unsigned int* visited = NULL; visited = calloc( num_edges, sizeof( unsigned int ) ); assert( visited ); for( i = 0; i < num_terminals; i++ ) { t = terminals[i]; current = t; while( 0 == visited[current] ) { visited[current] = 1; prev = prev_edge_index[current]; if( INT_MAX == prev ) { if( 0 == i ) break; else { printf("ERROR: terminal %u not connected\n", t); return 0; } } current = sorted_tails[prev]; } } free( visited ); return 1; }
adapter.h
/** * Implementation of a lock-free b-slack tree using LLX/SCX. * Trevor Brown, 2018. */ #ifndef DS_ADAPTER_H #define DS_ADAPTER_H #include <iostream> #include "errors.h" #ifdef USE_TREE_STATS # define TREE_STATS_BYTES_AT_DEPTH # include "tree_stats.h" #endif #include "bslack_impl.h" #if !defined FAT_NODE_DEGREE // #warning "FAT_NODE_DEGREE was not defined... using default: 16." #define FAT_NODE_DEGREE 16 #endif #define NODE_T bslack_ns::Node<FAT_NODE_DEGREE, K> #define RECORD_MANAGER_T record_manager<Reclaim, Alloc, Pool, NODE_T> #define DATA_STRUCTURE_T bslack_ns::bslack<FAT_NODE_DEGREE, K, std::less<K>, RECORD_MANAGER_T> template <typename K, typename V, class Reclaim = reclaimer_debra<K>, class Alloc = allocator_new<K>, class Pool = pool_none<K>> class ds_adapter { private: DATA_STRUCTURE_T * const ds; public: ds_adapter(const int NUM_THREADS, const K& KEY_ANY, const K& unused1, const V& unused2, Random64 * const unused3) : ds(new DATA_STRUCTURE_T(NUM_THREADS, KEY_ANY)) { if (sizeof(V) > sizeof(void *)) { setbench_error("Value type V is too large to fit in void *. This data structure stores all values in fields of type void *, so this is a problem."); } if (NUM_THREADS > MAX_THREADS_POW2) { setbench_error("NUM_THREADS exceeds MAX_THREADS_POW2"); } } ~ds_adapter() { delete ds; } void * getNoValue() { return ds->NO_VALUE; } void initThread(const int tid) { ds->initThread(tid); } void deinitThread(const int tid) { ds->deinitThread(tid); } bool contains(const int tid, const K& key) { return ds->contains(tid, key); } V insert(const int tid, const K& key, const V& val) { return (V) ds->insert(tid, key, val); } V insertIfAbsent(const int tid, const K& key, const V& val) { return (V) ds->insertIfAbsent(tid, key, val); } V erase(const int tid, const K& key) { return (V) ds->erase(tid, key).first; } V find(const int tid, const K& key) { return (V) ds->find(tid, key).first; } int rangeQuery(const int tid, const K& lo, const K& hi, K * const resultKeys, V * const resultValues) { return ds->rangeQuery(tid, lo, hi, resultKeys, (void ** const) resultValues); } void printSummary() { ds->debugGetRecMgr()->printStatus(); } bool validateStructure() { return true; } void printObjectSizes() { std::cout<<"size_node="<<(sizeof(NODE_T))<<std::endl; } // try to clean up: must only be called by a single thread as part of the test harness! void debugGCSingleThreaded() { ds->debugGetRecMgr()->debugGCSingleThreaded(); } #ifdef USE_TREE_STATS class NodeHandler { public: typedef NODE_T * NodePtrType; K minKey; K maxKey; NodeHandler(const K& _minKey, const K& _maxKey) { minKey = _minKey; maxKey = _maxKey; } class ChildIterator { private: size_t ix; NodePtrType node; // node being iterated over public: ChildIterator(NodePtrType _node) { node = _node; ix = 0; } bool hasNext() { return ix < node->size; } NodePtrType next() { return node->ptrs[ix++]; } }; static bool isLeaf(NodePtrType node) { return node->leaf; } static ChildIterator getChildIterator(NodePtrType node) { return ChildIterator(node); } static size_t getNumChildren(NodePtrType node) { return node->size; } static size_t getNumKeys(NodePtrType node) { return isLeaf(node) ? node->size : 0; } static size_t getSumOfKeys(NodePtrType node) { size_t sz = getNumKeys(node); size_t result = 0; for (size_t i=0;i<sz;++i) { result += (size_t) node->keys[i]; } return result; } static size_t getSizeInBytes(NodePtrType node) { return sizeof(*node); } }; TreeStats<NodeHandler> * createTreeStats(const K& _minKey, const K& _maxKey) { return new TreeStats<NodeHandler>(new NodeHandler(_minKey, _maxKey), ds->debug_getEntryPoint(), true); } #endif private: template<typename... Arguments> void iterate_helper_fn(int depth, void (*callback)(K key, V value, Arguments... args) , NODE_T * node, Arguments... args) { if (node == NULL) return; if (node->leaf) { for (int i=0;i<node->getABDegree();++i) { K key = node->keys[i]; V val = (V) node->ptrs[i]; callback(key, val, args...); } return; } for (int i=0;i<node->getABDegree();++i) { if (depth == 4) { #pragma omp task iterate_helper_fn(1+depth, callback, (NODE_T *) node->ptrs[i], args...); } else { iterate_helper_fn(1+depth, callback, (NODE_T *) node->ptrs[i], args...); } } } public: #define DS_ADAPTER_SUPPORTS_TERMINAL_ITERATE template<typename... Arguments> void iterate(void (*callback)(K key, V value, Arguments... args), Arguments... args) { #pragma omp parallel { #pragma omp single iterate_helper_fn(0, callback, ds->debug_getEntryPoint(), args...); } } }; #undef RECORD_MANAGER_T #undef DATA_STRUCTURE_T #undef FAT_NODE_DEGREE #endif
GB_binop__first_int32.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__first_int32 // A.*B function (eWiseMult): GB_AemultB__first_int32 // A*D function (colscale): GB_AxD__first_int32 // D*A function (rowscale): GB_DxB__first_int32 // C+=B function (dense accum): GB_Cdense_accumB__first_int32 // C+=b function (dense accum): GB_Cdense_accumb__first_int32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__first_int32 // C=scalar+B GB_bind1st__first_int32 // C=scalar+B' GB_bind1st_tran__first_int32 // C=A+scalar (none) // C=A'+scalar (none) // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = aij #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ ; // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ 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 ; // 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_FIRST || GxB_NO_INT32 || GxB_NO_FIRST_INT32) //------------------------------------------------------------------------------ // 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__first_int32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__first_int32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__first_int32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type int32_t int32_t bwork = (*((int32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__first_int32 ( 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 int32_t *GB_RESTRICT Cx = (int32_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__first_int32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *GB_RESTRICT Cx = (int32_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__first_int32 ( 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__first_int32 ( 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__first_int32 ( 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 int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { ; ; Cx [p] = x ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( 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 ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int32_t aij = Ax [p] ; Cx [p] = aij ; } return (GrB_SUCCESS) ; #endif } #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) \ { \ ; ; \ Cx [pC] = x ; \ } GrB_Info GB_bind1st_tran__first_int32 ( 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 \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = aij ; \ } GrB_Info (none) ( 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 int32_t y = (*((const int32_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
mult_add_MEX.c
#include "mex.h" #include <math.h> #include "matrix.h" #include <string.h> #include "fast_mxArray_setup.c" #ifdef __GNU__ #include <omp.h> #endif #ifndef MAXCORES #define MAXCORES 1 #endif void mexFunction(int nlhs, mxArray *left[], int nrhs, const mxArray *right[]) { /* Declare variables */ mwSize nD, elem, cmplxX, cmplxY, *size2; long long i; const mwSize *size; mxComplexity cmplx; mxClassID precision1, precision3; mxArray *a, *X, *b, *Y, *Z; double *pa, *pXr, *pXi, *pb, *pYr, *pYi, *pZr, *pZi, Ad=0.0, Bd=0.0; float *paf, *pXrf, *pXif, *pbf, *pYrf, *pYif, *pZrf, *pZif, Af=0.0, Bf=0.0; /* Get number of elements */ elem = mxGetNumberOfElements(right[1]); nD = mxGetNumberOfDimensions(right[1]); size = mxGetDimensions(right[1]); /* Perform strange memory copy to replicate the size (needed for create_array_d/f) */ size2 = (mwSize *)mxMalloc(nD*sizeof(mwSize)); memcpy(size2,size,nD*sizeof(mwSize)); /* Test for complex arrays and obtain data class of input arrays */ cmplxX = mxIsComplex(right[1]); cmplxY = mxIsComplex(right[3]); precision1 = mxGetClassID(right[1]); precision3 = mxGetClassID(right[3]); cmplx = cmplxX ? mxCOMPLEX:mxREAL; /* Throw error if precision or complex mismatch */ if (precision1 != precision3) mexErrMsgTxt("mult_add_MEX: Input data type mismatch"); if (cmplxX != cmplxY) mexErrMsgTxt("Inputs 1 and 3 have different complexity"); if (mxIsComplex(right[0]) | mxIsComplex(right[2])) mexErrMsgTxt("Input 0 and/or 2 is complex"); /* Create output array and pointers */ if (precision1 == mxDOUBLE_CLASS) create_array_d(&(left[0]), &pZr, &pZi, nD, size2, cmplx, 0); else create_array_f(&(left[0]), &pZrf, &pZif, nD, size2, cmplx, 0); /* Get pointers to input arrays */ if (precision1 == mxDOUBLE_CLASS) { pXr = mxGetData(right[1]); pYr = mxGetData(right[3]); if (cmplxX) { pXi = mxGetImagData(right[1]); pYi = mxGetImagData(right[3]); } } else { pXrf = mxGetData(right[1]); pYrf = mxGetData(right[3]); if (cmplxX) { pXif = mxGetImagData(right[1]); pYif = mxGetImagData(right[3]); } } /* Get pointers to input constants */ if (mxGetClassID(right[0]) == mxDOUBLE_CLASS) pa = mxGetData(right[0]); else paf = mxGetData(right[0]); if (mxGetClassID(right[2]) == mxDOUBLE_CLASS) pb = mxGetData(right[2]); else pbf = mxGetData(right[2]); /* Convert first scale factor to correct data type */ if (precision1 == mxDOUBLE_CLASS) { /*mexPrintf("Converting A to double\n");*/ if (mxGetClassID(right[0]) == mxDOUBLE_CLASS) Ad = pa[0]; else Ad = (double) paf[0]; } else { /*mexPrintf("Converting A to float\n");*/ if (mxGetClassID(right[0]) == mxDOUBLE_CLASS) Af = (float) pa[0]; else Af = paf[0]; } /* Convert second scale factor to correct data type */ if (precision1 == mxDOUBLE_CLASS) { /*mexPrintf("Converting B to double\n");*/ if (mxGetClassID(right[2]) == mxDOUBLE_CLASS) Bd = pb[0]; else Bd = (double) pbf[0]; } else { /*mexPrintf("Converting B to float\n");*/ if (mxGetClassID(right[2]) == mxDOUBLE_CLASS) Bf = (float) pb[0]; else Bf = pbf[0]; } /*mexPrintf("Ad: %f\t Bd: %f\n",Ad,Bd); mexPrintf("Af: %f\t Bf: %f\n",(double) Af,(double) Bf);*/ #ifdef __GNU__ /* Set number of threads */ omp_set_num_threads(MAXCORES); #endif /* Loop through and compute the product */ if (precision1 == mxDOUBLE_CLASS) { if (Ad == 1) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZr[i] = pXr[i] + Bd*pYr[i]; if (cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = pXi[i] + Bd*pYi[i]; } else if (cmplxX && !cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = pXi[i]; } else if (!cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = Bd*pYi[i]; } } else if (Bd == 1) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZr[i] = Ad*pXr[i] + pYr[i]; if (cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = Ad*pXi[i] + pYi[i]; } else if (cmplxX && !cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = Ad*pXi[i]; } else if (!cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = pYi[i]; } } else if (Ad == -1) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZr[i] = Bd*pYr[i] - pXr[i] ; if (cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = Bd*pYi[i] - pXi[i] ; } else if (cmplxX && !cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = -pXi[i]; } else if (!cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = Bd*pYi[i]; } } else if (Bd == -1) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZr[i] = Ad*pXr[i] - pYr[i]; if (cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = Ad*pXi[i] - pYi[i]; } else if (cmplxX && !cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = Ad*pXi[i]; } else if (!cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = -pYi[i]; } } else { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZr[i] = Ad*pXr[i] + Bd*pYr[i]; if (cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = Ad*pXi[i] + Bd*pYi[i]; } else if (cmplxX && !cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = Ad*pXi[i]; } else if (!cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZi[i] = Bd*pYi[i]; } } } else { if (Af == 1) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZrf[i] = pXrf[i] + Bf*pYrf[i]; if (cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = pXif[i] + Bf*pYif[i]; } else if (cmplxX && !cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = pXif[i]; } else if (!cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = Bf*pYif[i]; } } else if (Bf == 1) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZrf[i] = Af*pXrf[i] + pYrf[i]; if (cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = Af*pXif[i] + pYif[i]; } else if (cmplxX && !cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = Af*pXif[i]; } else if (!cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = pYif[i]; } } else if (Af == -1) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZrf[i] = Bf*pYrf[i] - pXrf[i] ; if (cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = Bf*pYif[i] - pXif[i] ; } else if (cmplxX && !cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = -pXif[i]; } else if (!cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = Bf*pYif[i]; } } else if (Bf == -1) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZrf[i] = Af*pXrf[i] - pYrf[i]; if (cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = Af*pXif[i] - pYif[i]; } else if (cmplxX && !cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = Af*pXif[i]; } else if (!cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = -pYif[i]; } } else { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZrf[i] = Af*pXrf[i] + Bf*pYrf[i]; if (cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = Af*pXif[i] + Bf*pYif[i]; } else if (cmplxX && !cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = Af*pXif[i]; } else if (!cmplxX && cmplxY) { #pragma omp parallel for private(i) for (i=0; i<elem; i++) pZif[i] = Bf*pYif[i]; } } } /* Free memory */ mxFree(size2); }
phonon.c
/* Copyright (C) 2015 Atsushi Togo */ /* All rights reserved. */ /* This file is part of phonopy. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* * Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* * Redistributions in binary form must reproduce the above copyright */ /* notice, this list of conditions and the following disclaimer in */ /* the documentation and/or other materials provided with the */ /* distribution. */ /* * Neither the name of the phonopy project nor the names of its */ /* contributors may be used to endorse or promote products derived */ /* from this software without specific prior written permission. */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */ /* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */ /* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */ /* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */ /* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */ /* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> #include <string.h> #include <stddef.h> #include <dynmat.h> #include <phonon.h> #include <lapack_wrapper.h> static size_t collect_undone_grid_points(size_t *undone, char *phonon_done, const size_t num_grid_points, const size_t *grid_points); static void get_undone_phonons(double *frequencies, lapack_complex_double *eigenvectors, const size_t *undone_grid_points, const size_t num_undone_grid_points, PHPYCONST int (*grid_address)[3], const int mesh[3], const double *fc2, PHPYCONST double(*svecs_fc2)[27][3], const int *multi_fc2, const size_t num_patom, const size_t num_satom, const double *masses_fc2, const int *p2s_fc2, const int *s2p_fc2, const double unit_conversion_factor, PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const char uplo); static void get_gonze_undone_phonons(double *frequencies, lapack_complex_double *eigenvectors, const size_t *undone_grid_points, const size_t num_undone_grid_points, PHPYCONST int (*grid_address)[3], const int mesh[3], const double *fc2, PHPYCONST double(*svecs_fc2)[27][3], const int *multi_fc2, PHPYCONST double (*positions)[3], const size_t num_patom, const size_t num_satom, const double *masses_fc2, const int *p2s_fc2, const int *s2p_fc2, const double unit_conversion_factor, PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const double *dd_q0, PHPYCONST double(*G_list)[3], const size_t num_G_points, const double lambda, const char uplo); static void get_phonons(lapack_complex_double *eigvecs, const double q[3], const double *fc2, const double *masses, const int *p2s, const int *s2p, const int *multi, const size_t num_patom, const size_t num_satom, PHPYCONST double(*svecs)[27][3], const int is_nac, PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const double unit_conversion_factor); static void get_gonze_phonons(lapack_complex_double *eigvecs, const double q[3], const double *fc2, const double *masses, const int *p2s, const int *s2p, const int *multi, PHPYCONST double (*positions)[3], const size_t num_patom, const size_t num_satom, PHPYCONST double(*svecs)[27][3], const int is_nac, PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const double *dd_q0, PHPYCONST double(*G_list)[3], const size_t num_G_points, const double lambda); static void get_dynamical_matrix(lapack_complex_double *dynmat, const double q[3], const double *fc2, const double *masses, const int *p2s, const int *s2p, const int *multi, const size_t num_patom, const size_t num_satom, PHPYCONST double(*svecs)[27][3], const int is_nac, PHPYCONST double (*born)[3][3], /* Wang NAC unless NULL */ PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor); static void get_charge_sum(double (*charge_sum)[3][3], const size_t num_patom, const size_t num_satom, const double q[3], PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor); static int needs_nac(PHPYCONST double (*born)[3][3], PHPYCONST int (*grid_address)[3], const size_t gp, const double *q_direction); void phn_get_phonons_at_gridpoints(double *frequencies, lapack_complex_double *eigenvectors, char *phonon_done, const size_t num_phonons, const size_t *grid_points, const size_t num_grid_points, PHPYCONST int (*grid_address)[3], const int mesh[3], const double *fc2, PHPYCONST double(*svecs_fc2)[27][3], const int *multi_fc2, const size_t num_patom, const size_t num_satom, const double *masses_fc2, const int *p2s_fc2, const int *s2p_fc2, const double unit_conversion_factor, PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, /* must be pointer */ const double nac_factor, const char uplo) { size_t num_undone; size_t *undone; undone = (size_t*)malloc(sizeof(size_t) * num_phonons); num_undone = collect_undone_grid_points(undone, phonon_done, num_grid_points, grid_points); get_undone_phonons(frequencies, eigenvectors, undone, num_undone, grid_address, mesh, fc2, svecs_fc2, multi_fc2, num_patom, num_satom, masses_fc2, p2s_fc2, s2p_fc2, unit_conversion_factor, born, dielectric, reciprocal_lattice, q_direction, nac_factor, uplo); free(undone); undone = NULL; } void phn_get_gonze_phonons_at_gridpoints(double *frequencies, lapack_complex_double *eigenvectors, char *phonon_done, const size_t num_phonons, const size_t *grid_points, const size_t num_grid_points, PHPYCONST int (*grid_address)[3], const int mesh[3], const double *fc2, PHPYCONST double(*svecs_fc2)[27][3], const int *multi_fc2, PHPYCONST double (*positions)[3], const size_t num_patom, const size_t num_satom, const double *masses_fc2, const int *p2s_fc2, const int *s2p_fc2, const double unit_conversion_factor, PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, /* pointer */ const double nac_factor, const double *dd_q0, PHPYCONST double(*G_list)[3], const size_t num_G_points, const double lambda, const char uplo) { size_t num_undone; size_t *undone; undone = (size_t*)malloc(sizeof(size_t) * num_phonons); num_undone = collect_undone_grid_points(undone, phonon_done, num_grid_points, grid_points); get_gonze_undone_phonons(frequencies, eigenvectors, undone, num_undone, grid_address, mesh, fc2, svecs_fc2, multi_fc2, positions, num_patom, num_satom, masses_fc2, p2s_fc2, s2p_fc2, unit_conversion_factor, born, dielectric, reciprocal_lattice, q_direction, nac_factor, dd_q0, G_list, num_G_points, lambda, uplo); free(undone); undone = NULL; } static size_t collect_undone_grid_points(size_t *undone, char *phonon_done, const size_t num_grid_points, const size_t *grid_points) { size_t i, gp, num_undone; num_undone = 0; for (i = 0; i < num_grid_points; i++) { gp = grid_points[i]; if (phonon_done[gp] == 0) { undone[num_undone] = gp; num_undone++; phonon_done[gp] = 1; } } return num_undone; } static void get_undone_phonons(double *frequencies, lapack_complex_double *eigenvectors, const size_t *undone_grid_points, const size_t num_undone_grid_points, PHPYCONST int (*grid_address)[3], const int mesh[3], const double *fc2, PHPYCONST double(*svecs_fc2)[27][3], const int *multi_fc2, const size_t num_patom, const size_t num_satom, const double *masses_fc2, const int *p2s_fc2, const int *s2p_fc2, const double unit_conversion_factor, PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const char uplo) { size_t i, j, gp, num_band; int is_nac, info; double q[3]; double *freqs_tmp; num_band = num_patom * 3; #pragma omp parallel for private(j, q, gp, is_nac) for (i = 0; i < num_undone_grid_points; i++) { gp = undone_grid_points[i]; for (j = 0; j < 3; j++) { q[j] = ((double)grid_address[gp][j]) / mesh[j]; } is_nac = needs_nac(born, grid_address, gp, q_direction); get_phonons(eigenvectors + num_band * num_band * gp, q, fc2, masses_fc2, p2s_fc2, s2p_fc2, multi_fc2, num_patom, num_satom, svecs_fc2, is_nac, born, dielectric, reciprocal_lattice, q_direction, nac_factor, unit_conversion_factor); } /* To avoid multithreaded BLAS in OpenMP loop */ #ifndef MULTITHREADED_BLAS #pragma omp parallel for private(j, gp, freqs_tmp, info) #endif for (i = 0; i < num_undone_grid_points; i++) { gp = undone_grid_points[i]; freqs_tmp = frequencies + num_band * gp; /* Store eigenvalues in freqs array. */ /* Eigenvectors are overwritten on eigvecs array. */ info = phonopy_zheev(freqs_tmp, eigenvectors + num_band * num_band * gp, num_band, uplo); /* Sqrt of eigenvalues are re-stored in freqs array.*/ for (j = 0; j < num_band; j++) { freqs_tmp[j] = sqrt(fabs(freqs_tmp[j])) * ((freqs_tmp[j] > 0) - (freqs_tmp[j] < 0)) * unit_conversion_factor; } } } static void get_gonze_undone_phonons(double *frequencies, lapack_complex_double *eigenvectors, const size_t *undone_grid_points, const size_t num_undone_grid_points, PHPYCONST int (*grid_address)[3], const int mesh[3], const double *fc2, PHPYCONST double(*svecs_fc2)[27][3], const int *multi_fc2, PHPYCONST double (*positions)[3], const size_t num_patom, const size_t num_satom, const double *masses_fc2, const int *p2s_fc2, const int *s2p_fc2, const double unit_conversion_factor, PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const double *dd_q0, PHPYCONST double(*G_list)[3], const size_t num_G_points, const double lambda, const char uplo) { size_t i, j, gp, num_band; int is_nac, info; double q[3]; double *freqs_tmp; num_band = num_patom * 3; #pragma omp parallel for private(j, q, gp, is_nac) for (i = 0; i < num_undone_grid_points; i++) { gp = undone_grid_points[i]; for (j = 0; j < 3; j++) { q[j] = ((double)grid_address[gp][j]) / mesh[j]; } is_nac = needs_nac(born, grid_address, gp, q_direction); get_gonze_phonons(eigenvectors + num_band * num_band * gp, q, fc2, masses_fc2, p2s_fc2, s2p_fc2, multi_fc2, positions, num_patom, num_satom, svecs_fc2, is_nac, born, dielectric, reciprocal_lattice, q_direction, nac_factor, dd_q0, G_list, num_G_points, lambda); } /* To avoid multithreaded BLAS in OpenMP loop */ #ifndef MULTITHREADED_BLAS #pragma omp parallel for private(j, gp, freqs_tmp, info) #endif for (i = 0; i < num_undone_grid_points; i++) { gp = undone_grid_points[i]; /* Store eigenvalues in freqs array. */ /* Eigenvectors are overwritten on eigvecs array. */ freqs_tmp = frequencies + num_band * gp; info = phonopy_zheev(freqs_tmp, eigenvectors + num_band * num_band * gp, num_band, uplo); /* Sqrt of eigenvalues are re-stored in freqs array.*/ for (j = 0; j < num_band; j++) { freqs_tmp[j] = sqrt(fabs(freqs_tmp[j])) * ((freqs_tmp[j] > 0) - (freqs_tmp[j] < 0)) * unit_conversion_factor; } } } static void get_phonons(lapack_complex_double *eigvecs, const double q[3], const double *fc2, const double *masses, const int *p2s, const int *s2p, const int *multi, const size_t num_patom, const size_t num_satom, PHPYCONST double(*svecs)[27][3], const int is_nac, PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const double unit_conversion_factor) { /* Store dynamical matrix in eigvecs array. */ get_dynamical_matrix(eigvecs, q, fc2, masses, p2s, s2p, multi, num_patom, num_satom, svecs, is_nac, born, dielectric, reciprocal_lattice, q_direction, nac_factor); } static void get_gonze_phonons(lapack_complex_double *eigvecs, const double q[3], const double *fc2, const double *masses, const int *p2s, const int *s2p, const int *multi, PHPYCONST double (*positions)[3], const size_t num_patom, const size_t num_satom, PHPYCONST double(*svecs)[27][3], const int is_nac, PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor, const double *dd_q0, PHPYCONST double(*G_list)[3], const size_t num_G_points, const double lambda) { size_t i, j, k, l, adrs, num_band; double mm; double q_cart[3]; double *q_dir_cart; lapack_complex_double *dd; dd = NULL; q_dir_cart = NULL; num_band = num_patom * 3; dym_get_dynamical_matrix_at_q((double*)eigvecs, num_patom, num_satom, fc2, q, svecs, multi, masses, s2p, p2s, NULL, 0); dd = (lapack_complex_double*) malloc(sizeof(lapack_complex_double) * num_band * num_band); for (i = 0; i < 3; i++) { q_cart[i] = 0; for (j = 0; j < 3; j++) { q_cart[i] += reciprocal_lattice[i][j] * q[j]; } } if (q_direction) { q_dir_cart = (double*)malloc(sizeof(double) * 3); for (i = 0; i < 3; i++) { q_dir_cart[i] = 0; for (j = 0; j < 3; j++) { q_dir_cart[i] += reciprocal_lattice[i][j] * q_direction[j]; } } } dym_get_recip_dipole_dipole((double*)dd, dd_q0, G_list, num_G_points, num_patom, q_cart, q_dir_cart, born, dielectric, positions, nac_factor, lambda, 1e-5); if (q_direction) { free(q_dir_cart); q_dir_cart = NULL; } for (i = 0; i < num_patom; i++) { for (j = 0; j < num_patom; j++) { mm = sqrt(masses[i] * masses[j]); for (k = 0; k < 3; k++) { for (l = 0; l < 3; l++) { adrs = i * num_patom * 9 + k * num_patom * 3 + j * 3 + l; eigvecs[adrs] = lapack_make_complex_double( lapack_complex_double_real(eigvecs[adrs]) + lapack_complex_double_real(dd[adrs]) / mm, lapack_complex_double_imag(eigvecs[adrs]) + lapack_complex_double_imag(dd[adrs]) / mm); } } } } free(dd); dd = NULL; } static void get_dynamical_matrix(lapack_complex_double *dynmat, const double q[3], const double *fc2, const double *masses, const int *p2s, const int *s2p, const int *multi, const size_t num_patom, const size_t num_satom, PHPYCONST double(*svecs)[27][3], const int is_nac, PHPYCONST double (*born)[3][3], /* Wang NAC unless NULL */ PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor) { double (*charge_sum)[3][3]; charge_sum = NULL; if (is_nac) { charge_sum = (double(*)[3][3]) malloc(sizeof(double[3][3]) * num_patom * num_patom * 9); get_charge_sum(charge_sum, num_patom, num_satom, q, born, dielectric, reciprocal_lattice, q_direction, nac_factor); } dym_get_dynamical_matrix_at_q((double*)dynmat, num_patom, num_satom, fc2, q, svecs, multi, masses, s2p, p2s, charge_sum, 0); if (is_nac) { free(charge_sum); charge_sum = NULL; } } static void get_charge_sum(double (*charge_sum)[3][3], const size_t num_patom, const size_t num_satom, const double q[3], PHPYCONST double (*born)[3][3], PHPYCONST double dielectric[3][3], PHPYCONST double reciprocal_lattice[3][3], const double *q_direction, const double nac_factor) { size_t i, j; double inv_dielectric_factor, dielectric_factor, tmp_val; double q_cart[3]; if (q_direction) { for (i = 0; i < 3; i++) { q_cart[i] = 0.0; for (j = 0; j < 3; j++) { q_cart[i] += reciprocal_lattice[i][j] * q_direction[j]; } } } else { for (i = 0; i < 3; i++) { q_cart[i] = 0.0; for (j = 0; j < 3; j++) { q_cart[i] += reciprocal_lattice[i][j] * q[j]; } } } inv_dielectric_factor = 0.0; for (i = 0; i < 3; i++) { tmp_val = 0.0; for (j = 0; j < 3; j++) { tmp_val += dielectric[i][j] * q_cart[j]; } inv_dielectric_factor += tmp_val * q_cart[i]; } /* N = num_satom / num_patom = number of prim-cell in supercell */ /* N is used for Wang's method. */ dielectric_factor = nac_factor / inv_dielectric_factor / num_satom * num_patom; dym_get_charge_sum(charge_sum, num_patom, dielectric_factor, q_cart, born); } static int needs_nac(PHPYCONST double (*born)[3][3], PHPYCONST int (*grid_address)[3], const size_t gp, const double *q_direction) { int is_nac; if (born) { if (grid_address[gp][0] == 0 && grid_address[gp][1] == 0 && grid_address[gp][2] == 0 && q_direction == NULL) { is_nac = 0; } else { is_nac = 1; } } else { is_nac = 0; } return is_nac; }
omp_single_private.c
<ompts:test> <ompts:testdescription>Test which checks the omp single private directive.</ompts:testdescription> <ompts:ompversion>2.0</ompts:ompversion> <ompts:directive>omp singel private</ompts:directive> <ompts:dependences>omp critical,omp flush,omp single nowait</ompts:dependences> <ompts:testcode> #include <stdio.h> #include "omp_testsuite.h" int myit = 0; #pragma omp threadprivate(myit) int myresult = 0; #pragma omp threadprivate(myresult) int <ompts:testcode:functionname>omp_single_private</ompts:testcode:functionname>(FILE * logFile) { <ompts:orphan:vars> int nr_threads_in_single; int result; int nr_iterations; </ompts:orphan:vars> int i; myit = 0; nr_threads_in_single = 0; nr_iterations = 0; result = 0; #pragma omp parallel private(i) { myresult = 0; myit = 0; for (i = 0; i < LOOPCOUNT; i++) { <ompts:orphan> #pragma omp single <ompts:check>private(nr_threads_in_single) </ompts:check>nowait { nr_threads_in_single = 0; #pragma omp flush nr_threads_in_single++; #pragma omp flush myit++; myresult = myresult + nr_threads_in_single; } /* end of single */ </ompts:orphan> } /* end of for */ #pragma omp critical { result += nr_threads_in_single; nr_iterations += myit; } } /* end of parallel */ return ((result == 0) && (nr_iterations == LOOPCOUNT)); } /* end of check_single private */ </ompts:testcode> </ompts:test>
interppotential_calc_potential.c
/* C code for calculating a potential and its forces on a grid */ #ifdef _WIN32 #include <Python.h> #endif #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #ifdef _OPENMP #include <omp.h> #endif #define CHUNKSIZE 1 //Potentials #include <galpy_potentials.h> #include <actionAngle.h> #include <integrateFullOrbit.h> #include <interp_2d.h> #include <cubic_bspline_2d_coeffs.h> #ifdef _WIN32 // On Windows, *need* to define this function to allow the package to be imported #if PY_MAJOR_VERSION >= 3 PyMODINIT_FUNC PyInit_galpy_interppotential_c(void) { // Python 3 return NULL; } #else PyMODINIT_FUNC initgalpy_interppotential_c(void) {} // Python 2 #endif #endif //Macros to export functions in DLL on different OS #if defined(_WIN32) #define EXPORT __declspec(dllexport) #elif defined(__GNUC__) #define EXPORT __attribute__((visibility("default"))) #else // Just do nothing? #define EXPORT #endif /* MAIN FUNCTIONS */ EXPORT void calc_potential(int nR, double *R, int nz, double *z, int npot, int * pot_type, double * pot_args, double *out, int * err){ int ii, jj, tid, nthreads; #ifdef _OPENMP nthreads = omp_get_max_threads(); #else nthreads = 1; #endif double * row= (double *) malloc ( nthreads * nz * ( sizeof ( double ) ) ); //Set up the potentials struct potentialArg * potentialArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) ); parse_leapFuncArgs_Full(npot,potentialArgs,&pot_type,&pot_args); //Run through the grid and calculate UNUSED int chunk= CHUNKSIZE; #pragma omp parallel for schedule(static,chunk) private(ii,tid,jj) \ shared(row,npot,potentialArgs,R,z,nR,nz) for (ii=0; ii < nR; ii++){ #ifdef _OPENMP tid= omp_get_thread_num(); #else tid = 0; #endif for (jj=0; jj < nz; jj++){ *(row+jj+tid*nz)= evaluatePotentials(*(R+ii),*(z+jj),npot,potentialArgs); } put_row(out,ii,row+tid*nz,nz); } free_potentialArgs(npot,potentialArgs); free(potentialArgs); free(row); } EXPORT void calc_rforce(int nR, double *R, int nz, double *z, int npot, int * pot_type, double * pot_args, double *out, int * err){ int ii, jj, tid, nthreads; #ifdef _OPENMP nthreads = omp_get_max_threads(); #else nthreads = 1; #endif double * row= (double *) malloc ( nthreads * nz * ( sizeof ( double ) ) ); //Set up the potentials struct potentialArg * potentialArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) ); parse_leapFuncArgs_Full(npot,potentialArgs,&pot_type,&pot_args); //Run through the grid and calculate UNUSED int chunk= CHUNKSIZE; #pragma omp parallel for schedule(static,chunk) private(ii,tid,jj) \ shared(row,npot,potentialArgs,R,z,nR,nz) for (ii=0; ii < nR; ii++){ #ifdef _OPENMP tid= omp_get_thread_num(); #else tid = 0; #endif for (jj=0; jj < nz; jj++){ *(row+jj+tid*nz)= calcRforce(*(R+ii),*(z+jj),0.,0.,npot,potentialArgs); } put_row(out,ii,row+tid*nz,nz); } free_potentialArgs(npot,potentialArgs); free(potentialArgs); free(row); } EXPORT void calc_zforce(int nR, double *R, int nz, double *z, int npot, int * pot_type, double * pot_args, double *out, int * err){ int ii, jj, tid, nthreads; #ifdef _OPENMP nthreads = omp_get_max_threads(); #else nthreads = 1; #endif double * row= (double *) malloc ( nthreads * nz * ( sizeof ( double ) ) ); //Set up the potentials struct potentialArg * potentialArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) ); parse_leapFuncArgs_Full(npot,potentialArgs,&pot_type,&pot_args); //Run through the grid and calculate UNUSED int chunk= CHUNKSIZE; #pragma omp parallel for schedule(static,chunk) private(ii,tid,jj) \ shared(row,npot,potentialArgs,R,z,nR,nz) for (ii=0; ii < nR; ii++){ #ifdef _OPENMP tid= omp_get_thread_num(); #else tid = 0; #endif for (jj=0; jj < nz; jj++){ *(row+jj+tid*nz)= calczforce(*(R+ii),*(z+jj),0.,0.,npot,potentialArgs); } put_row(out,ii,row+tid*nz,nz); } free_potentialArgs(npot,potentialArgs); free(potentialArgs); free(row); } EXPORT void eval_potential(int nR, double *R, double *z, int npot, int * pot_type, double * pot_args, double *out, int * err){ int ii; //Set up the potentials struct potentialArg * potentialArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) ); parse_leapFuncArgs_Full(npot,potentialArgs,&pot_type,&pot_args); //Run through and evaluate for (ii=0; ii < nR; ii++){ *(out+ii)= evaluatePotentials(*(R+ii),*(z+ii),npot,potentialArgs); } free_potentialArgs(npot,potentialArgs); free(potentialArgs); } EXPORT void eval_rforce(int nR, double *R, double *z, int npot, int * pot_type, double * pot_args, double *out, int * err){ int ii; //Set up the potentials struct potentialArg * potentialArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) ); parse_leapFuncArgs_Full(npot,potentialArgs,&pot_type,&pot_args); //Run through and evaluate for (ii=0; ii < nR; ii++){ *(out+ii)= calcRforce(*(R+ii),*(z+ii),0.,0.,npot,potentialArgs); } free_potentialArgs(npot,potentialArgs); free(potentialArgs); } EXPORT void eval_zforce(int nR, double *R, double *z, int npot, int * pot_type, double * pot_args, double *out, int * err){ int ii; //Set up the potentials struct potentialArg * potentialArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) ); parse_leapFuncArgs_Full(npot,potentialArgs,&pot_type,&pot_args); //Run through and evaluate for (ii=0; ii < nR; ii++){ *(out+ii)= calczforce(*(R+ii),*(z+ii),0.,0.,npot,potentialArgs); } free_potentialArgs(npot,potentialArgs); free(potentialArgs); }
reduction2.c
#include <omp.h> #include <stdio.h> #define SIZE 1000000 main () { int i, n, chunk; float a[SIZE], b[SIZE], result; /* Some initializations */ n = SIZE; chunk = 10; result = 0.0; for (i=0; i < n; i++) { a[i] = i * 1.0; b[i] = i * 2.0; } #pragma omp parallel for \ default(shared) private(i) \ schedule(static,chunk) \ reduction(+:result) for (i=0; i < n; i++) result = result + (a[i] * b[i]); printf("Final result= %f\n",result); }
header.h
//--------------------------------------------------------------------- //--------------------------------------------------------------------- // // header.h // //--------------------------------------------------------------------- //--------------------------------------------------------------------- #ifndef __HEADER_H #define __HEADER_H //--------------------------------------------------------------------- // The following include file is generated automatically by the // "setparams" utility. It defines // maxcells: the square root of the maximum number of processors // 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 "npbparams.h" #include "RCCE.h" //we introduce the next definition to avoid confusing the compiler, which //sometimes thinks the variable class is a reserved word #define class _class_ #include "common.h" #define AA 0 #define BB 1 #define CC 2 #define BLOCK_SIZE 5 #define EAST 2000 #define WEST 3000 #define NORTH 4000 #define SOUTH 5000 #define BOTTOM 6000 #define TOP 7000 #define WESTDIR 0 #define EASTDIR 1 #define SOUTHDIR 2 #define NORTHDIR 3 #define BOTTOMDIR 4 #define TOPDIR 5 #define MAX_CELL_DIM ((PROBLEM_SIZE/MAXCELLS)+1) #define IMAX MAX_CELL_DIM #define JMAX MAX_CELL_DIM #define KMAX MAX_CELL_DIM #define BUF_SIZE (MAX_CELL_DIM*MAX_CELL_DIM*(MAXCELLS-1)*60+1) #define SQR(x) (x)*(x) #define grid_points(m) grid_points[m-1] #define ce(m,n) ce[(m-1)+5*(n-1)] #define cell_coord(m,n) cell_coord[(m-1)+3*(n-1)] #define cell_low(m,n) cell_low[(m-1)+3*(n-1)] #define cell_high(m,n) cell_high[(m-1)+3*(n-1)] #define cell_size(m,n) cell_size[(m-1)+3*(n-1)] #define predecessor(m) predecessor[m-1] #define slice(m,n) slice[(m-1)+3*(n-1)] #define grid_size(m) grid_size[m-1] #define successor(m) successor[m-1] #define start(m,n) start[(m-1)+3*(n-1)] #define end(m,n) end[(m-1)+3*(n-1)] #define us(i,j,k,c) us[(i+1)+(IMAX+2)*((j+1)+(JMAX+2)*((k+1)+(KMAX+2)*(c-1)))] #define vs(i,j,k,c) vs[(i+1)+(IMAX+2)*((j+1)+(JMAX+2)*((k+1)+(KMAX+2)*(c-1)))] #define ws(i,j,k,c) ws[(i+1)+(IMAX+2)*((j+1)+(JMAX+2)*((k+1)+(KMAX+2)*(c-1)))] #define qs(i,j,k,c) qs[(i+1)+(IMAX+2)*((j+1)+(JMAX+2)*((k+1)+(KMAX+2)*(c-1)))] #define rho_i(i,j,k,c) rho_i[(i+1)+(IMAX+2)*((j+1)+(JMAX+2)*((k+1)+(KMAX+2)*(c-1)))] #define square(i,j,k,c) square[(i+1)+(IMAX+2)*((j+1)+(JMAX+2)*((k+1)+(KMAX+2)*(c-1)))] #define forcing(m,i,j,k,c) forcing[(m-1)+5*(i+IMAX*(j+JMAX*(k+KMAX*(c-1))))] #define u(m,i,j,k,c) u[(m-1)+5*((i+2)+(IMAX+4)*((j+2)+(JMAX+4)*((k+2)+(KMAX+4)*(c-1))))] #define rhs(m,i,j,k,c) rhs[(m-1)+5*((i+1)+(IMAX+1)*((j+1)+(JMAX+1)*((k+1)+(KMAX+1)*(c-1))))] #define lhsc(m,n,i,j,k,c) lhsc[(m-1)+5*((n-1)+5*((i+1)+(IMAX+1)*((j+1)+(JMAX+1)*((k+1)+(KMAX+1)*(c-1)))))] #define backsub_info(m,i,j,c) backsub_info[(m-1)+5*((i)+(IMAX+1)*((j)+(JMAX+1)*(c-1)))] #define in_buffer(i) in_buffer[i-1] #define out_buffer(i) out_buffer[i-1] #define cv(m) cv[m+2] #define rhon(m) rhon[m+2] #define rhos(m) rhos[m+2] #define rhoq(m) rhoq[m+2] #define cuf(m) cuf[m+2] #define q(m) q[m+2] #define ue(m,n) ue[(m+2)+(MAX_CELL_DIM+4)*(n-1)] #define buf(m,n) buf[(m+2)+(MAX_CELL_DIM+4)*(n-1)] #define sum(m) sum[m-1] #define xce_sub(m) xce_sub[m-1] #ifdef G_MAIN int ncells, grid_points[3]; double elapsed_time; double tx1, tx2, tx3, ty1, ty2, ty3, tz1, tz2, tz3, dx1, dx2, dx3, dx4, dx5, dy1, dy2, dy3, dy4, dy5, dz1, dz2, dz3, dz4, dz5, dssp, dt, ce[5*13], dxmax, dymax, dzmax, xxcon1, xxcon2, xxcon3, xxcon4, xxcon5, dx1tx1, dx2tx1, dx3tx1, dx4tx1, dx5tx1, yycon1, yycon2, yycon3, yycon4, yycon5, dy1ty1, dy2ty1, dy3ty1, dy4ty1, dy5ty1, zzcon1, zzcon2, zzcon3, zzcon4, zzcon5, dz1tz1, dz2tz1, dz3tz1, dz4tz1, dz5tz1, dnxm1, dnym1, dnzm1, c1c2, c1c5, c3c4, c1345, conz1, c1, c2, c3, c4, c5, c4dssp, c5dssp, dtdssp, dttx1, bt, dttx2, dtty1, dtty2, dttz1, dttz2, c2dttx1, c2dtty1, c2dttz1, comz1, comz4, comz5, comz6, c3c4tx3, c3c4ty3, c3c4tz3, c2iv, con43, con16; int cell_coord[MAXCELLS*3], cell_low[MAXCELLS*3], cell_high[MAXCELLS*3], cell_size[MAXCELLS*3], predecessor[3], slice[MAXCELLS*3], grid_size[3], successor[3], start[MAXCELLS*3], end[MAXCELLS*3]; double us [(IMAX+2)*(JMAX+2)*(KMAX+2)*MAXCELLS], vs [(IMAX+2)*(JMAX+2)*(KMAX+2)*MAXCELLS], ws [(IMAX+2)*(JMAX+2)*(KMAX+2)*MAXCELLS], qs [(IMAX+2)*(JMAX+2)*(KMAX+2)*MAXCELLS], rho_i [(IMAX+2)*(JMAX+2)*(KMAX+2)*MAXCELLS], square [(IMAX+2)*(JMAX+2)*(KMAX+2)*MAXCELLS], forcing [5*IMAX*JMAX*KMAX*MAXCELLS], u [5*(IMAX+4)*(JMAX+4)*(KMAX+4)*MAXCELLS], rhs [5*(IMAX+1)*(JMAX+1)*(KMAX+1)*MAXCELLS], lhsc [5*5*(IMAX+1)*(JMAX+1)*(KMAX+1)*MAXCELLS], backsub_info [5*(MAX_CELL_DIM+1)*(MAX_CELL_DIM+1)*MAXCELLS], in_buffer[BUF_SIZE], out_buffer[BUF_SIZE]; double cv[MAX_CELL_DIM+4], rhon[MAX_CELL_DIM+4], rhos[MAX_CELL_DIM+4], rhoq[MAX_CELL_DIM+4], cuf[MAX_CELL_DIM+4], q[MAX_CELL_DIM+4], ue[(MAX_CELL_DIM+4)*5], buf[(MAX_CELL_DIM+4)*5]; int west_size, east_size, bottom_size, top_size, north_size, south_size, start_send_west, start_send_east, start_send_south, start_send_north, start_send_bottom, start_send_top, start_recv_west, start_recv_east, start_recv_south, start_recv_north, start_recv_bottom, start_recv_top; // // These are used by btio // int collbuf_nodes, collbuf_size, iosize, idump, record_length, idump_sub, rd_interval; double sum[NITER_DEFAULT], xce_sub[5]; long int iseek; int send_color[6], recv_color[6]; #else extern int ncells, grid_points[3]; extern double elapsed_time; extern double tx1, tx2, tx3, ty1, ty2, ty3, tz1, tz2, tz3, dx1, dx2, dx3, dx4, dx5, dy1, dy2, dy3, dy4, dy5, dz1, dz2, dz3, dz4, dz5, dssp, dt, ce[5*13], dxmax, dymax, dzmax, xxcon1, xxcon2, xxcon3, xxcon4, xxcon5, dx1tx1, dx2tx1, dx3tx1, dx4tx1, dx5tx1, yycon1, yycon2, yycon3, yycon4, yycon5, dy1ty1, dy2ty1, dy3ty1, dy4ty1, dy5ty1, zzcon1, zzcon2, zzcon3, zzcon4, zzcon5, dz1tz1, dz2tz1, dz3tz1, dz4tz1, dz5tz1, dnxm1, dnym1, dnzm1, c1c2, c1c5, c3c4, c1345, conz1, c1, c2, c3, c4, c5, c4dssp, c5dssp, dtdssp, dttx1, bt, dttx2, dtty1, dtty2, dttz1, dttz2, c2dttx1, c2dtty1, c2dttz1, comz1, comz4, comz5, comz6, c3c4tx3, c3c4ty3, c3c4tz3, c2iv, con43, con16; extern int cell_coord[MAXCELLS*3], cell_low[MAXCELLS*3], cell_high[MAXCELLS*3], cell_size[MAXCELLS*3], predecessor[3], slice[MAXCELLS*3], grid_size[3], successor[3], start[MAXCELLS*3], end[MAXCELLS*3]; extern double us [(IMAX+2)*(JMAX+2)*(KMAX+2)*MAXCELLS], vs [(IMAX+2)*(JMAX+2)*(KMAX+2)*MAXCELLS], ws [(IMAX+2)*(JMAX+2)*(KMAX+2)*MAXCELLS], qs [(IMAX+2)*(JMAX+2)*(KMAX+2)*MAXCELLS], rho_i [(IMAX+2)*(JMAX+2)*(KMAX+2)*MAXCELLS], square [(IMAX+2)*(JMAX+2)*(KMAX+2)*MAXCELLS], forcing [5*IMAX*JMAX*KMAX*MAXCELLS], u [5*(IMAX+4)*(JMAX+4)*(KMAX+4)*MAXCELLS], rhs [5*(IMAX+1)*(JMAX+1)*(KMAX+1)*MAXCELLS], lhsc [5*5*(IMAX+1)*(JMAX+1)*(KMAX+1)*MAXCELLS], backsub_info [5*(MAX_CELL_DIM+1)*(MAX_CELL_DIM+1)*MAXCELLS], in_buffer[BUF_SIZE], out_buffer[BUF_SIZE]; extern double cv[MAX_CELL_DIM+4], rhon[MAX_CELL_DIM+4], rhos[MAX_CELL_DIM+4], rhoq[MAX_CELL_DIM+4], cuf[MAX_CELL_DIM+4], q[MAX_CELL_DIM+4], ue[(MAX_CELL_DIM+4)*5], buf[(MAX_CELL_DIM+4)*5]; extern int west_size, east_size, bottom_size, top_size, north_size, south_size, start_send_west, start_send_east, start_send_south, start_send_north, start_send_bottom, start_send_top, start_recv_west, start_recv_east, start_recv_south, start_recv_north, start_recv_bottom, start_recv_top; // // These are used by btio // extern int collbuf_nodes, collbuf_size, iosize, idump, record_length, idump_sub, rd_interval; extern double sum[NITER_DEFAULT], xce_sub[5]; extern long int iseek; extern int send_color[6], recv_color[6]; #endif /*G_MAIN*/ extern void matvec_sub(double ablock[], double avec[], double bvec[]); extern void matmul_sub(double ablock[], double bblock[], double cblock[]); extern void binvcrhs( double lhs[], double c[], double r[] ); extern void binvrhs( double lhs[], double r[] ); extern void exact_solution(double xi,double eta,double zeta,double dtemp[]); extern int setup_mpi(int *argc, char ***argv); extern void make_set(void); extern void set_constants(void); extern void lhsinit(void); extern void lhsabinit(double lhsa[], double lhsb[], int size); extern void initialize(void); extern void exact_rhs(void); extern void compute_buffer_size(int c); extern void adi(void); extern void compute_rhs(void); extern void copy_faces(void); extern void x_solve(void); extern void y_solve(void); extern void z_solve(void); extern void add(void); extern void verify(int niter, char *class, int *verified); extern void error_norm(double rms[]); extern void rhs_norm(double rms[]); extern void setup_btio(void); extern void output_timestep(void); extern void btio_cleanup(void); extern void btio_verify(int *verified); extern void accumulate_norms(double xce[]); extern void clear_timestep(void); #endif #ifdef _OPENMP #pragma omp threadprivate (cell_coord, cell_low, cell_high, cell_size) #pragma omp threadprivate (predecessor, slice, grid_size, successor) #pragma omp threadprivate (start, end) #pragma omp threadprivate (ncells, grid_points, elapsed_time) #pragma omp threadprivate (tx1, tx2, tx3, ty1, ty2, ty3, tz1, tz2, tz3, \ dx1, dx2, dx3, dx4, dx5, dy1, dy2, dy3, dy4, \ dy5, dz1, dz2, dz3, dz4, dz5, dssp, dt, \ ce, dxmax, dymax, dzmax, xxcon1, xxcon2, \ xxcon3, xxcon4, xxcon5, dx1tx1, dx2tx1, dx3tx1, \ dx4tx1, dx5tx1, yycon1, yycon2, yycon3, yycon4, \ yycon5, dy1ty1, dy2ty1, dy3ty1, dy4ty1, dy5ty1, \ zzcon1, zzcon2, zzcon3, zzcon4, zzcon5, dz1tz1, \ dz2tz1, dz3tz1, dz4tz1, dz5tz1, dnxm1, dnym1, \ dnzm1, c1c2, c1c5, c3c4, c1345, conz1, c1, c2, \ c3, c4, c5, c4dssp, c5dssp, dtdssp, dttx1, bt, \ dttx2, dtty1, dtty2, dttz1, dttz2, c2dttx1, \ c2dtty1, c2dttz1, comz1, comz4, comz5, comz6, \ c3c4tx3, c3c4ty3, c3c4tz3, c2iv, con43, con16) #pragma omp threadprivate (us, vs, ws, qs, rho_i, square, forcing, \ u, rhs, lhsc, backsub_info, in_buffer, out_buffer) #pragma omp threadprivate (cv, rhon, rhos, rhoq, cuf, q, ue, buf) #pragma omp threadprivate (west_size, east_size, bottom_size, top_size, \ north_size, south_size, start_send_west, \ start_send_east, start_send_south, start_send_north, \ start_send_bottom, start_send_top, start_recv_west, \ start_recv_east, start_recv_south, start_recv_north, \ start_recv_bottom, start_recv_top, send_color, recv_color) // // These are used by btio // #pragma omp threadprivate (collbuf_nodes, collbuf_size, iosize, idump,\ record_length, idump_sub, rd_interval, \ sum, xce_sub, iseek) #endif
single3.c
/* */ #include <stdio.h> #include <omp.h> #include<assert.h> int a; int b; int main(void) { #pragma omp parallel { #pragma omp single { int num_threads = 2; } #pragma omp single nowait copyprivate(a,b) { int num_threads = 3; } } return 0; }
dcsc.h
/****************************************************************/ /* Parallel Combinatorial BLAS Library (for Graph Computations) */ /* version 1.6 -------------------------------------------------*/ /* date: 6/15/2017 ---------------------------------------------*/ /* authors: Ariful Azad, Aydin Buluc --------------------------*/ /****************************************************************/ /* Copyright (c) 2010-2017, The Regents of the University of California Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _DCSC_H #define _DCSC_H #include <cstdlib> #include <vector> #include <limits> #include <cassert> #include "SpDefs.h" #include "SpHelper.h" #include "StackEntry.h" #include "MemoryPool.h" #include "promote.h" namespace combblas { template <class IT, class NT> class Dcsc { public: typedef NT value_type; typedef IT index_type; Dcsc (); Dcsc (IT nnz, IT nzcol); Dcsc (IT nnz, const std::vector<IT> & indices, bool isRow); //!< Create a logical matrix from (row/column) indices vector Dcsc (StackEntry<NT, std::pair<IT,IT> > * multstack, IT mdim, IT ndim, IT nnz); Dcsc (const Dcsc<IT,NT> & rhs); // copy constructor Dcsc<IT,NT> & operator=(const Dcsc<IT,NT> & rhs); // assignment operator Dcsc<IT,NT> & operator+=(const Dcsc<IT,NT> & rhs); // add and assign operator ~Dcsc(); bool operator==(const Dcsc<IT,NT> & rhs); template <typename NNT> operator Dcsc<IT,NNT>() const; //<! numeric type conversion template <typename NIT, typename NNT> operator Dcsc<NIT,NNT>() const; //<! index+numeric type conversion void EWiseMult(const Dcsc<IT,NT> & rhs, bool exclude); void EWiseScale(NT ** scaler); //<! scale elements of "this" with the elements dense rhs matrix template <typename IU, typename NU1, typename NU2> friend Dcsc<IU, typename promote_trait<NU1,NU2>::T_promote> EWiseMult(const Dcsc<IU,NU1> & A, const Dcsc<IU,NU2> * B, bool exclude); // Note that the second parameter is a POINTER template <typename _UnaryOperation> void Apply(_UnaryOperation __unary_op) { //transform(numx, numx+nz, numx, __unary_op); #ifdef _OPENMP #pragma omp parallel for #endif for(IT i=0; i < nz; ++i) numx[i] = __unary_op(numx[i]); } template <typename _UnaryOperation, typename GlobalIT> Dcsc<IT,NT>* PruneI(_UnaryOperation __unary_op, bool inPlace, GlobalIT rowOffset, GlobalIT colOffset); template <typename _UnaryOperation> Dcsc<IT,NT>* Prune(_UnaryOperation __unary_op, bool inPlace); template <typename _BinaryOperation> Dcsc<IT,NT>* PruneColumn(NT* pvals, _BinaryOperation __binary_op, bool inPlace); template <typename _BinaryOperation> Dcsc<IT,NT>* PruneColumn(IT* pinds, NT* pvals, _BinaryOperation __binary_op, bool inPlace); IT AuxIndex(const IT colind, bool & found, IT * aux, IT csize) const; void RowSplit(int numsplits); void ColSplit(std::vector< Dcsc<IT,NT>* > & parts, std::vector<IT> & cuts); void ColConcatenate(std::vector< Dcsc<IT,NT>* > & parts, std::vector<IT> & offsets); void Split(Dcsc<IT,NT> * & A, Dcsc<IT,NT> * & B, IT cut); //! \todo{special case of ColSplit, to be deprecated...} void Merge(const Dcsc<IT,NT> * Adcsc, const Dcsc<IT,NT> * B, IT cut); //! \todo{special case of ColConcatenate, to be deprecated...} IT ConstructAux(IT ndim, IT * & aux) const; void Resize(IT nzcnew, IT nznew); template<class VT> void FillColInds(const VT * colnums, IT nind, std::vector< std::pair<IT,IT> > & colinds, IT * aux, IT csize) const; Dcsc<IT,NT> & AddAndAssign (StackEntry<NT, std::pair<IT,IT> > * multstack, IT mdim, IT ndim, IT nnz); template <typename _BinaryOperation> void UpdateDense(NT ** array, _BinaryOperation __binary_op) const; // update dense 2D array's entries with __binary_op using elements of "this" //! wrap object around pre-allocated arrays (possibly RDMA registered) Dcsc (IT * _cp, IT * _jc, IT * _ir, NT * _numx, IT _nz, IT _nzc, bool _memowned = true) : cp(_cp), jc(_jc), ir(_ir), numx(_numx), nz(_nz), nzc(_nzc), memowned(_memowned) {}; IT * cp; //!< The master array, size nzc+1 (keeps column pointers) IT * jc ; //!< col indices, size nzc IT * ir ; //!< row indices, size nz NT * numx; //!< generic values, size nz IT nz; IT nzc; //!< number of columns with at least one non-zero in them bool memowned; private: void getindices (StackEntry<NT, std::pair<IT,IT> > * multstack, IT & rindex, IT & cindex, IT & j, IT nnz); }; } #include "../src/dcsc.cpp" #endif
lai.c
#include<stdio.h> #include "gdal.h" #include<omp.h> #include "cpl_string.h" /* mcd15A3 MODLAND_QC bits [0-1] * 0 -> class 0: LAI produced, Good quality (main algorithm with or without saturation) * 1 -> class 1: LAI produced, Other Quality (back-up algorithm or fill values) */ #define NODATA 255 #define Null 1000000000 int mcd15A3a(int pixel) { return (pixel & 0x01); } void usage() { printf( "-----------------------------------------\n"); printf( "--Modis Processing chain--OpenMP code----\n"); printf( "-----------------------------------------\n"); printf( "./lai inLAI inLAI_QA\n"); printf( "\toutLAI\n"); printf( "\t[Offset Scale]\n"); printf( "-----------------------------------------\n"); printf( "inLAI\t\tModis MCD15A3 LAI 1000m\n"); printf( "inLAI_QA\t\tModis MCD15A3 FparLai_QC\n"); printf( "outLAI\tQA corrected LAI output [-]\n"); printf( "Offset\t Optional offset (DN2LAI)\n"); printf( "Scale\t Optional scale (DN2LAI)\n"); return; } int main( int argc, char *argv[] ) { if( argc < 4 ) { usage(); return 1; } char *inB2 = argv[1]; //LAI char *inB3 = argv[2]; //LAI_QA char *laiF = argv[3]; // Corrected LAI float offset=Null, scale=Null; if(argv[4] != NULL && argv[5] != NULL){ offset = atof(argv[4]); // Optional Offset (offset+DN*scale) scale = atof(argv[5]); // Optional scale (offset+DN*scale) } GDALAllRegister(); GDALDatasetH hD2 = GDALOpen(inB2,GA_ReadOnly);//LAI GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//LAI_QA if(hD2==NULL||hD3==NULL){ printf("One or more input files "); printf("could not be loaded\n"); exit(1); } GDALDriverH hDr2 = GDALGetDatasetDriver(hD2); char **options = NULL; //options = CSLSetNameValue( options, "TILED", "YES" ); //options = CSLSetNameValue( options, "COMPRESS", "DEFLATE" ); //options = CSLSetNameValue( options, "PREDICTOR", "2" ); GDALDatasetH hDOut = GDALCreateCopy(hDr2,laiF,hD2,FALSE,options,NULL,NULL); GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1); GDALSetRasterNoDataValue(hBOut, NODATA); GDALRasterBandH hB2 = GDALGetRasterBand(hD2,1);//LAI GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//LAI_QA int nX = GDALGetRasterBandXSize(hB2); int nY = GDALGetRasterBandYSize(hB2); int N=nX*nY; float *l2 = (float *) malloc(sizeof(float)*N); float *l3 = (float *) malloc(sizeof(float)*N); float *lOut = (float *) malloc(sizeof(float)*N); int rc, qa; //LAI 1Km int err = 0; err=GDALRasterIO(hB2,GF_Read,0,0,nX,nY,l2,nX,nY,GDT_Float32,0,0); //LAI_QA 1Km err=GDALRasterIO(hB3,GF_Read,0,0,nX,nY,l3,nX,nY,GDT_Float32,0,0); #pragma omp parallel for default(none) \ private (rc, qa) shared (N, l2, l3, lOut, offset, scale) for(rc=0;rc<N;rc++){ qa=mcd15A3a(l3[rc]); if( qa != 0) lOut[rc] = NODATA; if(offset!=Null && scale!=Null){ lOut[rc] = offset + l2[rc] * scale; } else lOut[rc] = l2[rc]; } #pragma omp barrier err=GDALRasterIO(hBOut,GF_Write,0,0,nX,nY,lOut,nX,nY,GDT_Float32,0,0); err=err+1; if( l2 != NULL ) free( l2 ); if( l3 != NULL ) free( l3 ); GDALClose(hD2); GDALClose(hD3); GDALClose(hDOut); return(EXIT_SUCCESS); }
threadprivate.c
#include <stdio.h> #include <omp.h> int counter = 0; #pragma omp threadprivate(counter) int increment_counter(){ return ++counter; } int main(){ #pragma omp parallel { int id = omp_get_thread_num(); counter = increment_counter(); } printf("%d\n", counter); }
profile.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP RRRR OOO FFFFF IIIII L EEEEE % % P P R R O O F I L E % % PPPP RRRR O O FFF I L EEE % % P R R O O F I L E % % P R R OOO F IIIII LLLLL EEEEE % % % % % % MagickCore Image Profile Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/colorspace-private.h" #include "magick/configure.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/hashmap.h" #include "magick/image.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/option-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/splay-tree.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/token.h" #include "magick/utility.h" #if defined(MAGICKCORE_LCMS_DELEGATE) #if defined(MAGICKCORE_HAVE_LCMS_LCMS2_H) #include <wchar.h> #include <lcms/lcms2.h> #else #include <wchar.h> #include "lcms2.h" #endif #endif #if defined(MAGICKCORE_XML_DELEGATE) # if defined(MAGICKCORE_WINDOWS_SUPPORT) # if !defined(__MINGW32__) # include <win32config.h> # endif # endif # include <libxml/parser.h> # include <libxml/tree.h> #endif /* Forward declarations */ static MagickBooleanType SetImageProfileInternal(Image *,const char *,const StringInfo *, const MagickBooleanType); static void WriteTo8BimProfile(Image *,const char*,const StringInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageProfiles() clones one or more image profiles. % % The format of the CloneImageProfiles method is: % % MagickBooleanType CloneImageProfiles(Image *image, % const Image *clone_image) % % A description of each parameter follows: % % o image: the image. % % o clone_image: the clone image. % */ MagickExport MagickBooleanType CloneImageProfiles(Image *image, const Image *clone_image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clone_image != (const Image *) NULL); assert(clone_image->signature == MagickCoreSignature); image->color_profile.length=clone_image->color_profile.length; image->color_profile.info=clone_image->color_profile.info; image->iptc_profile.length=clone_image->iptc_profile.length; image->iptc_profile.info=clone_image->iptc_profile.info; if (clone_image->profiles != (void *) NULL) { if (image->profiles != (void *) NULL) DestroyImageProfiles(image); image->profiles=CloneSplayTree((SplayTreeInfo *) clone_image->profiles, (void *(*)(void *)) ConstantString,(void *(*)(void *)) CloneStringInfo); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageProfile() deletes a profile from the image by its name. % % The format of the DeleteImageProfile method is: % % MagickBooleanTyupe DeleteImageProfile(Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport MagickBooleanType DeleteImageProfile(Image *image,const char *name) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return(MagickFalse); if (LocaleCompare(name,"icc") == 0) { /* Continue to support deprecated color profile for now. */ image->color_profile.length=0; image->color_profile.info=(unsigned char *) NULL; } if (LocaleCompare(name,"iptc") == 0) { /* Continue to support deprecated IPTC profile for now. */ image->iptc_profile.length=0; image->iptc_profile.info=(unsigned char *) NULL; } WriteTo8BimProfile(image,name,(StringInfo *) NULL); return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->profiles,name)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageProfiles() releases memory associated with an image profile map. % % The format of the DestroyProfiles method is: % % void DestroyImageProfiles(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImageProfiles(Image *image) { if (image->profiles != (SplayTreeInfo *) NULL) image->profiles=DestroySplayTree((SplayTreeInfo *) image->profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageProfile() gets a profile associated with an image by name. % % The format of the GetImageProfile method is: % % const StringInfo *GetImageProfile(const Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport const StringInfo *GetImageProfile(const Image *image, const char *name) { const StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((StringInfo *) NULL); profile=(const StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,name); return(profile); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImageProfile() gets the next profile name for an image. % % The format of the GetNextImageProfile method is: % % char *GetNextImageProfile(const Image *image) % % A description of each parameter follows: % % o hash_info: the hash info. % */ MagickExport char *GetNextImageProfile(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((char *) NULL); return((char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->profiles)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P r o f i l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ProfileImage() associates, applies, or removes an ICM, IPTC, or generic % profile with / to / from an image. If the profile is NULL, it is removed % from the image otherwise added or applied. Use a name of '*' and a profile % of NULL to remove all profiles from the image. % % ICC and ICM profiles are handled as follows: If the image does not have % an associated color profile, the one you provide is associated with the % image and the image pixels are not transformed. Otherwise, the colorspace % transform defined by the existing and new profile are applied to the image % pixels and the new profile is associated with the image. % % The format of the ProfileImage method is: % % MagickBooleanType ProfileImage(Image *image,const char *name, % const void *datum,const size_t length,const MagickBooleanType clone) % % A description of each parameter follows: % % o image: the image. % % o name: Name of profile to add or remove: ICC, IPTC, or generic profile. % % o datum: the profile data. % % o length: the length of the profile. % % o clone: should be MagickFalse. % */ #if defined(MAGICKCORE_LCMS_DELEGATE) typedef struct _LCMSInfo { ColorspaceType colorspace; cmsUInt32Number type; size_t channels; cmsHPROFILE profile; int intent; double **magick_restrict pixels, scale, translate; } LCMSInfo; #if LCMS_VERSION < 2060 static void* cmsGetContextUserData(cmsContext ContextID) { return(ContextID); } static cmsContext cmsCreateContext(void *magick_unused(Plugin),void *UserData) { magick_unreferenced(Plugin); return((cmsContext) UserData); } static void cmsSetLogErrorHandlerTHR(cmsContext magick_unused(ContextID), cmsLogErrorHandlerFunction Fn) { magick_unreferenced(ContextID); cmsSetLogErrorHandler(Fn); } static void cmsDeleteContext(cmsContext magick_unused(ContextID)) { magick_unreferenced(ContextID); } #endif static double **DestroyPixelThreadSet(double **pixels) { register ssize_t i; if (pixels == (double **) NULL) return((double **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (double *) NULL) pixels[i]=(double *) RelinquishMagickMemory(pixels[i]); pixels=(double **) RelinquishMagickMemory(pixels); return(pixels); } static double **AcquirePixelThreadSet(const size_t columns, const size_t channels) { double **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(double **) AcquireQuantumMemory(number_threads,sizeof(*pixels)); if (pixels == (double **) NULL) return((double **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(double *) AcquireQuantumMemory(columns,channels* sizeof(**pixels)); if (pixels[i] == (double *) NULL) return(DestroyPixelThreadSet(pixels)); } return(pixels); } static cmsHTRANSFORM *DestroyTransformThreadSet(cmsHTRANSFORM *transform) { register ssize_t i; assert(transform != (cmsHTRANSFORM *) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (transform[i] != (cmsHTRANSFORM) NULL) cmsDeleteTransform(transform[i]); transform=(cmsHTRANSFORM *) RelinquishMagickMemory(transform); return(transform); } static cmsHTRANSFORM *AcquireTransformThreadSet(const LCMSInfo *source_info, const LCMSInfo *target_info,const cmsUInt32Number flags, cmsContext cms_context) { cmsHTRANSFORM *transform; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); transform=(cmsHTRANSFORM *) AcquireQuantumMemory(number_threads, sizeof(*transform)); if (transform == (cmsHTRANSFORM *) NULL) return((cmsHTRANSFORM *) NULL); (void) memset(transform,0,number_threads*sizeof(*transform)); for (i=0; i < (ssize_t) number_threads; i++) { transform[i]=cmsCreateTransformTHR(cms_context,source_info->profile, source_info->type,target_info->profile,target_info->type, target_info->intent,flags); if (transform[i] == (cmsHTRANSFORM) NULL) return(DestroyTransformThreadSet(transform)); } return(transform); } static void LCMSExceptionHandler(cmsContext context,cmsUInt32Number severity, const char *message) { Image *image; (void) LogMagickEvent(TransformEvent,GetMagickModule(),"lcms: #%u, %s", severity,message != (char *) NULL ? message : "no message"); image=(Image *) cmsGetContextUserData(context); if (image != (Image *) NULL) (void) ThrowMagickException(&image->exception,GetMagickModule(), ImageWarning,"UnableToTransformColorspace","`%s'",image->filename); } #endif static MagickBooleanType SetsRGBImageProfile(Image *image) { static unsigned char sRGBProfile[] = { 0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00, 0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20, 0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a, 0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99, 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67, 0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70, 0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88, 0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c, 0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24, 0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24, 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14, 0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14, 0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14, 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14, 0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d, 0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65, 0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e, 0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00, 0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c, 0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2, 0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d, 0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0, 0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87, 0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4, 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19, 0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37, 0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54, 0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72, 0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90, 0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae, 0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb, 0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb, 0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d, 0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32, 0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59, 0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83, 0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1, 0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1, 0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14, 0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b, 0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84, 0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1, 0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00, 0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43, 0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a, 0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3, 0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20, 0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71, 0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4, 0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c, 0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77, 0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5, 0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37, 0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d, 0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07, 0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74, 0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5, 0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a, 0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2, 0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f, 0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf, 0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54, 0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc, 0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69, 0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9, 0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e, 0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26, 0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3, 0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64, 0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09, 0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3, 0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61, 0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13, 0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9, 0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84, 0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43, 0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06, 0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce, 0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b, 0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c, 0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41, 0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b, 0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa, 0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd, 0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5, 0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2, 0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3, 0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99, 0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94, 0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94, 0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98, 0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1, 0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf, 0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2, 0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda, 0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7, 0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18, 0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f, 0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b, 0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b, 0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1, 0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c, 0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c, 0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91, 0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb, 0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a, 0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f, 0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8, 0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37, 0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c, 0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05, 0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74, 0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8, 0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61, 0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0, 0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64, 0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee, 0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d, 0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12, 0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab, 0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b, 0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0, 0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a, 0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a, 0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00, 0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb, 0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c, 0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42, 0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f, 0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0, 0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8, 0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95, 0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78, 0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61, 0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f, 0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43, 0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d, 0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d, 0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43, 0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f, 0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60, 0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78, 0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95, 0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8, 0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1, 0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11, 0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46, 0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81, 0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2, 0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a, 0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57, 0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab, 0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04, 0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64, 0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca, 0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36, 0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8, 0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20, 0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f, 0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24, 0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf, 0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40, 0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8, 0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76, 0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a, 0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4, 0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75, 0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d, 0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea, 0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae, 0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79, 0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a, 0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21, 0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff, 0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3, 0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce, 0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf, 0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7, 0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5, 0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba, 0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6, 0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8, 0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1, 0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10, 0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36, 0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63, 0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96, 0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0, 0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11, 0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58, 0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7, 0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb, 0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57, 0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba, 0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff }; StringInfo *profile; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (GetImageProfile(image,"icc") != (const StringInfo *) NULL) return(MagickFalse); profile=AcquireStringInfo(sizeof(sRGBProfile)); SetStringInfoDatum(profile,sRGBProfile); status=SetImageProfile(image,"icc",profile); profile=DestroyStringInfo(profile); return(status); } MagickExport MagickBooleanType ProfileImage(Image *image,const char *name, const void *datum,const size_t length, const MagickBooleanType magick_unused(clone)) { #define GetLCMSPixel(source_info,pixel) \ (source_info.scale*QuantumScale*(pixel)+source_info.translate) #define ProfileImageTag "Profile/Image" #define SetLCMSPixel(target_info,pixel) \ ClampToQuantum(target_info.scale*QuantumRange*(pixel)+target_info.translate) #define ThrowProfileException(severity,tag,context) \ { \ if (cms_context != (cmsContext) NULL) \ cmsDeleteContext(cms_context); \ if (source_info.profile != (cmsHPROFILE) NULL) \ (void) cmsCloseProfile(source_info.profile); \ if (target_info.profile != (cmsHPROFILE) NULL) \ (void) cmsCloseProfile(target_info.profile); \ ThrowBinaryException(severity,tag,context); \ } MagickBooleanType status; StringInfo *profile; magick_unreferenced(clone); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(name != (const char *) NULL); if ((datum == (const void *) NULL) || (length == 0)) { char *next; /* Delete image profile(s). */ ResetImageProfileIterator(image); for (next=GetNextImageProfile(image); next != (const char *) NULL; ) { if (IsOptionMember(next,name) != MagickFalse) { (void) DeleteImageProfile(image,next); ResetImageProfileIterator(image); } next=GetNextImageProfile(image); } return(MagickTrue); } /* Add a ICC, IPTC, or generic profile to the image. */ status=MagickTrue; profile=AcquireStringInfo((size_t) length); SetStringInfoDatum(profile,(unsigned char *) datum); if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0)) status=SetImageProfile(image,name,profile); else { const StringInfo *icc_profile; icc_profile=GetImageProfile(image,"icc"); if ((icc_profile != (const StringInfo *) NULL) && (CompareStringInfo(icc_profile,profile) == 0)) { const char *value; value=GetImageProperty(image,"exif:ColorSpace"); (void) value; if (LocaleCompare(value,"1") != 0) (void) SetsRGBImageProfile(image); value=GetImageProperty(image,"exif:InteroperabilityIndex"); if (LocaleCompare(value,"R98.") != 0) (void) SetsRGBImageProfile(image); icc_profile=GetImageProfile(image,"icc"); } if ((icc_profile != (const StringInfo *) NULL) && (CompareStringInfo(icc_profile,profile) == 0)) { profile=DestroyStringInfo(profile); return(MagickTrue); } #if !defined(MAGICKCORE_LCMS_DELEGATE) (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (LCMS)", image->filename); #else { cmsContext cms_context; LCMSInfo source_info, target_info; /* Transform pixel colors as defined by the color profiles. */ cms_context=cmsCreateContext(NULL,image); if (cms_context == (cmsContext) NULL) ThrowBinaryImageException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); cmsSetLogErrorHandlerTHR(cms_context,LCMSExceptionHandler); source_info.profile=cmsOpenProfileFromMemTHR(cms_context, GetStringInfoDatum(profile),(cmsUInt32Number) GetStringInfoLength(profile)); if (source_info.profile == (cmsHPROFILE) NULL) { cmsDeleteContext(cms_context); ThrowBinaryImageException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); } if ((cmsGetDeviceClass(source_info.profile) != cmsSigLinkClass) && (icc_profile == (StringInfo *) NULL)) status=SetImageProfile(image,name,profile); else { CacheView *image_view; cmsColorSpaceSignature signature; cmsHTRANSFORM *magick_restrict transform; cmsUInt32Number flags; ExceptionInfo *exception; MagickOffsetType progress; ssize_t y; exception=(&image->exception); target_info.profile=(cmsHPROFILE) NULL; if (icc_profile != (StringInfo *) NULL) { target_info.profile=source_info.profile; source_info.profile=cmsOpenProfileFromMemTHR(cms_context, GetStringInfoDatum(icc_profile),(cmsUInt32Number) GetStringInfoLength(icc_profile)); if (source_info.profile == (cmsHPROFILE) NULL) ThrowProfileException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); } source_info.scale=1.0; source_info.translate=0.0; source_info.colorspace=sRGBColorspace; source_info.channels=3; switch (cmsGetColorSpace(source_info.profile)) { case cmsSigCmykData: { source_info.colorspace=CMYKColorspace; source_info.channels=4; source_info.type=(cmsUInt32Number) TYPE_CMYK_DBL; source_info.scale=100.0; break; } case cmsSigGrayData: { source_info.colorspace=GRAYColorspace; source_info.channels=1; source_info.type=(cmsUInt32Number) TYPE_GRAY_DBL; break; } case cmsSigLabData: { source_info.colorspace=LabColorspace; source_info.type=(cmsUInt32Number) TYPE_Lab_DBL; source_info.scale=100.0; source_info.translate=(-0.5); break; } case cmsSigRgbData: { source_info.colorspace=sRGBColorspace; source_info.type=(cmsUInt32Number) TYPE_RGB_DBL; break; } case cmsSigXYZData: { source_info.colorspace=XYZColorspace; source_info.type=(cmsUInt32Number) TYPE_XYZ_DBL; break; } default: ThrowProfileException(ImageError, "ColorspaceColorProfileMismatch",name); } signature=cmsGetPCS(source_info.profile); if (target_info.profile != (cmsHPROFILE) NULL) signature=cmsGetColorSpace(target_info.profile); target_info.scale=1.0; target_info.translate=0.0; target_info.channels=3; switch (signature) { case cmsSigCmykData: { target_info.colorspace=CMYKColorspace; target_info.channels=4; target_info.type=(cmsUInt32Number) TYPE_CMYK_DBL; target_info.scale=0.01; break; } case cmsSigGrayData: { target_info.colorspace=GRAYColorspace; target_info.channels=1; target_info.type=(cmsUInt32Number) TYPE_GRAY_DBL; break; } case cmsSigLabData: { target_info.colorspace=LabColorspace; target_info.type=(cmsUInt32Number) TYPE_Lab_DBL; target_info.scale=0.01; target_info.translate=0.5; break; } case cmsSigRgbData: { target_info.colorspace=sRGBColorspace; target_info.type=(cmsUInt32Number) TYPE_RGB_DBL; break; } case cmsSigXYZData: { target_info.colorspace=XYZColorspace; target_info.type=(cmsUInt32Number) TYPE_XYZ_DBL; break; } default: ThrowProfileException(ImageError, "ColorspaceColorProfileMismatch",name); } switch (image->rendering_intent) { case AbsoluteIntent: { target_info.intent=INTENT_ABSOLUTE_COLORIMETRIC; break; } case PerceptualIntent: { target_info.intent=INTENT_PERCEPTUAL; break; } case RelativeIntent: { target_info.intent=INTENT_RELATIVE_COLORIMETRIC; break; } case SaturationIntent: { target_info.intent=INTENT_SATURATION; break; } default: { target_info.intent=INTENT_PERCEPTUAL; break; } } flags=cmsFLAGS_HIGHRESPRECALC; #if defined(cmsFLAGS_BLACKPOINTCOMPENSATION) if (image->black_point_compensation != MagickFalse) flags|=cmsFLAGS_BLACKPOINTCOMPENSATION; #endif transform=AcquireTransformThreadSet(&source_info,&target_info, flags,cms_context); if (transform == (cmsHTRANSFORM *) NULL) ThrowProfileException(ImageError,"UnableToCreateColorTransform", name); /* Transform image as dictated by the source & target image profiles. */ source_info.pixels=AcquirePixelThreadSet(image->columns, source_info.channels); target_info.pixels=AcquirePixelThreadSet(image->columns, target_info.channels); if ((source_info.pixels == (double **) NULL) || (target_info.pixels == (double **) NULL)) { target_info.pixels=DestroyPixelThreadSet(target_info.pixels); source_info.pixels=DestroyPixelThreadSet(source_info.pixels); transform=DestroyTransformThreadSet(transform); ThrowProfileException(ResourceLimitError, "MemoryAllocationFailed",image->filename); } if (SetImageStorageClass(image,DirectClass) == MagickFalse) { target_info.pixels=DestroyPixelThreadSet(target_info.pixels); source_info.pixels=DestroyPixelThreadSet(source_info.pixels); transform=DestroyTransformThreadSet(transform); if (source_info.profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(source_info.profile); if (target_info.profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(target_info.profile); return(MagickFalse); } if (target_info.colorspace == CMYKColorspace) (void) SetImageColorspace(image,target_info.colorspace); progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register IndexPacket *magick_restrict indexes; register double *p; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); p=source_info.pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { *p++=GetLCMSPixel(source_info,GetPixelRed(q)); if (source_info.channels > 1) { *p++=GetLCMSPixel(source_info,GetPixelGreen(q)); *p++=GetLCMSPixel(source_info,GetPixelBlue(q)); } if (source_info.channels > 3) { *p=GetLCMSPixel(source_info,0); if (indexes != (IndexPacket *) NULL) *p=GetLCMSPixel(source_info,GetPixelIndex(indexes+x)); p++; } q++; } cmsDoTransform(transform[id],source_info.pixels[id], target_info.pixels[id],(unsigned int) image->columns); p=target_info.pixels[id]; q-=image->columns; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,SetLCMSPixel(target_info,*p)); SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); p++; if (target_info.channels > 1) { SetPixelGreen(q,SetLCMSPixel(target_info,*p)); p++; SetPixelBlue(q,SetLCMSPixel(target_info,*p)); p++; } if (target_info.channels > 3) { if (indexes != (IndexPacket *) NULL) SetPixelIndex(indexes+x,SetLCMSPixel(target_info,*p)); p++; } q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ProfileImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) SetImageColorspace(image,target_info.colorspace); switch (signature) { case cmsSigRgbData: { image->type=image->matte == MagickFalse ? TrueColorType : TrueColorMatteType; break; } case cmsSigCmykData: { image->type=image->matte == MagickFalse ? ColorSeparationType : ColorSeparationMatteType; break; } case cmsSigGrayData: { image->type=image->matte == MagickFalse ? GrayscaleType : GrayscaleMatteType; break; } default: break; } target_info.pixels=DestroyPixelThreadSet(target_info.pixels); source_info.pixels=DestroyPixelThreadSet(source_info.pixels); transform=DestroyTransformThreadSet(transform); if ((status != MagickFalse) && (cmsGetDeviceClass(source_info.profile) != cmsSigLinkClass)) status=SetImageProfile(image,name,profile); if (target_info.profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(target_info.profile); } (void) cmsCloseProfile(source_info.profile); cmsDeleteContext(cms_context); } #endif } profile=DestroyStringInfo(profile); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveImageProfile() removes a named profile from the image and returns its % value. % % The format of the RemoveImageProfile method is: % % void *RemoveImageProfile(Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport StringInfo *RemoveImageProfile(Image *image,const char *name) { StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((StringInfo *) NULL); if (LocaleCompare(name,"icc") == 0) { /* Continue to support deprecated color profile for now. */ image->color_profile.length=0; image->color_profile.info=(unsigned char *) NULL; } if (LocaleCompare(name,"iptc") == 0) { /* Continue to support deprecated IPTC profile for now. */ image->iptc_profile.length=0; image->iptc_profile.info=(unsigned char *) NULL; } WriteTo8BimProfile(image,name,(StringInfo *) NULL); profile=(StringInfo *) RemoveNodeFromSplayTree((SplayTreeInfo *) image->profiles,name); return(profile); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t P r o f i l e I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImageProfileIterator() resets the image profile iterator. Use it in % conjunction with GetNextImageProfile() to iterate over all the profiles % associated with an image. % % The format of the ResetImageProfileIterator method is: % % ResetImageProfileIterator(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void ResetImageProfileIterator(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return; ResetSplayTreeIterator((SplayTreeInfo *) image->profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageProfile() adds a named profile to the image. If a profile with the % same name already exists, it is replaced. This method differs from the % ProfileImage() method in that it does not apply CMS color profiles. % % The format of the SetImageProfile method is: % % MagickBooleanType SetImageProfile(Image *image,const char *name, % const StringInfo *profile) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name, for example icc, exif, and 8bim (8bim is the % Photoshop wrapper for iptc profiles). % % o profile: A StringInfo structure that contains the named profile. % */ static void *DestroyProfile(void *profile) { return((void *) DestroyStringInfo((StringInfo *) profile)); } static inline const unsigned char *ReadResourceByte(const unsigned char *p, unsigned char *quantum) { *quantum=(*p++); return(p); } static inline const unsigned char *ReadResourceLong(const unsigned char *p, unsigned int *quantum) { *quantum=(unsigned int) (*p++) << 24; *quantum|=(unsigned int) (*p++) << 16; *quantum|=(unsigned int) (*p++) << 8; *quantum|=(unsigned int) (*p++); return(p); } static inline const unsigned char *ReadResourceShort(const unsigned char *p, unsigned short *quantum) { *quantum=(unsigned short) (*p++) << 8; *quantum|=(unsigned short) (*p++); return(p); } static inline void WriteResourceLong(unsigned char *p, const unsigned int quantum) { unsigned char buffer[4]; buffer[0]=(unsigned char) (quantum >> 24); buffer[1]=(unsigned char) (quantum >> 16); buffer[2]=(unsigned char) (quantum >> 8); buffer[3]=(unsigned char) quantum; (void) memcpy(p,buffer,4); } static void WriteTo8BimProfile(Image *image,const char *name, const StringInfo *profile) { const unsigned char *datum, *q; register const unsigned char *p; size_t length; StringInfo *profile_8bim; ssize_t count; unsigned char length_byte; unsigned int value; unsigned short id, profile_id; if (LocaleCompare(name,"icc") == 0) profile_id=0x040f; else if (LocaleCompare(name,"iptc") == 0) profile_id=0x0404; else if (LocaleCompare(name,"xmp") == 0) profile_id=0x0424; else return; profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,"8bim"); if (profile_8bim == (StringInfo *) NULL) return; datum=GetStringInfoDatum(profile_8bim); length=GetStringInfoLength(profile_8bim); for (p=datum; p < (datum+length-16); ) { q=p; if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((count & 0x01) != 0) count++; if ((count < 0) || (p > (datum+length-count)) || (count > (ssize_t) length)) break; if (id != profile_id) p+=count; else { size_t extent, offset; ssize_t extract_extent; StringInfo *extract_profile; extract_extent=0; extent=(datum+length)-(p+count); if (profile == (StringInfo *) NULL) { offset=(q-datum); extract_profile=AcquireStringInfo(offset+extent); (void) memcpy(extract_profile->datum,datum,offset); } else { offset=(p-datum); extract_extent=profile->length; if ((extract_extent & 0x01) != 0) extract_extent++; extract_profile=AcquireStringInfo(offset+extract_extent+extent); (void) memcpy(extract_profile->datum,datum,offset-4); WriteResourceLong(extract_profile->datum+offset-4,(unsigned int) profile->length); (void) memcpy(extract_profile->datum+offset, profile->datum,profile->length); } (void) memcpy(extract_profile->datum+offset+extract_extent, p+count,extent); (void) AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString("8bim"),CloneStringInfo(extract_profile)); extract_profile=DestroyStringInfo(extract_profile); break; } } } static void GetProfilesFromResourceBlock(Image *image, const StringInfo *resource_block) { const unsigned char *datum; register const unsigned char *p; size_t length; ssize_t count; StringInfo *profile; unsigned char length_byte; unsigned int value; unsigned short id; datum=GetStringInfoDatum(resource_block); length=GetStringInfoLength(resource_block); for (p=datum; p < (datum+length-16); ) { if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((p > (datum+length-count)) || (count > (ssize_t) length) || (count < 0)) break; switch (id) { case 0x03ed: { unsigned int resolution; unsigned short units; /* Resolution. */ if (count < 10) break; p=ReadResourceLong(p,&resolution); image->x_resolution=((double) resolution)/65536.0; p=ReadResourceShort(p,&units)+2; p=ReadResourceLong(p,&resolution)+4; image->y_resolution=((double) resolution)/65536.0; /* Values are always stored as pixels per inch. */ if ((ResolutionType) units != PixelsPerCentimeterResolution) image->units=PixelsPerInchResolution; else { image->units=PixelsPerCentimeterResolution; image->x_resolution/=2.54; image->y_resolution/=2.54; } break; } case 0x0404: { /* IPTC Profile */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"iptc",profile,MagickTrue); profile=DestroyStringInfo(profile); p+=count; break; } case 0x040c: { /* Thumbnail. */ p+=count; break; } case 0x040f: { /* ICC Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"icc",profile,MagickTrue); profile=DestroyStringInfo(profile); p+=count; break; } case 0x0422: { /* EXIF Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"exif",profile,MagickTrue); profile=DestroyStringInfo(profile); p+=count; break; } case 0x0424: { /* XMP Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"xmp",profile,MagickTrue); profile=DestroyStringInfo(profile); p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } } #if defined(MAGICKCORE_XML_DELEGATE) static MagickBooleanType ValidateXMPProfile(const StringInfo *profile) { xmlDocPtr document; /* Parse XML profile. */ document=xmlReadMemory((const char *) GetStringInfoDatum(profile),(int) GetStringInfoLength(profile),"xmp.xml",NULL,XML_PARSE_NOERROR | XML_PARSE_NOWARNING); if (document == (xmlDocPtr) NULL) return(MagickFalse); xmlFreeDoc(document); return(MagickTrue); } #else static MagickBooleanType ValidateXMPProfile(const StringInfo *profile) { return(MagickFalse); } #endif static MagickBooleanType SetImageProfileInternal(Image *image,const char *name, const StringInfo *profile,const MagickBooleanType recursive) { char key[MaxTextExtent]; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((LocaleCompare(name,"xmp") == 0) && (ValidateXMPProfile(profile) == MagickFalse)) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ImageWarning,"CorruptImageProfile","`%s'",name); return(MagickTrue); } if (image->profiles == (SplayTreeInfo *) NULL) image->profiles=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, DestroyProfile); (void) CopyMagickString(key,name,MaxTextExtent); LocaleLower(key); status=AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString(key),CloneStringInfo(profile)); if ((status != MagickFalse) && ((LocaleCompare(name,"icc") == 0) || (LocaleCompare(name,"icm") == 0))) { const StringInfo *icc_profile; /* Continue to support deprecated color profile member. */ icc_profile=GetImageProfile(image,name); if (icc_profile != (const StringInfo *) NULL) { image->color_profile.length=GetStringInfoLength(icc_profile); image->color_profile.info=GetStringInfoDatum(icc_profile); } } if ((status != MagickFalse) && ((LocaleCompare(name,"iptc") == 0) || (LocaleCompare(name,"8bim") == 0))) { const StringInfo *iptc_profile; /* Continue to support deprecated IPTC profile member. */ iptc_profile=GetImageProfile(image,name); if (iptc_profile != (const StringInfo *) NULL) { image->iptc_profile.length=GetStringInfoLength(iptc_profile); image->iptc_profile.info=GetStringInfoDatum(iptc_profile); } } if (status != MagickFalse) { if (LocaleCompare(name,"8bim") == 0) GetProfilesFromResourceBlock(image,profile); else if (recursive == MagickFalse) WriteTo8BimProfile(image,name,profile); } return(status); } MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name, const StringInfo *profile) { return(SetImageProfileInternal(image,name,profile,MagickFalse)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImageProfiles() synchronizes image properties with the image profiles. % Currently we only support updating the EXIF resolution and orientation. % % The format of the SyncImageProfiles method is: % % MagickBooleanType SyncImageProfiles(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static inline int ReadProfileByte(unsigned char **p,size_t *length) { int c; if (*length < 1) return(EOF); c=(int) (*(*p)++); (*length)--; return(c); } static inline signed short ReadProfileShort(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } static inline signed int ReadProfileLong(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned int value; if (endian == LSBEndian) { value=(unsigned int) buffer[3] << 24; value|=(unsigned int) buffer[2] << 16; value|=(unsigned int) buffer[1] << 8; value|=(unsigned int) buffer[0]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } static inline signed int ReadProfileMSBLong(unsigned char **p,size_t *length) { signed int value; if (*length < 4) return(0); value=ReadProfileLong(MSBEndian,*p); (*length)-=4; *p+=4; return(value); } static inline signed short ReadProfileMSBShort(unsigned char **p, size_t *length) { signed short value; if (*length < 2) return(0); value=ReadProfileShort(MSBEndian,*p); (*length)-=2; *p+=2; return(value); } static inline void WriteProfileLong(const EndianType endian, const size_t value,unsigned char *p) { unsigned char buffer[4]; if (endian == LSBEndian) { buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); (void) memcpy(p,buffer,4); return; } buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; (void) memcpy(p,buffer,4); } static void WriteProfileShort(const EndianType endian, const unsigned short value,unsigned char *p) { unsigned char buffer[2]; if (endian == LSBEndian) { buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); (void) memcpy(p,buffer,2); return; } buffer[0]=(unsigned char) (value >> 8); buffer[1]=(unsigned char) value; (void) memcpy(p,buffer,2); } static MagickBooleanType Sync8BimProfile(Image *image,StringInfo *profile) { size_t length; ssize_t count; unsigned char *p; unsigned short id; length=GetStringInfoLength(profile); p=GetStringInfoDatum(profile); while (length != 0) { if (ReadProfileByte(&p,&length) != 0x38) continue; if (ReadProfileByte(&p,&length) != 0x42) continue; if (ReadProfileByte(&p,&length) != 0x49) continue; if (ReadProfileByte(&p,&length) != 0x4D) continue; if (length < 7) return(MagickFalse); id=ReadProfileMSBShort(&p,&length); count=(ssize_t) ReadProfileByte(&p,&length); if ((count >= (ssize_t) length) || (count < 0)) return(MagickFalse); p+=count; length-=count; if ((*p & 0x01) == 0) (void) ReadProfileByte(&p,&length); count=(ssize_t) ReadProfileMSBLong(&p,&length); if ((count > (ssize_t) length) || (count < 0)) return(MagickFalse); if ((id == 0x3ED) && (count == 16)) { if (image->units == PixelsPerCentimeterResolution) WriteProfileLong(MSBEndian,(unsigned int) (image->x_resolution*2.54* 65536.0),p); else WriteProfileLong(MSBEndian,(unsigned int) (image->x_resolution* 65536.0),p); WriteProfileShort(MSBEndian,(unsigned short) image->units,p+4); if (image->units == PixelsPerCentimeterResolution) WriteProfileLong(MSBEndian,(unsigned int) (image->y_resolution*2.54* 65536.0),p+8); else WriteProfileLong(MSBEndian,(unsigned int) (image->y_resolution* 65536.0),p+8); WriteProfileShort(MSBEndian,(unsigned short) image->units,p+12); } p+=count; length-=count; } return(MagickTrue); } static MagickBooleanType SyncExifProfile(Image *image, StringInfo *profile) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 typedef struct _DirectoryInfo { unsigned char *directory; size_t entry; } DirectoryInfo; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; size_t entry, length, number_entries; SplayTreeInfo *exif_resources; ssize_t id, level, offset; static int format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; unsigned char *directory, *exif; /* Set EXIF resolution tag. */ length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); if ((id != 0x4949) && (id != 0x4D4D)) { while (length != 0) { if (ReadProfileByte(&exif,&length) != 0x45) continue; if (ReadProfileByte(&exif,&length) != 0x78) continue; if (ReadProfileByte(&exif,&length) != 0x69) continue; if (ReadProfileByte(&exif,&length) != 0x66) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); } endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadProfileShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadProfileLong(endian,exif+4); if ((offset < 0) || ((size_t) offset >= length)) return(MagickFalse); directory=exif+offset; level=0; entry=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=ReadProfileShort(endian,directory); for ( ; entry < number_entries; entry++) { int components; register unsigned char *p, *q; size_t number_bytes; ssize_t format, tag_value; q=(unsigned char *) (directory+2+(12*entry)); if (q > (exif+length-12)) break; /* corrupt EXIF */ if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(ssize_t) ReadProfileShort(endian,q); format=(ssize_t) ReadProfileShort(endian,q+2); if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS)) break; components=(int) ReadProfileLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*format_bytes[format]; if ((ssize_t) number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { /* The directory entry contains an offset. */ offset=(ssize_t) ReadProfileLong(endian,q+8); if ((offset < 0) || ((size_t) (offset+number_bytes) > length)) continue; if (~length < number_bytes) continue; /* prevent overflow */ p=(unsigned char *) (exif+offset); } switch (tag_value) { case 0x011a: { (void) WriteProfileLong(endian,(size_t) (image->x_resolution+0.5),p); if (number_bytes == 8) (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x011b: { (void) WriteProfileLong(endian,(size_t) (image->y_resolution+0.5),p); if (number_bytes == 8) (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x0112: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) image->orientation,p); break; } (void) WriteProfileShort(endian,(unsigned short) image->orientation, p); break; } case 0x0128: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) (image->units+1),p); break; } (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p); break; } default: break; } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET)) { offset=(ssize_t) ReadProfileLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; level++; directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadProfileLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(MagickTrue); } MagickExport MagickBooleanType SyncImageProfiles(Image *image) { MagickBooleanType status; StringInfo *profile; status=MagickTrue; profile=(StringInfo *) GetImageProfile(image,"8BIM"); if (profile != (StringInfo *) NULL) if (Sync8BimProfile(image,profile) == MagickFalse) status=MagickFalse; profile=(StringInfo *) GetImageProfile(image,"EXIF"); if (profile != (StringInfo *) NULL) if (SyncExifProfile(image,profile) == MagickFalse) status=MagickFalse; return(status); }
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_H #include "clang/AST/Availability.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/OperatorPrecedence.h" #include "clang/Basic/Specifiers.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Sema.h" #include "clang/Sema/IGenHint.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Frontend/OpenMP/OMPContext.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SaveAndRestore.h" #include <memory> #include <stack> namespace clang { class PragmaHandler; class Scope; class BalancedDelimiterTracker; class CorrectionCandidateCallback; class DeclGroupRef; class DiagnosticBuilder; struct LoopHint; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class OMPClause; class ObjCTypeParamList; class ObjCTypeParameter; struct OMPTraitProperty; struct OMPTraitSelector; struct OMPTraitSet; class OMPTraitInfo; /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. /// class Parser : public CodeCompletionHandler { friend class ColonProtectionRAIIObject; friend class ParsingOpenMPDirectiveRAII; friend class InMessageExpressionRAIIObject; friend class PoisonSEHIdentifiersRAIIObject; friend class ObjCDeclContextSwitch; friend class ParenBraceBracketBalancer; friend class BalancedDelimiterTracker; Preprocessor &PP; /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of // a statement). SourceLocation PrevTokLocation; /// Tracks an expected type for the current token when parsing an expression. /// Used by code completion for ranking. PreferredTypeBuilder PreferredType; unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; unsigned short MisplacedModuleBeginCount = 0; /// Actions - These are the callbacks we invoke as we parse various constructs /// in the file. Sema &Actions; DiagnosticsEngine &Diags; /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; Scope *ScopeCache[ScopeCacheSize]; /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; /// Contextual keywords for Microsoft extensions. IdentifierInfo *Ident__except; mutable IdentifierInfo *Ident_sealed; /// Ident_super - IdentifierInfo for "super", to support fast /// comparison. IdentifierInfo *Ident_super; /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled. IdentifierInfo *Ident_vector; IdentifierInfo *Ident_bool; /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. /// Only present if AltiVec enabled. IdentifierInfo *Ident_pixel; /// Objective-C contextual keywords. IdentifierInfo *Ident_instancetype; /// Identifier for "introduced". IdentifierInfo *Ident_introduced; /// Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// Identifier for "message". IdentifierInfo *Ident_message; /// Identifier for "strict". IdentifierInfo *Ident_strict; /// Identifier for "replacement". IdentifierInfo *Ident_replacement; /// Identifiers used by the 'external_source_symbol' attribute. IdentifierInfo *Ident_language, *Ident_defined_in, *Ident_generated_declaration; /// C++11 contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_GNU_final; mutable IdentifierInfo *Ident_override; // C++2a contextual keywords. mutable IdentifierInfo *Ident_import; mutable IdentifierInfo *Ident_module; // C++ type trait keywords that can be reverted to identifiers and still be // used as type traits. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; std::unique_ptr<PragmaHandler> IGenHandler; std::unique_ptr<PragmaHandler> AlignHandler; std::unique_ptr<PragmaHandler> GCCVisibilityHandler; std::unique_ptr<PragmaHandler> OptionsHandler; std::unique_ptr<PragmaHandler> PackHandler; std::unique_ptr<PragmaHandler> MSStructHandler; std::unique_ptr<PragmaHandler> UnusedHandler; std::unique_ptr<PragmaHandler> WeakHandler; std::unique_ptr<PragmaHandler> RedefineExtnameHandler; std::unique_ptr<PragmaHandler> FPContractHandler; std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; std::unique_ptr<PragmaHandler> OpenMPHandler; std::unique_ptr<PragmaHandler> PCSectionHandler; std::unique_ptr<PragmaHandler> MSCommentHandler; std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; std::unique_ptr<PragmaHandler> FloatControlHandler; std::unique_ptr<PragmaHandler> MSPointersToMembers; std::unique_ptr<PragmaHandler> MSVtorDisp; std::unique_ptr<PragmaHandler> MSInitSeg; std::unique_ptr<PragmaHandler> MSDataSeg; std::unique_ptr<PragmaHandler> MSBSSSeg; std::unique_ptr<PragmaHandler> MSConstSeg; std::unique_ptr<PragmaHandler> MSCodeSeg; std::unique_ptr<PragmaHandler> MSSection; std::unique_ptr<PragmaHandler> MSRuntimeChecks; std::unique_ptr<PragmaHandler> MSIntrinsic; std::unique_ptr<PragmaHandler> MSOptimize; std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; std::unique_ptr<PragmaHandler> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> FPHandler; std::unique_ptr<PragmaHandler> STDCFENVHandler; std::unique_ptr<PragmaHandler> STDCCXLIMITHandler; std::unique_ptr<PragmaHandler> STDCUnknownHandler; std::unique_ptr<PragmaHandler> AttributePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler; std::unique_ptr<CommentHandler> CommentSemaHandler; /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template /// argument list. bool GreaterThanIsOperator; /// ColonIsSacred - When this is false, we aggressively try to recover from /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not /// safe in case statements and a few other things. This is managed by the /// ColonProtectionRAIIObject RAII object. bool ColonIsSacred; /// Parsing OpenMP directive mode. bool OpenMPDirectiveParsing = false; /// When true, we are directly inside an Objective-C message /// send expression. /// /// This is managed by the \c InMessageExpressionRAIIObject class, and /// should not be set directly. bool InMessageExpression; /// Gets set to true after calling ProduceSignatureHelp, it is for a /// workaround to make sure ProduceSignatureHelp is only called at the deepest /// function call. bool CalledSignatureHelp = false; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// Current kind of OpenMP clause OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown; /// RAII class that manages the template parameter depth. class TemplateParameterDepthRAII { unsigned &Depth; unsigned AddedLevels; public: explicit TemplateParameterDepthRAII(unsigned &Depth) : Depth(Depth), AddedLevels(0) {} ~TemplateParameterDepthRAII() { Depth -= AddedLevels; } void operator++() { ++Depth; ++AddedLevels; } void addDepth(unsigned D) { Depth += D; AddedLevels += D; } void setAddedDepth(unsigned D) { Depth = Depth - AddedLevels + D; AddedLevels = D; } unsigned getDepth() const { return Depth; } unsigned getOriginalDepth() const { return Depth - AddedLevels; } }; /// Factory object for creating ParsedAttr objects. AttributeFactory AttrFactory; /// Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; void MaybeDestroyTemplateIds() { if (!TemplateIds.empty() && (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens())) DestroyTemplateIds(); } void DestroyTemplateIds(); /// RAII object to destroy TemplateIdAnnotations where possible, from a /// likely-good position during parsing. struct DestroyTemplateIdAnnotationsRAIIObj { Parser &Self; DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {} ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); } }; /// Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; /// Tracker for '<' tokens that might have been intended to be treated as an /// angle bracket instead of a less-than comparison. /// /// This happens when the user intends to form a template-id, but typoes the /// template-name or forgets a 'template' keyword for a dependent template /// name. /// /// We track these locations from the point where we see a '<' with a /// name-like expression on its left until we see a '>' or '>>' that might /// match it. struct AngleBracketTracker { /// Flags used to rank candidate template names when there is more than one /// '<' in a scope. enum Priority : unsigned short { /// A non-dependent name that is a potential typo for a template name. PotentialTypo = 0x0, /// A dependent name that might instantiate to a template-name. DependentName = 0x2, /// A space appears before the '<' token. SpaceBeforeLess = 0x0, /// No space before the '<' token NoSpaceBeforeLess = 0x1, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName) }; struct Loc { Expr *TemplateName; SourceLocation LessLoc; AngleBracketTracker::Priority Priority; unsigned short ParenCount, BracketCount, BraceCount; bool isActive(Parser &P) const { return P.ParenCount == ParenCount && P.BracketCount == BracketCount && P.BraceCount == BraceCount; } bool isActiveOrNested(Parser &P) const { return isActive(P) || P.ParenCount > ParenCount || P.BracketCount > BracketCount || P.BraceCount > BraceCount; } }; SmallVector<Loc, 8> Locs; /// Add an expression that might have been intended to be a template name. /// In the case of ambiguity, we arbitrarily select the innermost such /// expression, for example in 'foo < bar < baz', 'bar' is the current /// candidate. No attempt is made to track that 'foo' is also a candidate /// for the case where we see a second suspicious '>' token. void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc, Priority Prio) { if (!Locs.empty() && Locs.back().isActive(P)) { if (Locs.back().Priority <= Prio) { Locs.back().TemplateName = TemplateName; Locs.back().LessLoc = LessLoc; Locs.back().Priority = Prio; } } else { Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount, P.BracketCount, P.BraceCount}); } } /// Mark the current potential missing template location as having been /// handled (this happens if we pass a "corresponding" '>' or '>>' token /// or leave a bracket scope). void clear(Parser &P) { while (!Locs.empty() && Locs.back().isActiveOrNested(P)) Locs.pop_back(); } /// Get the current enclosing expression that might hve been intended to be /// a template name. Loc *getCurrent(Parser &P) { if (!Locs.empty() && Locs.back().isActive(P)) return &Locs.back(); return nullptr; } }; AngleBracketTracker AngleBrackets; IdentifierInfo *getSEHExceptKeyword(); /// True if we are within an Objective-C container while parsing C-like decls. /// /// This is necessary because Sema thinks we have left the container /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will /// be NULL. bool ParsingInObjCContainer; /// Whether to skip parsing of function bodies. /// /// This option can be used, for example, to speed up searches for /// declarations/definitions when indexing. bool SkipFunctionBodies; /// The location of the expression statement that is being parsed right now. /// Used to determine if an expression that is being parsed is a statement or /// just a regular sub-expression. SourceLocation ExprStatementTokLoc; /// Flags describing a context in which we're parsing a statement. enum class ParsedStmtContext { /// This context permits declarations in language modes where declarations /// are not statements. AllowDeclarationsInC = 0x1, /// This context permits standalone OpenMP directives. AllowStandaloneOpenMPDirectives = 0x2, /// This context is at the top level of a GNU statement expression. InStmtExpr = 0x4, /// The context of a regular substatement. SubStmt = 0, /// The context of a compound-statement. Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives, LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr) }; /// Act on an expression statement that might be the last statement in a /// GNU statement expression. Checks whether we are actually at the end of /// a statement expression and builds a suitable expression statement. StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx); public: Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); ~Parser() override; const LangOptions &getLangOpts() const { return PP.getLangOpts(); } const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Sema &getActions() const { return Actions; } AttributeFactory &getAttrFactory() { return AttrFactory; } const Token &getCurToken() const { return Tok; } Scope *getCurScope() const { return Actions.getCurScope(); } void incrementMSManglingNumber() const { return Actions.incrementMSManglingNumber(); } Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; typedef Sema::FullExprArg FullExprArg; // Parsing methods. /// Initialize - Warm up the parser. /// void Initialize(); /// Parse the first top-level declaration in a translation unit. bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false); bool ParseTopLevelDecl() { DeclGroupPtrTy Result; return ParseTopLevelDecl(Result); } /// ConsumeToken - Consume the current 'peek token' and lex the next one. /// This does not work with special tokens: string literals, code completion, /// annotation tokens and balanced tokens must be handled using the specific /// consume methods. /// Returns the location of the consumed token. SourceLocation ConsumeToken() { assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } bool TryConsumeToken(tok::TokenKind Expected) { if (Tok.isNot(Expected)) return false; assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return true; } bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { if (!TryConsumeToken(Expected)) return false; Loc = PrevTokLocation; return true; } /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { if (isTokenParen()) return ConsumeParen(); if (isTokenBracket()) return ConsumeBracket(); if (isTokenBrace()) return ConsumeBrace(); if (isTokenStringLiteral()) return ConsumeStringToken(); if (Tok.is(tok::code_completion)) return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() : handleUnexpectedCodeCompletionToken(); if (Tok.isAnnotation()) return ConsumeAnnotationToken(); return ConsumeToken(); } SourceLocation getEndOfPreviousToken() { return PP.getLocForEndOfToken(PrevTokLocation); } /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds /// to the given nullability kind. IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { return Actions.getNullabilityKeyword(nullability); } private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.isOneOf(tok::l_square, tok::r_square); } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); } /// isTokenStringLiteral - True if this token is a string-literal. bool isTokenStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } /// isTokenSpecial - True if this token requires special consumption methods. bool isTokenSpecial() const { return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation(); } /// Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// Return the current token to the token stream and make the given /// token the current token. void UnconsumeToken(Token &Consumed) { Token Next = Tok; PP.EnterToken(Consumed, /*IsReinject*/true); PP.Lex(Tok); PP.EnterToken(Next, /*IsReinject*/true); } SourceLocation ConsumeAnnotationToken() { assert(Tok.isAnnotation() && "wrong consume method"); SourceLocation Loc = Tok.getLocation(); PrevTokLocation = Tok.getAnnotationEndLoc(); PP.Lex(Tok); return Loc; } /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { assert(isTokenParen() && "wrong consume method"); if (Tok.getKind() == tok::l_paren) ++ParenCount; else if (ParenCount) { AngleBrackets.clear(*this); --ParenCount; // Don't let unbalanced )'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { assert(isTokenBracket() && "wrong consume method"); if (Tok.getKind() == tok::l_square) ++BracketCount; else if (BracketCount) { AngleBrackets.clear(*this); --BracketCount; // Don't let unbalanced ]'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { assert(isTokenBrace() && "wrong consume method"); if (Tok.getKind() == tok::l_brace) ++BraceCount; else if (BraceCount) { AngleBrackets.clear(*this); --BraceCount; // Don't let unbalanced }'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation /// phase #6. SourceLocation ConsumeStringToken() { assert(isTokenStringLiteral() && "Should only consume string literals with this method"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// Consume the current code-completion token. /// /// This routine can be called to consume the code-completion token and /// continue processing in special cases where \c cutOffParsing() isn't /// desired, such as token caching or completion with lookahead. SourceLocation ConsumeCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } ///\ brief When we are consuming a code-completion token without having /// matched specific position in the grammar, provide code-completion results /// based on context. /// /// \returns the source location of the code-completion token. SourceLocation handleUnexpectedCodeCompletionToken(); /// Abruptly cut off parsing; mainly used when we have reached the /// code-completion point. void cutOffParsing() { if (PP.isCodeCompletionEnabled()) PP.setCodeCompletionReached(); // Cut off parsing by acting as if we reached the end-of-file. Tok.setKind(tok::eof); } /// Determine if we're at the end of the file or at a transition /// between modules. bool isEofOrEom() { tok::TokenKind Kind = Tok.getKind(); return Kind == tok::eof || Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include; } /// Checks if the \p Level is valid for use in a fold expression. bool isFoldOperator(prec::Level Level) const; /// Checks if the \p Kind is a valid operator for fold expressions. bool isFoldOperator(tok::TokenKind Kind) const; /// Initialize all pragma handlers. void initializePragmaHandlers(); /// Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); /// Handle the annotation token produced for /// #pragma comment... void HandlePragmaMSComment(); void HandlePragmaMSPointersToMembers(); void HandlePragmaMSVtorDisp(); void HandlePragmaMSPragma(); bool HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation); /// Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// Handle the annotation token produced for /// #pragma STDC FENV_ACCESS... void HandlePragmaFEnvAccess(); /// Handle the annotation token produced for /// #pragma float_control void HandlePragmaFloatControl(); /// \brief Handle the annotation token produced for /// #pragma clang fp ... void HandlePragmaFP(); /// Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// Handle the annotation token produced for /// #pragma igen reduce. bool HandlePragmaIGen(IGenHint &Hint); /// Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); bool ParsePragmaAttributeSubjectMatchRuleSet( attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); void HandlePragmaAttribute(); /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. /// /// Note that this differs from the Preprocessor's LookAhead method, because /// the Parser always has one token lexed that the preprocessor doesn't. /// const Token &GetLookAheadToken(unsigned N) { if (N == 0 || Tok.is(tok::eof)) return Tok; return PP.LookAhead(N-1); } public: /// NextToken - This peeks ahead one token and returns it without /// consuming it. const Token &NextToken() { return PP.LookAhead(0); } /// getTypeAnnotation - Read a parsed type out of an annotation token. static TypeResult getTypeAnnotation(const Token &Tok) { if (!Tok.getAnnotationValue()) return TypeError(); return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, TypeResult T) { assert((T.isInvalid() || T.get()) && "produced a valid-but-null type annotation?"); Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr()); } static NamedDecl *getNonTypeAnnotation(const Token &Tok) { return static_cast<NamedDecl*>(Tok.getAnnotationValue()); } static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) { Tok.setAnnotationValue(ND); } static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) { return static_cast<IdentifierInfo*>(Tok.getAnnotationValue()); } static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) { Tok.setAnnotationValue(ND); } /// Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(const Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// Set the primary expression corresponding to the given annotation /// token. static void setExprAnnotation(Token &Tok, ExprResult ER) { Tok.setAnnotationValue(ER.getAsOpaquePointer()); } public: // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to // find a type name by attempting typo correction. bool TryAnnotateTypeOrScopeToken(); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); bool MightBeCXXScopeToken() { return Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super); } bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) { return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext); } private: enum AnnotatedNameKind { /// Annotation has failed and emitted an error. ANK_Error, /// The identifier is a tentatively-declared name. ANK_TentativeDecl, /// The identifier is a template name. FIXME: Add an annotation for that. ANK_TemplateName, /// The identifier can't be resolved. ANK_Unresolved, /// Annotation was successful. ANK_Success }; AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr); /// Push a tok::annot_cxxscope token onto the token stream. void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, /// replacing them with the non-context-sensitive keywords. This returns /// true if the token was replaced. bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { if (!getLangOpts().AltiVec && !getLangOpts().ZVector) return false; if (Tok.getIdentifierInfo() != Ident_vector && Tok.getIdentifierInfo() != Ident_bool && (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) return false; return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); } /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector /// identifier token, replacing it with the non-context-sensitive __vector. /// This returns true if the token was replaced. bool TryAltiVecVectorToken() { if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || Tok.getIdentifierInfo() != Ident_vector) return false; return TryAltiVecVectorTokenOutOfLine(); } bool TryAltiVecVectorTokenOutOfLine(); bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid); /// Returns true if the current token is the identifier 'instancetype'. /// /// Should only be used in Objective-C language modes. bool isObjCInstancetype() { assert(getLangOpts().ObjC); if (Tok.isAnnotation()) return false; if (!Ident_instancetype) Ident_instancetype = PP.getIdentifierInfo("instancetype"); return Tok.getIdentifierInfo() == Ident_instancetype; } /// TryKeywordIdentFallback - For compatibility with system headers using /// keywords as identifiers, attempt to convert the current token to an /// identifier and optionally disable the keyword for the remainder of the /// translation unit. This returns false if the token was not replaced, /// otherwise emits a diagnostic and returns true. bool TryKeywordIdentFallback(bool DisableKeyword); /// Get the TemplateIdAnnotation from the token. TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); /// TentativeParsingAction - An object that is used as a kind of "tentative /// parsing transaction". It gets instantiated to mark the token position and /// after the token consumption is done, Commit() or Revert() is called to /// either "commit the consumed tokens" or revert to the previously marked /// token position. Example: /// /// TentativeParsingAction TPA(*this); /// ConsumeToken(); /// .... /// TPA.Revert(); /// class TentativeParsingAction { Parser &P; PreferredTypeBuilder PrevPreferredType; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser& p) : P(p) { PrevPreferredType = P.PreferredType; PrevTok = P.Tok; PrevTentativelyDeclaredIdentifierCount = P.TentativelyDeclaredIdentifiers.size(); PrevParenCount = P.ParenCount; PrevBracketCount = P.BracketCount; PrevBraceCount = P.BraceCount; P.PP.EnableBacktrackAtThisPos(); isActive = true; } void Commit() { assert(isActive && "Parsing action was finished!"); P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.PP.CommitBacktrackedTokens(); isActive = false; } void Revert() { assert(isActive && "Parsing action was finished!"); P.PP.Backtrack(); P.PreferredType = PrevPreferredType; P.Tok = PrevTok; P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.ParenCount = PrevParenCount; P.BracketCount = PrevBracketCount; P.BraceCount = PrevBraceCount; isActive = false; } ~TentativeParsingAction() { assert(!isActive && "Forgot to call Commit or Revert!"); } }; /// A TentativeParsingAction that automatically reverts in its destructor. /// Useful for disambiguation parses that will always be reverted. class RevertingTentativeParsingAction : private Parser::TentativeParsingAction { public: RevertingTentativeParsingAction(Parser &P) : Parser::TentativeParsingAction(P) {} ~RevertingTentativeParsingAction() { Revert(); } }; class UnannotatedTentativeParsingAction; /// ObjCDeclContextSwitch - An object used to switch context from /// an objective-c decl context to its enclosing decl context and /// back. class ObjCDeclContextSwitch { Parser &P; Decl *DC; SaveAndRestore<bool> WithinObjCContainer; public: explicit ObjCDeclContextSwitch(Parser &p) : P(p), DC(p.getObjCDeclContext()), WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { if (DC) P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); } ~ObjCDeclContextSwitch() { if (DC) P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); } }; /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// /// If a trivial punctuator misspelling is encountered, a FixIt error /// diagnostic is issued and false is returned after recovery. /// /// If the input is malformed, this emits the specified diagnostic and true is /// returned. bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag = diag::err_expected, StringRef DiagMsg = ""); /// The parser expects a semicolon and, if present, will consume it. /// /// If the next token is not a semicolon, this emits the specified diagnostic, /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior /// to the semicolon, consumes that extra token. bool ExpectAndConsumeSemi(unsigned DiagID); /// The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified); /// Return false if the next token is an identifier. An 'expected identifier' /// error is emitted otherwise. /// /// The parser tries to recover from the error by checking if the next token /// is a C++ keyword when parsing Objective-C++. Return false if the recovery /// was successful. bool expectIdentifier(); public: //===--------------------------------------------------------------------===// // Scope manipulation /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the /// parser enters the new scope, and this object's constructor will /// create that new scope. Similarly, once the object is destroyed /// the parser will exit the scope. class ParseScope { Parser *Self; ParseScope(const ParseScope &) = delete; void operator=(const ParseScope &) = delete; public: // ParseScope - Construct a new object to manage a scope in the // parser Self where the new Scope is created with the flags // ScopeFlags, but only when we aren't about to enter a compound statement. ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, bool BeforeCompoundStmt = false) : Self(Self) { if (EnteredScope && !BeforeCompoundStmt) Self->EnterScope(ScopeFlags); else { if (BeforeCompoundStmt) Self->incrementMSManglingNumber(); this->Self = nullptr; } } // Exit - Exit the scope associated with this object now, rather // than waiting until the object is destroyed. void Exit() { if (Self) { Self->ExitScope(); Self = nullptr; } } ~ParseScope() { Exit(); } }; /// Introduces zero or more scopes for parsing. The scopes will all be exited /// when the object is destroyed. class MultiParseScope { Parser &Self; unsigned NumScopes = 0; MultiParseScope(const MultiParseScope&) = delete; public: MultiParseScope(Parser &Self) : Self(Self) {} void Enter(unsigned ScopeFlags) { Self.EnterScope(ScopeFlags); ++NumScopes; } void Exit() { while (NumScopes) { Self.ExitScope(); --NumScopes; } } ~MultiParseScope() { Exit(); } }; /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); /// ExitScope - Pop a scope off the scope stack. void ExitScope(); /// Re-enter the template scopes for a declaration that might be a template. unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D); private: /// RAII object used to modify the scope flags for the current scope. class ParseScopeFlags { Scope *CurScope; unsigned OldFlags; ParseScopeFlags(const ParseScopeFlags &) = delete; void operator=(const ParseScopeFlags &) = delete; public: ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); ~ParseScopeFlags(); }; //===--------------------------------------------------------------------===// // Diagnostic Emission and Error recovery. public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); } private: void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); void CheckNestedObjCContexts(SourceLocation AtLoc); public: /// Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R) { return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | static_cast<unsigned>(R)); } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless StopBeforeMatch is specified). Because we cannot guarantee /// that the token will ever occur, this skips to the next token, or to some /// likely good stopping point. If Flags has StopAtSemi flag, skipping will /// stop at a ';' character. Balances (), [], and {} delimiter tokens while /// skipping. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { return SkipUntil(llvm::makeArrayRef(T), Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2}; return SkipUntil(TokArray, Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2, T3}; return SkipUntil(TokArray, Flags); } bool SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); /// SkipMalformedDecl - Read tokens until we get to some likely good stopping /// point for skipping past a simple-declaration. void SkipMalformedDecl(); /// The location of the first statement inside an else that might /// have a missleading indentation. If there is no /// MisleadingIndentationChecker on an else active, this location is invalid. SourceLocation MisleadingIndentationElseLoc; private: //===--------------------------------------------------------------------===// // Lexing and parsing of C++ inline methods. struct ParsingClass; /// [class.mem]p1: "... the class is regarded as complete within /// - function bodies /// - default arguments /// - exception-specifications (TODO: C++0x) /// - and brace-or-equal-initializers for non-static data members /// (including such things in nested classes)." /// LateParsedDeclarations build the tree of those elements so they can /// be parsed after parsing the top-level class. class LateParsedDeclaration { public: virtual ~LateParsedDeclaration(); virtual void ParseLexedMethodDeclarations(); virtual void ParseLexedMemberInitializers(); virtual void ParseLexedMethodDefs(); virtual void ParseLexedAttributes(); virtual void ParseLexedPragmas(); }; /// Inner node of the LateParsedDeclaration tree that parses /// all its members recursively. class LateParsedClass : public LateParsedDeclaration { public: LateParsedClass(Parser *P, ParsingClass *C); ~LateParsedClass() override; void ParseLexedMethodDeclarations() override; void ParseLexedMemberInitializers() override; void ParseLexedMethodDefs() override; void ParseLexedAttributes() override; void ParseLexedPragmas() override; private: Parser *Self; ParsingClass *Class; }; /// Contains the lexed tokens of an attribute with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. /// FIXME: Perhaps we should change the name of LateParsedDeclaration to /// LateParsedTokens. struct LateParsedAttribute : public LateParsedDeclaration { Parser *Self; CachedTokens Toks; IdentifierInfo &AttrName; IdentifierInfo *MacroII = nullptr; SourceLocation AttrNameLoc; SmallVector<Decl*, 2> Decls; explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc) : Self(P), AttrName(Name), AttrNameLoc(Loc) {} void ParseLexedAttributes() override; void addDecl(Decl *D) { Decls.push_back(D); } }; /// Contains the lexed tokens of a pragma with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. class LateParsedPragma : public LateParsedDeclaration { Parser *Self = nullptr; AccessSpecifier AS = AS_none; CachedTokens Toks; public: explicit LateParsedPragma(Parser *P, AccessSpecifier AS) : Self(P), AS(AS) {} void takeToks(CachedTokens &Cached) { Toks.swap(Cached); } const CachedTokens &toks() const { return Toks; } AccessSpecifier getAccessSpecifier() const { return AS; } void ParseLexedPragmas() override; }; // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { public: LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } bool parseSoon() { return ParseSoon; } private: bool ParseSoon; // Are we planning to parse these shortly after creation? }; /// Contains the lexed tokens of a member function definition /// which needs to be parsed at the end of the class declaration /// after parsing all other member declarations. struct LexedMethod : public LateParsedDeclaration { Parser *Self; Decl *D; CachedTokens Toks; explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {} void ParseLexedMethodDefs() override; }; /// LateParsedDefaultArgument - Keeps track of a parameter that may /// have a default argument that cannot be parsed yet because it /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { explicit LateParsedDefaultArgument(Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr) : Param(P), Toks(std::move(Toks)) { } /// Param - The parameter declaration for this parameter. Decl *Param; /// Toks - The sequence of tokens that comprises the default /// argument expression, not including the '=' or the terminating /// ')' or ','. This will be NULL for parameters that have no /// default argument. std::unique_ptr<CachedTokens> Toks; }; /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration : public LateParsedDeclaration { explicit LateParsedMethodDeclaration(Parser *P, Decl *M) : Self(P), Method(M), ExceptionSpecTokens(nullptr) {} void ParseLexedMethodDeclarations() override; Parser* Self; /// Method - The method declaration. Decl *Method; /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; /// The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; }; /// LateParsedMemberInitializer - An initializer for a non-static class data /// member whose parsing must to be delayed until the class is completely /// defined (C++11 [class.mem]p2). struct LateParsedMemberInitializer : public LateParsedDeclaration { LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) { } void ParseLexedMemberInitializers() override; Parser *Self; /// Field - The field declaration. Decl *Field; /// CachedTokens - The sequence of tokens that comprises the initializer, /// including any leading '='. CachedTokens Toks; }; /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; /// Representation of a class that has been parsed, including /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : TopLevelClass(TopLevelClass), IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) {} /// Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// Whether this class is an __interface. bool IsInterface : 1; /// The class or class template whose definition we are parsing. Decl *TagOrTemplate; /// LateParsedDeclarations - Method declarations, inline definitions and /// nested classes that contain pieces whose parsing will be delayed until /// the top-level class is fully defined. LateParsedDeclarationsContainer LateParsedDeclarations; }; /// The stack of classes that is currently being /// parsed. Nested and local classes will be pushed onto this stack /// when they are parsed, and removed afterward. std::stack<ParsingClass *> ClassStack; ParsingClass &getCurrentClass() { assert(!ClassStack.empty() && "No lexed method stacks!"); return *ClassStack.top(); } /// RAII object used to manage the parsing of a class definition. class ParsingClassDefinition { Parser &P; bool Popped; Sema::ParsingClassState State; public: ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : P(P), Popped(false), State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { } /// Pop this class of the stack. void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(State); } ~ParsingClassDefinition() { if (!Popped) P.PopParsingClass(State); } }; /// Contains information about any template-specific /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, bool isSpecialization, bool lastParameterListWasEmpty = false) : Kind(isSpecialization? ExplicitSpecialization : Template), TemplateParams(TemplateParams), LastParameterListWasEmpty(lastParameterListWasEmpty) { } explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) : Kind(ExplicitInstantiation), TemplateParams(nullptr), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false){ } /// The kind of template we are parsing. enum { /// We are not parsing a template at all. NonTemplate = 0, /// We are parsing a template declaration. Template, /// We are parsing an explicit specialization. ExplicitSpecialization, /// We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// Whether the last template parameter list was empty. bool LastParameterListWasEmpty; SourceRange getSourceRange() const LLVM_READONLY; }; // In ParseCXXInlineMethods.cpp. struct ReenterTemplateScopeRAII; struct ReenterClassScopeRAII; void LexTemplateFunctionForLateParsing(CachedTokens &Toks); void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); Sema::ParsingClassState PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(Sema::ParsingClassState); enum CachedInitKind { CIK_DefaultArgument, CIK_DefaultInitializer }; NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS, SourceLocation PureSpecLoc); void ParseCXXNonStaticMemberInitializer(Decl *VarD); void ParseLexedAttributes(ParsingClass &Class); void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition); void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); void ParseLexedMethodDefs(ParsingClass &Class); void ParseLexedMethodDef(LexedMethod &LM); void ParseLexedMemberInitializers(ParsingClass &Class); void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); void ParseLexedPragmas(ParsingClass &Class); void ParseLexedPragma(LateParsedPragma &LP); bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); bool ConsumeAndStoreConditional(CachedTokens &Toks); bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true) { return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); } bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true); //===--------------------------------------------------------------------===// // C99 6.9: External Definitions. struct ParsedAttributesWithRange : ParsedAttributes { ParsedAttributesWithRange(AttributeFactory &factory) : ParsedAttributes(factory) {} void clear() { ParsedAttributes::clear(); Range = SourceRange(); } SourceRange Range; }; struct ParsedAttributesViewWithRange : ParsedAttributesView { ParsedAttributesViewWithRange() : ParsedAttributesView() {} void clearListOnly() { ParsedAttributesView::clearListOnly(); Range = SourceRange(); } SourceRange Range; }; DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr); bool isDeclarationAfterDeclarator(); bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS); void SkipFunctionBody(); Decl *ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), LateParsedAttrList *LateParsedAttrs = nullptr); void ParseKNRParamDeclarations(Declarator &D); // EndLoc is filled with the location of the last token of the simple-asm. ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc); ExprResult ParseAsmStringLiteral(bool ForAsmLabel); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs); DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &prefixAttrs); class ObjCTypeParamListScope; ObjCTypeParamList *parseObjCTypeParamList(); ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList = true); void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing); void ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc); bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndProtoLoc, bool consumeLastToken); /// Parse the first angle-bracket-delimited clause for an /// Objective-C object or object pointer type, which may be either /// type arguments or protocol qualifiers. void parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols); /// Parse either Objective-C type arguments or protocol qualifiers; if the /// former, also parse protocol qualifiers afterward. void parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken); /// Parse a protocol qualifier type such as '<NSCopying>', which is /// an anachronistic way of writing 'id<NSCopying>'. TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); /// Parse Objective-C type arguments and protocol qualifiers, extending the /// current type with the parsed result. TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc); void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl); DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, ParsedAttributes &prefixAttrs); struct ObjCImplParsingDataRAII { Parser &P; Decl *Dcl; bool HasCFunction; typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; LateParsedObjCMethodContainer LateParsedObjCMethods; ObjCImplParsingDataRAII(Parser &parser, Decl *D) : P(parser), Dcl(D), HasCFunction(false) { P.CurParsedObjCImpl = this; Finished = false; } ~ObjCImplParsingDataRAII(); void finish(SourceRange AtEnd); bool isFinished() const { return Finished; } private: bool Finished; }; ObjCImplParsingDataRAII *CurParsedObjCImpl; void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc, ParsedAttributes &Attrs); DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, objc_nonnull, objc_nullable, objc_null_unspecified, objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; bool isTokIdentifier_in() const; ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx, ParsedAttributes *ParamAttrs); void ParseObjCMethodRequirement(); Decl *ParseObjCMethodPrototype( tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition = true); Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition=true); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); Decl *ParseObjCMethodDefinition(); public: //===--------------------------------------------------------------------===// // C99 6.5: Expressions. /// TypeCastState - State whether an expression is or may be a type cast. enum TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast }; ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpressionInExprEvalContext( TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseCaseExpression(SourceLocation CaseLoc); ExprResult ParseConstraintExpression(); ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause); ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated); ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); /// Control what ParseCastExpression will parse. enum CastParseKind { AnyCastExpr = 0, UnaryExprOnly, PrimaryExprOnly }; ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); /// Returns true if the next token cannot start an expression. bool isNotExpressionStart(); /// Returns true if the next token would start a postfix-expression /// suffix. bool isPostfixExpressionSuffixStart() { tok::TokenKind K = Tok.getKind(); return (K == tok::l_square || K == tok::l_paren || K == tok::period || K == tok::arrow || K == tok::plusplus || K == tok::minusminus); } bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); void checkPotentialAngleBracket(ExprResult &PotentialTemplateName); bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &, const Token &OpToken); bool checkPotentialAngleBracketDelimiter(const Token &OpToken) { if (auto *Info = AngleBrackets.getCurrent(*this)) return checkPotentialAngleBracketDelimiter(*Info, OpToken); return false; } ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); ExprResult ParseUniqueStableNameExpression(); ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange); typedef SmallVector<Expr*, 20> ExprListTy; typedef SmallVector<SourceLocation, 20> CommaLocsTy; /// ParseExpressionList - Used for C/C++ (argument-)expression-list. bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, llvm::function_ref<void()> ExpressionStarts = llvm::function_ref<void()>()); /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs); /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' FoldExpr, // Also allow fold-expression <anything> CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> }; ExprResult ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc); ExprResult ParseCXXAmbiguousParenExpression( ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); ExprResult ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); ExprResult ParseGenericSelectionExpression(); ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); //===--------------------------------------------------------------------===// // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS); bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors, bool EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = false, bool InUsingDeclaration = false); //===--------------------------------------------------------------------===// // C++11 5.1.2: Lambda expressions /// Result of tentatively parsing a lambda-introducer. enum class LambdaIntroducerTentativeParse { /// This appears to be a lambda-introducer, which has been fully parsed. Success, /// This is a lambda-introducer, but has not been fully parsed, and this /// function needs to be called again to parse it. Incomplete, /// This is definitely an Objective-C message send expression, rather than /// a lambda-introducer, attribute-specifier, or array designator. MessageSend, /// This is not a lambda-introducer. Invalid, }; // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); bool ParseLambdaIntroducer(LambdaIntroducer &Intro, LambdaIntroducerTentativeParse *Tentative = nullptr); ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast. ExprResult ParseBuiltinBitCast(); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Type Identification ExprResult ParseCXXTypeid(); //===--------------------------------------------------------------------===// // C++ : Microsoft __uuidof Expression ExprResult ParseCXXUuidof(); //===--------------------------------------------------------------------===// // C++ 5.2.4: C++ Pseudo-Destructor Expressions ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType); //===--------------------------------------------------------------------===// // C++ 9.3.2: C++ 'this' pointer ExprResult ParseCXXThis(); //===--------------------------------------------------------------------===// // C++ 15: C++ Throw Expression ExprResult ParseThrowExpression(); ExceptionSpecificationType tryParseExceptionSpecification( bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens); // EndLoc is filled with the location of the last token of the specification. ExceptionSpecificationType ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges); //===--------------------------------------------------------------------===// // C++0x 8: Function declaration trailing-return-type TypeResult ParseTrailingReturnType(SourceRange &Range, bool MayBeFollowedByDirectInit); //===--------------------------------------------------------------------===// // C++ 2.13.5: C++ Boolean Literals ExprResult ParseCXXBoolLiteral(); //===--------------------------------------------------------------------===// // C++ 5.2.3: Explicit type conversion (functional notation) ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); //===--------------------------------------------------------------------===// // C++ 5.3.4 and 5.3.5: C++ new and delete bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, Declarator &D); void ParseDirectNewDeclarator(Declarator &D); ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start); //===--------------------------------------------------------------------===// // C++ if/switch/while/for condition expression. struct ForRangeInfo; Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, Sema::ConditionKind CK, ForRangeInfo *FRI = nullptr); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // C++ Concepts ExprResult ParseRequiresExpression(); void ParseTrailingRequiresClause(Declarator &D); //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression /// '{' ... ExprResult ParseInitializer() { if (Tok.isNot(tok::l_brace)) return ParseAssignmentExpression(); return ParseBraceInitializer(); } bool MayBeDesignationStart(); ExprResult ParseBraceInitializer(); ExprResult ParseInitializerWithPotentialDesignator( llvm::function_ref<void(const Designation &)> CodeCompleteCB); //===--------------------------------------------------------------------===// // clang Expressions ExprResult ParseBlockLiteralExpression(); // ^{...} //===--------------------------------------------------------------------===// // Objective-C Expressions ExprResult ParseObjCAtExpression(SourceLocation AtLocation); ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); bool isSimpleObjCMessageExpression(); ExprResult ParseObjCMessageExpression(); ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); ExprResult ParseAssignmentExprWithObjCMessageExprStart( SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef SmallVector<Stmt*, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef SmallVector<Expr*, 12> ExprVector; /// A SmallVector of types. typedef SmallVector<ParsedType, 12> TypeVector; StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt); StmtResult ParseStatementOrDeclaration( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(ParsedStmtContext StmtCtx); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs, ParsedStmtContext StmtCtx); StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx, bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); bool ConsumeNullStmt(StmtVector &Stmts); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(StmtResult *InitStmt, Sema::ConditionResult &CondResult, SourceLocation Loc, Sema::ConditionKind CK, SourceLocation *LParenLoc = nullptr, SourceLocation *RParenLoc = nullptr); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParsePragmaIGen(StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// Parse the block; this code is always used. IEB_Parse, /// Skip the block entirely; this code is never used. IEB_Skip, /// Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// The location of the initial keyword. SourceLocation KeywordLoc; /// Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// Nested-name-specifier preceding the name. CXXScopeSpec SS; /// The name we're looking for. UnqualifiedId Name; /// The behavior of this __if_exists or __if_not_exists block /// should. IfExistsBehavior Behavior; }; bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); void ParseMicrosoftIfExistsExternalDeclaration(); void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, ParsedAttributes &AccessAttrs, AccessSpecifier &CurAS); bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk); bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs); //===--------------------------------------------------------------------===// // C++ 6: Statements and Blocks StmtResult ParseCXXTryBlock(); StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); StmtResult ParseCXXCatchBlock(bool FnCatch = false); //===--------------------------------------------------------------------===// // MS: SEH Statements and Blocks StmtResult ParseSEHTryBlock(); StmtResult ParseSEHExceptBlock(SourceLocation Loc); StmtResult ParseSEHFinallyBlock(SourceLocation Loc); StmtResult ParseSEHLeaveStatement(); //===--------------------------------------------------------------------===// // Objective-C Statements StmtResult ParseObjCAtStatement(SourceLocation atLoc, ParsedStmtContext StmtCtx); StmtResult ParseObjCTryStmt(SourceLocation atLoc); StmtResult ParseObjCThrowStmt(SourceLocation atLoc); StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); //===--------------------------------------------------------------------===// // C99 6.7: Declarations. /// A context for parsing declaration specifiers. TODO: flesh this /// out, there are other significant restrictions on specifiers than /// would be best implemented in the parser. enum class DeclSpecContext { DSC_normal, // normal context DSC_class, // class context, enables 'friend' DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list DSC_trailing, // C++11 trailing-type-specifier in a trailing return type DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration DSC_top_level, // top-level/namespace declaration context DSC_template_param, // template parameter context DSC_template_type_arg, // template type argument context DSC_objc_method_result, // ObjC method result context, enables 'instancetype' DSC_condition // condition declaration context }; /// Is this a context in which we are parsing just a type-specifier (or /// trailing-type-specifier)? static bool isTypeSpecifier(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: return false; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return true; } llvm_unreachable("Missing DeclSpecContext case"); } /// Whether a defining-type-specifier is permitted in a given context. enum class AllowDefiningTypeSpec { /// The grammar doesn't allow a defining-type-specifier here, and we must /// not parse one (eg, because a '{' could mean something else). No, /// The grammar doesn't allow a defining-type-specifier here, but we permit /// one for error recovery purposes. Sema will reject. NoButErrorRecovery, /// The grammar allows a defining-type-specifier here, even though it's /// always invalid. Sema will reject. YesButInvalid, /// The grammar allows a defining-type-specifier here, and one can be valid. Yes }; /// Is this a context in which we are parsing defining-type-specifiers (and /// so permit class and enum definitions in addition to non-defining class and /// enum elaborated-type-specifiers)? static AllowDefiningTypeSpec isDefiningTypeSpecifierContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_alias_declaration: case DeclSpecContext::DSC_objc_method_result: return AllowDefiningTypeSpec::Yes; case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_template_param: return AllowDefiningTypeSpec::YesButInvalid; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: return AllowDefiningTypeSpec::NoButErrorRecovery; case DeclSpecContext::DSC_trailing: return AllowDefiningTypeSpec::No; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which an opaque-enum-declaration can appear? static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: return true; case DeclSpecContext::DSC_alias_declaration: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which we can perform class template argument /// deduction? static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_type_specifier: return true; case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Information on a C++0x for-range-initializer found while parsing a /// declaration which turns out to be a for-range-declaration. struct ForRangeInit { SourceLocation ColonLoc; ExprResult RangeExpr; bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } }; struct ForRangeInfo : ForRangeInit { StmtResult LoopVar; }; DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, SourceLocation *DeclSpecStart = nullptr); DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr, SourceLocation *DeclSpecStart = nullptr); bool MightBeDeclarator(DeclaratorContext Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context, SourceLocation *DeclEnd = nullptr, ForRangeInit *FRI = nullptr); Decl *ParseDeclarationAfterDeclarator(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); bool ParseAsmAttributesAfterDeclarator(Declarator &D); Decl *ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ForRangeInit *FRI = nullptr); Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); /// When in code-completion, skip parsing of the function/method body /// unless the body contains the code-completion point. /// /// \returns true if the function body was skipped. bool trySkippingFunctionBody(); bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); void ParseDeclarationSpecifiers( DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal, LateParsedAttrList *LateAttrs = nullptr); bool DiagnoseMissingSemiAfterTagDefinition( DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); void ParseSpecifierQualifierList( DeclSpec &DS, AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType, RecordDecl *TagDecl); void ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); bool isTypeSpecifierQualifier(); /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool isKnownToBeTypeSpecifier(const Token &Tok) const; /// Return true if we know that we are definitely looking at a /// decl-specifier, and isn't part of an expression such as a function-style /// cast. Return false if it's no a decl-specifier, or we're not sure. bool isKnownToBeDeclarationSpecifier() { if (getLangOpts().CPlusPlus) return isCXXDeclarationSpecifier() == TPResult::True; return isDeclarationSpecifier(true); } /// isDeclarationStatement - Disambiguates between a declaration or an /// expression statement, when parsing function bodies. /// Returns true for declaration, false for expression. bool isDeclarationStatement() { if (getLangOpts().CPlusPlus) return isCXXDeclarationStatement(); return isDeclarationSpecifier(true); } /// isForInitDeclaration - Disambiguates between a declaration or an /// expression in the context of the C 'clause-1' or the C++ // 'for-init-statement' part of a 'for' statement. /// Returns true for declaration, false for expression. bool isForInitDeclaration() { if (getLangOpts().OpenMP) Actions.startOpenMPLoop(); if (getLangOpts().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// Starting with a scope specifier, identifier, or /// template-id that refers to the current class, determine whether /// this is a constructor declarator. bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); /// Specifies the context in which type-id/expression /// disambiguation will occur. enum TentativeCXXTypeIdContext { TypeIdInParens, TypeIdUnambiguous, TypeIdAsTemplateArgument }; /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know /// whether the parens contain an expression or a type-id. /// Returns true for a type-id and false for an expression. bool isTypeIdInParens(bool &isAmbiguous) { if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdInParens, isAmbiguous); isAmbiguous = false; return isTypeSpecifierQualifier(); } bool isTypeIdInParens() { bool isAmbiguous; return isTypeIdInParens(isAmbiguous); } /// Checks if the current tokens form type-id or expression. /// It is similar to isTypeIdInParens but does not suppose that type-id /// is in parenthesis. bool isTypeIdUnambiguously() { bool IsAmbiguous; if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); return isTypeSpecifierQualifier(); } /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. bool isCXXDeclarationStatement(); /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. bool isCXXSimpleDeclaration(bool AllowForRangeDecl); /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); struct ConditionDeclarationOrInitStatementState; enum class ConditionOrInitStatement { Expression, ///< Disambiguated as an expression (either kind). ConditionDecl, ///< Disambiguated as the declaration form of condition. InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. ForRangeDecl, ///< Disambiguated as a for-range declaration. Error ///< Can't be any of the above! }; /// Disambiguates between the different kinds of things that can happen /// after 'if (' or 'switch ('. This could be one of two different kinds of /// declaration (depending on whether there is a ';' later) or an expression. ConditionOrInitStatement isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt, bool CanBeForRangeDecl); bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); bool isCXXTypeId(TentativeCXXTypeIdContext Context) { bool isAmbiguous; return isCXXTypeId(Context, isAmbiguous); } /// TPResult - Used as the result value for functions whose purpose is to /// disambiguate C++ constructs by "tentatively parsing" them. enum class TPResult { True, False, Ambiguous, Error }; /// Determine whether we could have an enum-base. /// /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise /// only consider this to be an enum-base if the next token is a '{'. /// /// \return \c false if this cannot possibly be an enum base; \c true /// otherwise. bool isEnumBase(bool AllowSemi); /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a /// declaration specifier, TPResult::False if it is not, /// TPResult::Ambiguous if it could be either a decl-specifier or a /// function-style cast, and TPResult::Error if a parsing error was /// encountered. If it could be a braced C++11 function-style cast, returns /// BracedCastResult. /// Doesn't consume tokens. TPResult isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, bool *InvalidAsDeclSpec = nullptr); /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or /// \c TPResult::Ambiguous, determine whether the decl-specifier would be /// a type-specifier other than a cv-qualifier. bool isCXXDeclarationSpecifierAType(); /// Determine whether the current token sequence might be /// '<' template-argument-list '>' /// rather than a less-than expression. TPResult isTemplateArgumentList(unsigned TokensToSkip); /// Determine whether an '(' after an 'explicit' keyword is part of a C++20 /// 'explicit(bool)' declaration, in earlier language modes where that is an /// extension. TPResult isExplicitBool(); /// Determine whether an identifier has been tentatively declared as a /// non-type. Such tentative declarations should not be found to name a type /// during a tentative parse, but also should not be annotated as a non-type. bool isTentativelyDeclared(IdentifierInfo *II); // "Tentative parsing" functions, used for disambiguation. If a parsing error // is encountered they will return TPResult::Error. // Returning TPResult::True/False indicates that the ambiguity was // resolved and tentative parsing may stop. TPResult::Ambiguous indicates // that more tentative parsing is necessary for disambiguation. // They all consume tokens, so backtracking should be used after calling them. TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); TPResult TryParseTypeofSpecifier(); TPResult TryParseProtocolQualifiers(); TPResult TryParsePtrOperatorSeq(); TPResult TryParseOperatorId(); TPResult TryParseInitDeclaratorList(); TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, bool mayHaveDirectInit = false); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); /// Try to skip a possibly empty sequence of 'attribute-specifier's without /// full validation of the syntactic structure of attributes. bool TrySkipAttributes(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, DeclaratorContext Context = DeclaratorContext::TypeNameContext, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); /// Are [[]] attributes enabled? bool standardAttributesAllowed() const { const LangOptions &LO = getLangOpts(); return LO.DoubleSquareBracketAttributes; } // Check for the start of an attribute-specifier-seq in a context where an // attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!standardAttributesAllowed()) return; if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && Tok.isNot(tok::kw_alignas)) return; DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); } void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation); void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); // FixItLoc = possible correct location for the attributes void ProhibitAttributes(ParsedAttributesWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clear(); } void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clearListOnly(); } void DiagnoseProhibitedAttributes(const SourceRange &Range, SourceLocation FixItLoc); // Forbid C++11 and C2x attributes that appear on certain syntactic locations // which standard permits but we don't supported yet, for example, attributes // appertain to decl specifiers. void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, unsigned DiagID); /// Skip C++11 and C2x attributes and return the end location of the /// last one. /// \returns SourceLocation() if there are no attributes. SourceLocation SkipCXX11Attributes(); /// Diagnose and skip C++11 and C2x attributes that appear in syntactic /// locations where attributes are not allowed. void DiagnoseAndSkipCXX11Attributes(); /// Parses syntax-generic attribute arguments for attributes which are /// known to the implementation, and adds them to the given ParsedAttributes /// list with the given attribute syntax. Returns the number of arguments /// parsed for the attribute. unsigned ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseGNUAttributes(Declarator &D, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributes attrs(AttrFactory); SourceLocation endLoc; ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D); D.takeAttributes(attrs, endLoc); } } void MaybeParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) ParseGNUAttributes(attrs, endLoc, LateAttrs); } void ParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr); void ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); unsigned ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseCXX11Attributes(Declarator &D) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } bool MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); return true; } return false; } void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) ParseCXX11Attributes(attrs, endLoc); } void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, SourceLocation *EndLoc = nullptr); void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *EndLoc = nullptr); /// Parses a C++11 (or C2x)-style attribute argument list. Returns true /// if this results in adding an attribute to the ParsedAttributes list. bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc); IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) ParseMicrosoftAttributes(attrs, endLoc); } void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); void ParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr); void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr) { const auto &LO = getLangOpts(); if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) ParseMicrosoftDeclSpecs(Attrs, End); } void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr); bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs); void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); SourceLocation SkipExtendedMicrosoftTypeAttributes(); void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); void ParseBorlandTypeAttributes(ParsedAttributes &attrs); void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); void ParseOpenCLQualifiers(ParsedAttributes &Attrs); /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0 /// or higher. /// \return false if error happens. bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) { if (getLangOpts().OpenCL) return ParseOpenCLUnrollHintAttribute(Attrs); return true; } /// Parses opencl_unroll_hint attribute. /// \return false if error happens. bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs); void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); VersionTuple ParseVersionTuple(SourceRange &Range); void ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); Optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeofSpecifier(DeclSpec &DS); SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, SourceLocation StartLoc, SourceLocation EndLoc); void ParseUnderlyingTypeSpecifier(DeclSpec &DS); void ParseAtomicSpecifier(DeclSpec &DS); ExprResult ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc); void ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *endLoc = nullptr); ExprResult ParseExtIntegerArgument(); VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { return isCXX11VirtSpecifier(Tok); } void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc); bool isCXX11FinalKeyword() const; /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to /// enter a new C++ declarator scope and exit it when the function is /// finished. class DeclaratorScopeObj { Parser &P; CXXScopeSpec &SS; bool EnteredScope; bool CreatedScope; public: DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} void EnterDeclaratorScope() { assert(!EnteredScope && "Already entered the scope!"); assert(SS.isSet() && "C++ scope was not set!"); CreatedScope = true; P.EnterScope(0); // Not a decl scope. if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) EnteredScope = true; } ~DeclaratorScopeObj() { if (EnteredScope) { assert(SS.isSet() && "C++ scope was cleared ?"); P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); } if (CreatedScope) P.ExitScope(); } }; /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. typedef void (Parser::*DirectDeclParseFunction)(Declarator&); void ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser); enum AttrRequirements { AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. AR_GNUAttributesParsed = 1 << 1, AR_CXX11AttributesParsed = 1 << 2, AR_DeclspecAttributesParsed = 1 << 3, AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed, AR_VendorAttributesParsed = AR_GNUAttributesParsed | AR_DeclspecAttributesParsed }; void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); void InitCXXThisScopeForDeclaratorIfRelevant( const Declarator &D, const DeclSpec &DS, llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( DeclaratorContext DeclaratorContext, ParsedAttributes &attrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc); void ParseBracketDeclarator(Declarator &D); void ParseMisplacedBracketDeclarator(Declarator &D); //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] /// The kind of attribute specifier we have found. enum CXX11AttributeKind { /// This is not an attribute specifier. CAK_NotAttributeSpecifier, /// This should be treated as an attribute-specifier. CAK_AttributeSpecifier, /// The next tokens are '[[', but this is not an attribute-specifier. This /// is ill-formed by C++11 [dcl.attr.grammar]p6. CAK_InvalidAttributeSpecifier }; CXX11AttributeKind isCXX11AttributeSpecifier(bool Disambiguate = false, bool OuterMightBeMessageSend = false); void DiagnoseUnexpectedNamespace(NamedDecl *Context); DeclGroupPtrTy ParseNamespace(DeclaratorContext Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); struct InnerNamespaceInfo { SourceLocation NamespaceLoc; SourceLocation InlineLoc; SourceLocation IdentLoc; IdentifierInfo *Ident; }; using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>; void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs, unsigned int index, SourceLocation &InlineLoc, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context); Decl *ParseExportDeclaration(); DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); struct UsingDeclarator { SourceLocation TypenameLoc; CXXScopeSpec SS; UnqualifiedId Name; SourceLocation EllipsisLoc; void clear() { TypenameLoc = EllipsisLoc = SourceLocation(); SS.clear(); Name.clear(); } }; bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D); DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none); Decl *ParseAliasDeclarationAfterDeclarator( const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, ParsedAttributes &Attrs, Decl **OwnedType = nullptr); Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. bool isValidAfterTypeSpecifier(bool CouldBeBitfield); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl); void ParseCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl); ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc); bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateAttrs); void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, VirtSpecifiers &VS); DeclGroupPtrTy ParseCXXClassMemberDeclaration( AccessSpecifier AS, ParsedAttributes &Attr, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ParsingDeclRAIIObject *DiagsFromTParams = nullptr); DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, DeclSpec::TST TagType, Decl *Tag); void ParseConstructorInitializer(Decl *ConstructorDecl); MemInitResult ParseMemInitializer(Decl *ConstructorDecl); void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl); //===--------------------------------------------------------------------===// // C++ 10: Derived classes [class.derived] TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation); void ParseBaseClause(Decl *ClassDecl); BaseResult ParseBaseSpecifier(Decl *ClassDecl); AccessSpecifier getAccessSpecifierIfPresent() const; bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId); bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result); //===--------------------------------------------------------------------===// // OpenMP: Directives and clauses. /// Parse clauses for '#pragma omp declare simd'. DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse a property kind into \p TIProperty for the selector set \p Set and /// selector \p Selector. void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty, llvm::omp::TraitSet Set, llvm::omp::TraitSelector Selector, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector kind into \p TISelector for the selector set \p Set. void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector set kind into \p TISet. void parseOMPTraitSetKind(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context property. void parseOMPContextProperty(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context selector. void parseOMPContextSelector(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &SeenSelectors); /// Parses an OpenMP context selector set. void parseOMPContextSelectorSet(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets); /// Parses OpenMP context selectors. bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI); /// Parse a `match` clause for an '#pragma omp declare variant'. Return true /// if there was an error. bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI); /// Parse clauses for '#pragma omp declare variant'. void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse clauses for '#pragma omp declare target'. DeclGroupPtrTy ParseOMPDeclareTargetClauses(); /// Parse '#pragma omp end declare target'. void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if /// it is not the current token. void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind); /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error /// that the "end" matching the "begin" directive of kind \p BeginKind was not /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`. void parseOMPEndDirective(OpenMPDirectiveKind BeginKind, OpenMPDirectiveKind ExpectedKind, OpenMPDirectiveKind FoundKind, SourceLocation MatchingLoc, SourceLocation FoundLoc, bool SkipUntilOpenMPEnd); /// Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// Parses initializer for provided omp_priv declaration inside the reduction /// initializer. void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); /// Parses 'omp declare mapper' directive. DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS); /// Parses variable declaration in 'omp declare mapper' directive. TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range, DeclarationName &Name, AccessSpecifier AS = AS_none); /// Tries to parse cast part of OpenMP array shaping operation: /// '[' expression ']' { '[' expression ']' } ')'. bool tryParseOpenMPArrayShapingCastPart(); /// Parses simple list of variables. /// /// \param Kind Kind of the directive. /// \param Callback Callback function to be called for the list elements. /// \param AllowScopeSpecifier true, if the variables can have fully /// qualified names. /// bool ParseOpenMPSimpleVarList( OpenMPDirectiveKind Kind, const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & Callback, bool AllowScopeSpecifier); /// Parses declarative or executable directive. /// /// \param StmtCtx The context in which we're parsing the directive. StmtResult ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx); /// Parses clause of kind \a CKind for directive of a kind \a Kind. /// /// \param DKind Kind of current directive. /// \param CKind Kind of current clause. /// \param FirstClause true, if this is the first clause of a kind \a CKind /// in current directive. /// OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause); /// Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param DKind Directive kind. /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false); /// Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses and creates OpenMP 5.0 iterators expression: /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier = /// <range-specification> }+ ')' ExprResult ParseOpenMPIteratorsExpr(); /// Parses allocators and traits in the context of the uses_allocator clause. /// Expected format: /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')' OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind); public: /// Parses simple expression in parens for single-expression clauses of OpenMP /// constructs. /// \param RLoc Returned location of right paren. ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand = false); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *DepModOrTailExpr = nullptr; SourceLocation ColonLoc; SourceLocation RLoc; CXXScopeSpec ReductionOrMapperIdScopeSpec; DeclarationNameInfo ReductionOrMapperId; int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or ///< lastprivate clause. SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> MapTypeModifiers; SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> MapTypeModifiersLoc; bool IsMapTypeImplicit = false; SourceLocation ExtraModifierLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result); /// Parses the mapper modifier in map, to, and from clauses. bool parseMapperModifier(OpenMPVarListDataTy &Data); /// Parses map-type-modifiers in map clause. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) bool parseMapTypeModifiers(OpenMPVarListDataTy &Data); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS); Decl *ParseSingleDeclarationAfterTemplate( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams); TPResult isStartOfTemplateTypeParameter(); NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); bool isTypeConstraintAnnotation(); bool TryAnnotateTypeConstraint(); NamedDecl * ParseConstrainedTemplateTypeParameter(unsigned Depth, unsigned Position); void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName); void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D); // C++ 14.3: Template arguments [temp.arg] typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc, SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true, bool TypeConstraint = false); void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS, bool IsClassName = false); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(DeclaratorContext Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); // C++2a: Template, concept definition [temp] Decl * ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl); Decl *ParseModuleImport(SourceLocation AtLoc); bool parseMisplacedModuleImport(); bool tryParseMisplacedModuleImport() { tok::TokenKind Kind = Tok.getKind(); if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include) return parseMisplacedModuleImport(); return false; } bool ParseModuleName( SourceLocation UseLoc, SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, bool IsImport); //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); //===--------------------------------------------------------------------===// // Preprocessor code-completion pass-through void CodeCompleteDirective(bool InConditional) override; void CodeCompleteInConditionalExclusion() override; void CodeCompleteMacroName(bool IsDefinition) override; void CodeCompletePreprocessorExpression() override; void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) override; void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override; void CodeCompleteNaturalLanguage() override; class GNUAsmQualifiers { unsigned Qualifiers = AQ_unspecified; public: enum AQ { AQ_unspecified = 0, AQ_volatile = 1, AQ_inline = 2, AQ_goto = 4, }; static const char *getQualifierName(AQ Qualifier); bool setAsmQualifier(AQ Qualifier); inline bool isVolatile() const { return Qualifiers & AQ_volatile; }; inline bool isInline() const { return Qualifiers & AQ_inline; }; inline bool isGoto() const { return Qualifiers & AQ_goto; } }; bool isGCCAsmStatement(const Token &TokAfterAsm) const; bool isGNUAsmQualifier(const Token &TokAfterAsm) const; GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const; bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ); }; } // end namespace clang #endif
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_H #include "clang/AST/Availability.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/OperatorPrecedence.h" #include "clang/Basic/Specifiers.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Frontend/OpenMP/OMPContext.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SaveAndRestore.h" #include <memory> #include <stack> namespace clang { class PragmaHandler; class Scope; class BalancedDelimiterTracker; class CorrectionCandidateCallback; class DeclGroupRef; class DiagnosticBuilder; struct LoopHint; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class OMPClause; class ObjCTypeParamList; class ObjCTypeParameter; struct OMPTraitProperty; struct OMPTraitSelector; struct OMPTraitSet; class OMPTraitInfo; /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. /// class Parser : public CodeCompletionHandler { friend class ColonProtectionRAIIObject; friend class ParsingOpenMPDirectiveRAII; friend class InMessageExpressionRAIIObject; friend class PoisonSEHIdentifiersRAIIObject; friend class ObjCDeclContextSwitch; friend class ParenBraceBracketBalancer; friend class BalancedDelimiterTracker; Preprocessor &PP; /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of // a statement). SourceLocation PrevTokLocation; /// Tracks an expected type for the current token when parsing an expression. /// Used by code completion for ranking. PreferredTypeBuilder PreferredType; unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; unsigned short MisplacedModuleBeginCount = 0; /// Actions - These are the callbacks we invoke as we parse various constructs /// in the file. Sema &Actions; DiagnosticsEngine &Diags; /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; Scope *ScopeCache[ScopeCacheSize]; /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; /// Contextual keywords for Microsoft extensions. IdentifierInfo *Ident__except; mutable IdentifierInfo *Ident_sealed; /// Ident_super - IdentifierInfo for "super", to support fast /// comparison. IdentifierInfo *Ident_super; /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled. IdentifierInfo *Ident_vector; IdentifierInfo *Ident_bool; /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. /// Only present if AltiVec enabled. IdentifierInfo *Ident_pixel; /// Objective-C contextual keywords. IdentifierInfo *Ident_instancetype; /// Identifier for "introduced". IdentifierInfo *Ident_introduced; /// Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// Identifier for "message". IdentifierInfo *Ident_message; /// Identifier for "strict". IdentifierInfo *Ident_strict; /// Identifier for "replacement". IdentifierInfo *Ident_replacement; /// Identifiers used by the 'external_source_symbol' attribute. IdentifierInfo *Ident_language, *Ident_defined_in, *Ident_generated_declaration; /// C++11 contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_GNU_final; mutable IdentifierInfo *Ident_override; // C++2a contextual keywords. mutable IdentifierInfo *Ident_import; mutable IdentifierInfo *Ident_module; // C++ type trait keywords that can be reverted to identifiers and still be // used as type traits. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; std::unique_ptr<PragmaHandler> AlignHandler; std::unique_ptr<PragmaHandler> GCCVisibilityHandler; std::unique_ptr<PragmaHandler> OptionsHandler; std::unique_ptr<PragmaHandler> PackHandler; std::unique_ptr<PragmaHandler> MSStructHandler; std::unique_ptr<PragmaHandler> UnusedHandler; std::unique_ptr<PragmaHandler> WeakHandler; std::unique_ptr<PragmaHandler> RedefineExtnameHandler; std::unique_ptr<PragmaHandler> FPContractHandler; std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; std::unique_ptr<PragmaHandler> OpenMPHandler; std::unique_ptr<PragmaHandler> PCSectionHandler; std::unique_ptr<PragmaHandler> MSCommentHandler; std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; std::unique_ptr<PragmaHandler> FloatControlHandler; std::unique_ptr<PragmaHandler> MSPointersToMembers; std::unique_ptr<PragmaHandler> MSVtorDisp; std::unique_ptr<PragmaHandler> MSInitSeg; std::unique_ptr<PragmaHandler> MSDataSeg; std::unique_ptr<PragmaHandler> MSBSSSeg; std::unique_ptr<PragmaHandler> MSConstSeg; std::unique_ptr<PragmaHandler> MSCodeSeg; std::unique_ptr<PragmaHandler> MSSection; std::unique_ptr<PragmaHandler> MSRuntimeChecks; std::unique_ptr<PragmaHandler> MSIntrinsic; std::unique_ptr<PragmaHandler> MSOptimize; std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; std::unique_ptr<PragmaHandler> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> FPHandler; std::unique_ptr<PragmaHandler> STDCFENVHandler; std::unique_ptr<PragmaHandler> STDCCXLIMITHandler; std::unique_ptr<PragmaHandler> STDCUnknownHandler; std::unique_ptr<PragmaHandler> AttributePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler; std::unique_ptr<CommentHandler> CommentSemaHandler; /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template /// argument list. bool GreaterThanIsOperator; /// ColonIsSacred - When this is false, we aggressively try to recover from /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not /// safe in case statements and a few other things. This is managed by the /// ColonProtectionRAIIObject RAII object. bool ColonIsSacred; /// Parsing OpenMP directive mode. bool OpenMPDirectiveParsing = false; /// When true, we are directly inside an Objective-C message /// send expression. /// /// This is managed by the \c InMessageExpressionRAIIObject class, and /// should not be set directly. bool InMessageExpression; /// Gets set to true after calling ProduceSignatureHelp, it is for a /// workaround to make sure ProduceSignatureHelp is only called at the deepest /// function call. bool CalledSignatureHelp = false; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// Current kind of OpenMP clause OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown; /// RAII class that manages the template parameter depth. class TemplateParameterDepthRAII { unsigned &Depth; unsigned AddedLevels; public: explicit TemplateParameterDepthRAII(unsigned &Depth) : Depth(Depth), AddedLevels(0) {} ~TemplateParameterDepthRAII() { Depth -= AddedLevels; } void operator++() { ++Depth; ++AddedLevels; } void addDepth(unsigned D) { Depth += D; AddedLevels += D; } void setAddedDepth(unsigned D) { Depth = Depth - AddedLevels + D; AddedLevels = D; } unsigned getDepth() const { return Depth; } unsigned getOriginalDepth() const { return Depth - AddedLevels; } }; /// Factory object for creating ParsedAttr objects. AttributeFactory AttrFactory; /// Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; void MaybeDestroyTemplateIds() { if (!TemplateIds.empty() && (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens())) DestroyTemplateIds(); } void DestroyTemplateIds(); /// RAII object to destroy TemplateIdAnnotations where possible, from a /// likely-good position during parsing. struct DestroyTemplateIdAnnotationsRAIIObj { Parser &Self; DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {} ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); } }; /// Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; /// Tracker for '<' tokens that might have been intended to be treated as an /// angle bracket instead of a less-than comparison. /// /// This happens when the user intends to form a template-id, but typoes the /// template-name or forgets a 'template' keyword for a dependent template /// name. /// /// We track these locations from the point where we see a '<' with a /// name-like expression on its left until we see a '>' or '>>' that might /// match it. struct AngleBracketTracker { /// Flags used to rank candidate template names when there is more than one /// '<' in a scope. enum Priority : unsigned short { /// A non-dependent name that is a potential typo for a template name. PotentialTypo = 0x0, /// A dependent name that might instantiate to a template-name. DependentName = 0x2, /// A space appears before the '<' token. SpaceBeforeLess = 0x0, /// No space before the '<' token NoSpaceBeforeLess = 0x1, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName) }; struct Loc { Expr *TemplateName; SourceLocation LessLoc; AngleBracketTracker::Priority Priority; unsigned short ParenCount, BracketCount, BraceCount; bool isActive(Parser &P) const { return P.ParenCount == ParenCount && P.BracketCount == BracketCount && P.BraceCount == BraceCount; } bool isActiveOrNested(Parser &P) const { return isActive(P) || P.ParenCount > ParenCount || P.BracketCount > BracketCount || P.BraceCount > BraceCount; } }; SmallVector<Loc, 8> Locs; /// Add an expression that might have been intended to be a template name. /// In the case of ambiguity, we arbitrarily select the innermost such /// expression, for example in 'foo < bar < baz', 'bar' is the current /// candidate. No attempt is made to track that 'foo' is also a candidate /// for the case where we see a second suspicious '>' token. void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc, Priority Prio) { if (!Locs.empty() && Locs.back().isActive(P)) { if (Locs.back().Priority <= Prio) { Locs.back().TemplateName = TemplateName; Locs.back().LessLoc = LessLoc; Locs.back().Priority = Prio; } } else { Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount, P.BracketCount, P.BraceCount}); } } /// Mark the current potential missing template location as having been /// handled (this happens if we pass a "corresponding" '>' or '>>' token /// or leave a bracket scope). void clear(Parser &P) { while (!Locs.empty() && Locs.back().isActiveOrNested(P)) Locs.pop_back(); } /// Get the current enclosing expression that might hve been intended to be /// a template name. Loc *getCurrent(Parser &P) { if (!Locs.empty() && Locs.back().isActive(P)) return &Locs.back(); return nullptr; } }; AngleBracketTracker AngleBrackets; IdentifierInfo *getSEHExceptKeyword(); /// True if we are within an Objective-C container while parsing C-like decls. /// /// This is necessary because Sema thinks we have left the container /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will /// be NULL. bool ParsingInObjCContainer; /// Whether to skip parsing of function bodies. /// /// This option can be used, for example, to speed up searches for /// declarations/definitions when indexing. bool SkipFunctionBodies; /// The location of the expression statement that is being parsed right now. /// Used to determine if an expression that is being parsed is a statement or /// just a regular sub-expression. SourceLocation ExprStatementTokLoc; /// Flags describing a context in which we're parsing a statement. enum class ParsedStmtContext { /// This context permits declarations in language modes where declarations /// are not statements. AllowDeclarationsInC = 0x1, /// This context permits standalone OpenMP directives. AllowStandaloneOpenMPDirectives = 0x2, /// This context is at the top level of a GNU statement expression. InStmtExpr = 0x4, /// The context of a regular substatement. SubStmt = 0, /// The context of a compound-statement. Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives, LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr) }; /// Act on an expression statement that might be the last statement in a /// GNU statement expression. Checks whether we are actually at the end of /// a statement expression and builds a suitable expression statement. StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx); public: Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); ~Parser() override; const LangOptions &getLangOpts() const { return PP.getLangOpts(); } const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Sema &getActions() const { return Actions; } AttributeFactory &getAttrFactory() { return AttrFactory; } const Token &getCurToken() const { return Tok; } Scope *getCurScope() const { return Actions.getCurScope(); } void incrementMSManglingNumber() const { return Actions.incrementMSManglingNumber(); } Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; typedef Sema::FullExprArg FullExprArg; // Parsing methods. /// Initialize - Warm up the parser. /// void Initialize(); /// Parse the first top-level declaration in a translation unit. bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false); bool ParseTopLevelDecl() { DeclGroupPtrTy Result; return ParseTopLevelDecl(Result); } /// ConsumeToken - Consume the current 'peek token' and lex the next one. /// This does not work with special tokens: string literals, code completion, /// annotation tokens and balanced tokens must be handled using the specific /// consume methods. /// Returns the location of the consumed token. SourceLocation ConsumeToken() { assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } bool TryConsumeToken(tok::TokenKind Expected) { if (Tok.isNot(Expected)) return false; assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return true; } bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { if (!TryConsumeToken(Expected)) return false; Loc = PrevTokLocation; return true; } /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { if (isTokenParen()) return ConsumeParen(); if (isTokenBracket()) return ConsumeBracket(); if (isTokenBrace()) return ConsumeBrace(); if (isTokenStringLiteral()) return ConsumeStringToken(); if (Tok.is(tok::code_completion)) return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() : handleUnexpectedCodeCompletionToken(); if (Tok.isAnnotation()) return ConsumeAnnotationToken(); return ConsumeToken(); } SourceLocation getEndOfPreviousToken() { return PP.getLocForEndOfToken(PrevTokLocation); } /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds /// to the given nullability kind. IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { return Actions.getNullabilityKeyword(nullability); } private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.isOneOf(tok::l_square, tok::r_square); } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); } /// isTokenStringLiteral - True if this token is a string-literal. bool isTokenStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } /// isTokenSpecial - True if this token requires special consumption methods. bool isTokenSpecial() const { return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation(); } /// Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// Return the current token to the token stream and make the given /// token the current token. void UnconsumeToken(Token &Consumed) { Token Next = Tok; PP.EnterToken(Consumed, /*IsReinject*/true); PP.Lex(Tok); PP.EnterToken(Next, /*IsReinject*/true); } SourceLocation ConsumeAnnotationToken() { assert(Tok.isAnnotation() && "wrong consume method"); SourceLocation Loc = Tok.getLocation(); PrevTokLocation = Tok.getAnnotationEndLoc(); PP.Lex(Tok); return Loc; } /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { assert(isTokenParen() && "wrong consume method"); if (Tok.getKind() == tok::l_paren) ++ParenCount; else if (ParenCount) { AngleBrackets.clear(*this); --ParenCount; // Don't let unbalanced )'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { assert(isTokenBracket() && "wrong consume method"); if (Tok.getKind() == tok::l_square) ++BracketCount; else if (BracketCount) { AngleBrackets.clear(*this); --BracketCount; // Don't let unbalanced ]'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { assert(isTokenBrace() && "wrong consume method"); if (Tok.getKind() == tok::l_brace) ++BraceCount; else if (BraceCount) { AngleBrackets.clear(*this); --BraceCount; // Don't let unbalanced }'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation /// phase #6. SourceLocation ConsumeStringToken() { assert(isTokenStringLiteral() && "Should only consume string literals with this method"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// Consume the current code-completion token. /// /// This routine can be called to consume the code-completion token and /// continue processing in special cases where \c cutOffParsing() isn't /// desired, such as token caching or completion with lookahead. SourceLocation ConsumeCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } ///\ brief When we are consuming a code-completion token without having /// matched specific position in the grammar, provide code-completion results /// based on context. /// /// \returns the source location of the code-completion token. SourceLocation handleUnexpectedCodeCompletionToken(); /// Abruptly cut off parsing; mainly used when we have reached the /// code-completion point. void cutOffParsing() { if (PP.isCodeCompletionEnabled()) PP.setCodeCompletionReached(); // Cut off parsing by acting as if we reached the end-of-file. Tok.setKind(tok::eof); } /// Determine if we're at the end of the file or at a transition /// between modules. bool isEofOrEom() { tok::TokenKind Kind = Tok.getKind(); return Kind == tok::eof || Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include; } /// Checks if the \p Level is valid for use in a fold expression. bool isFoldOperator(prec::Level Level) const; /// Checks if the \p Kind is a valid operator for fold expressions. bool isFoldOperator(tok::TokenKind Kind) const; /// Initialize all pragma handlers. void initializePragmaHandlers(); /// Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); /// Handle the annotation token produced for /// #pragma comment... void HandlePragmaMSComment(); void HandlePragmaMSPointersToMembers(); void HandlePragmaMSVtorDisp(); void HandlePragmaMSPragma(); bool HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation); /// Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// Handle the annotation token produced for /// #pragma STDC FENV_ACCESS... void HandlePragmaFEnvAccess(); /// Handle the annotation token produced for /// #pragma float_control void HandlePragmaFloatControl(); /// \brief Handle the annotation token produced for /// #pragma clang fp ... void HandlePragmaFP(); /// Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); bool ParsePragmaAttributeSubjectMatchRuleSet( attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); void HandlePragmaAttribute(); /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. /// /// Note that this differs from the Preprocessor's LookAhead method, because /// the Parser always has one token lexed that the preprocessor doesn't. /// const Token &GetLookAheadToken(unsigned N) { if (N == 0 || Tok.is(tok::eof)) return Tok; return PP.LookAhead(N-1); } public: /// NextToken - This peeks ahead one token and returns it without /// consuming it. const Token &NextToken() { return PP.LookAhead(0); } /// getTypeAnnotation - Read a parsed type out of an annotation token. static TypeResult getTypeAnnotation(const Token &Tok) { if (!Tok.getAnnotationValue()) return TypeError(); return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, TypeResult T) { assert((T.isInvalid() || T.get()) && "produced a valid-but-null type annotation?"); Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr()); } static NamedDecl *getNonTypeAnnotation(const Token &Tok) { return static_cast<NamedDecl*>(Tok.getAnnotationValue()); } static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) { Tok.setAnnotationValue(ND); } static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) { return static_cast<IdentifierInfo*>(Tok.getAnnotationValue()); } static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) { Tok.setAnnotationValue(ND); } /// Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(const Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// Set the primary expression corresponding to the given annotation /// token. static void setExprAnnotation(Token &Tok, ExprResult ER) { Tok.setAnnotationValue(ER.getAsOpaquePointer()); } public: // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to // find a type name by attempting typo correction. bool TryAnnotateTypeOrScopeToken(); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); bool MightBeCXXScopeToken() { return Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super); } bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) { return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext); } private: enum AnnotatedNameKind { /// Annotation has failed and emitted an error. ANK_Error, /// The identifier is a tentatively-declared name. ANK_TentativeDecl, /// The identifier is a template name. FIXME: Add an annotation for that. ANK_TemplateName, /// The identifier can't be resolved. ANK_Unresolved, /// Annotation was successful. ANK_Success }; AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr); /// Push a tok::annot_cxxscope token onto the token stream. void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, /// replacing them with the non-context-sensitive keywords. This returns /// true if the token was replaced. bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { if (!getLangOpts().AltiVec && !getLangOpts().ZVector) return false; if (Tok.getIdentifierInfo() != Ident_vector && Tok.getIdentifierInfo() != Ident_bool && (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) return false; return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); } /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector /// identifier token, replacing it with the non-context-sensitive __vector. /// This returns true if the token was replaced. bool TryAltiVecVectorToken() { if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || Tok.getIdentifierInfo() != Ident_vector) return false; return TryAltiVecVectorTokenOutOfLine(); } bool TryAltiVecVectorTokenOutOfLine(); bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid); /// Returns true if the current token is the identifier 'instancetype'. /// /// Should only be used in Objective-C language modes. bool isObjCInstancetype() { assert(getLangOpts().ObjC); if (Tok.isAnnotation()) return false; if (!Ident_instancetype) Ident_instancetype = PP.getIdentifierInfo("instancetype"); return Tok.getIdentifierInfo() == Ident_instancetype; } /// TryKeywordIdentFallback - For compatibility with system headers using /// keywords as identifiers, attempt to convert the current token to an /// identifier and optionally disable the keyword for the remainder of the /// translation unit. This returns false if the token was not replaced, /// otherwise emits a diagnostic and returns true. bool TryKeywordIdentFallback(bool DisableKeyword); /// Get the TemplateIdAnnotation from the token. TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); /// TentativeParsingAction - An object that is used as a kind of "tentative /// parsing transaction". It gets instantiated to mark the token position and /// after the token consumption is done, Commit() or Revert() is called to /// either "commit the consumed tokens" or revert to the previously marked /// token position. Example: /// /// TentativeParsingAction TPA(*this); /// ConsumeToken(); /// .... /// TPA.Revert(); /// class TentativeParsingAction { Parser &P; PreferredTypeBuilder PrevPreferredType; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser& p) : P(p) { PrevPreferredType = P.PreferredType; PrevTok = P.Tok; PrevTentativelyDeclaredIdentifierCount = P.TentativelyDeclaredIdentifiers.size(); PrevParenCount = P.ParenCount; PrevBracketCount = P.BracketCount; PrevBraceCount = P.BraceCount; P.PP.EnableBacktrackAtThisPos(); isActive = true; } void Commit() { assert(isActive && "Parsing action was finished!"); P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.PP.CommitBacktrackedTokens(); isActive = false; } void Revert() { assert(isActive && "Parsing action was finished!"); P.PP.Backtrack(); P.PreferredType = PrevPreferredType; P.Tok = PrevTok; P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.ParenCount = PrevParenCount; P.BracketCount = PrevBracketCount; P.BraceCount = PrevBraceCount; isActive = false; } ~TentativeParsingAction() { assert(!isActive && "Forgot to call Commit or Revert!"); } }; /// A TentativeParsingAction that automatically reverts in its destructor. /// Useful for disambiguation parses that will always be reverted. class RevertingTentativeParsingAction : private Parser::TentativeParsingAction { public: RevertingTentativeParsingAction(Parser &P) : Parser::TentativeParsingAction(P) {} ~RevertingTentativeParsingAction() { Revert(); } }; class UnannotatedTentativeParsingAction; /// ObjCDeclContextSwitch - An object used to switch context from /// an objective-c decl context to its enclosing decl context and /// back. class ObjCDeclContextSwitch { Parser &P; Decl *DC; SaveAndRestore<bool> WithinObjCContainer; public: explicit ObjCDeclContextSwitch(Parser &p) : P(p), DC(p.getObjCDeclContext()), WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { if (DC) P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); } ~ObjCDeclContextSwitch() { if (DC) P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); } }; /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// /// If a trivial punctuator misspelling is encountered, a FixIt error /// diagnostic is issued and false is returned after recovery. /// /// If the input is malformed, this emits the specified diagnostic and true is /// returned. bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag = diag::err_expected, StringRef DiagMsg = ""); /// The parser expects a semicolon and, if present, will consume it. /// /// If the next token is not a semicolon, this emits the specified diagnostic, /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior /// to the semicolon, consumes that extra token. bool ExpectAndConsumeSemi(unsigned DiagID); /// The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified); /// Return false if the next token is an identifier. An 'expected identifier' /// error is emitted otherwise. /// /// The parser tries to recover from the error by checking if the next token /// is a C++ keyword when parsing Objective-C++. Return false if the recovery /// was successful. bool expectIdentifier(); /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens. enum class CompoundToken { /// A '(' '{' beginning a statement-expression. StmtExprBegin, /// A '}' ')' ending a statement-expression. StmtExprEnd, /// A '[' '[' beginning a C++11 or C2x attribute. AttrBegin, /// A ']' ']' ending a C++11 or C2x attribute. AttrEnd, /// A '::' '*' forming a C++ pointer-to-member declaration. MemberPtr, }; /// Check that a compound operator was written in a "sensible" way, and warn /// if not. void checkCompoundToken(SourceLocation FirstTokLoc, tok::TokenKind FirstTokKind, CompoundToken Op); public: //===--------------------------------------------------------------------===// // Scope manipulation /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the /// parser enters the new scope, and this object's constructor will /// create that new scope. Similarly, once the object is destroyed /// the parser will exit the scope. class ParseScope { Parser *Self; ParseScope(const ParseScope &) = delete; void operator=(const ParseScope &) = delete; public: // ParseScope - Construct a new object to manage a scope in the // parser Self where the new Scope is created with the flags // ScopeFlags, but only when we aren't about to enter a compound statement. ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, bool BeforeCompoundStmt = false) : Self(Self) { if (EnteredScope && !BeforeCompoundStmt) Self->EnterScope(ScopeFlags); else { if (BeforeCompoundStmt) Self->incrementMSManglingNumber(); this->Self = nullptr; } } // Exit - Exit the scope associated with this object now, rather // than waiting until the object is destroyed. void Exit() { if (Self) { Self->ExitScope(); Self = nullptr; } } ~ParseScope() { Exit(); } }; /// Introduces zero or more scopes for parsing. The scopes will all be exited /// when the object is destroyed. class MultiParseScope { Parser &Self; unsigned NumScopes = 0; MultiParseScope(const MultiParseScope&) = delete; public: MultiParseScope(Parser &Self) : Self(Self) {} void Enter(unsigned ScopeFlags) { Self.EnterScope(ScopeFlags); ++NumScopes; } void Exit() { while (NumScopes) { Self.ExitScope(); --NumScopes; } } ~MultiParseScope() { Exit(); } }; /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); /// ExitScope - Pop a scope off the scope stack. void ExitScope(); /// Re-enter the template scopes for a declaration that might be a template. unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D); private: /// RAII object used to modify the scope flags for the current scope. class ParseScopeFlags { Scope *CurScope; unsigned OldFlags; ParseScopeFlags(const ParseScopeFlags &) = delete; void operator=(const ParseScopeFlags &) = delete; public: ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); ~ParseScopeFlags(); }; //===--------------------------------------------------------------------===// // Diagnostic Emission and Error recovery. public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); } private: void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); void CheckNestedObjCContexts(SourceLocation AtLoc); public: /// Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R) { return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | static_cast<unsigned>(R)); } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless StopBeforeMatch is specified). Because we cannot guarantee /// that the token will ever occur, this skips to the next token, or to some /// likely good stopping point. If Flags has StopAtSemi flag, skipping will /// stop at a ';' character. Balances (), [], and {} delimiter tokens while /// skipping. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { return SkipUntil(llvm::makeArrayRef(T), Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2}; return SkipUntil(TokArray, Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2, T3}; return SkipUntil(TokArray, Flags); } bool SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); /// SkipMalformedDecl - Read tokens until we get to some likely good stopping /// point for skipping past a simple-declaration. void SkipMalformedDecl(); /// The location of the first statement inside an else that might /// have a missleading indentation. If there is no /// MisleadingIndentationChecker on an else active, this location is invalid. SourceLocation MisleadingIndentationElseLoc; private: //===--------------------------------------------------------------------===// // Lexing and parsing of C++ inline methods. struct ParsingClass; /// [class.mem]p1: "... the class is regarded as complete within /// - function bodies /// - default arguments /// - exception-specifications (TODO: C++0x) /// - and brace-or-equal-initializers for non-static data members /// (including such things in nested classes)." /// LateParsedDeclarations build the tree of those elements so they can /// be parsed after parsing the top-level class. class LateParsedDeclaration { public: virtual ~LateParsedDeclaration(); virtual void ParseLexedMethodDeclarations(); virtual void ParseLexedMemberInitializers(); virtual void ParseLexedMethodDefs(); virtual void ParseLexedAttributes(); virtual void ParseLexedPragmas(); }; /// Inner node of the LateParsedDeclaration tree that parses /// all its members recursively. class LateParsedClass : public LateParsedDeclaration { public: LateParsedClass(Parser *P, ParsingClass *C); ~LateParsedClass() override; void ParseLexedMethodDeclarations() override; void ParseLexedMemberInitializers() override; void ParseLexedMethodDefs() override; void ParseLexedAttributes() override; void ParseLexedPragmas() override; private: Parser *Self; ParsingClass *Class; }; /// Contains the lexed tokens of an attribute with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. /// FIXME: Perhaps we should change the name of LateParsedDeclaration to /// LateParsedTokens. struct LateParsedAttribute : public LateParsedDeclaration { Parser *Self; CachedTokens Toks; IdentifierInfo &AttrName; IdentifierInfo *MacroII = nullptr; SourceLocation AttrNameLoc; SmallVector<Decl*, 2> Decls; explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc) : Self(P), AttrName(Name), AttrNameLoc(Loc) {} void ParseLexedAttributes() override; void addDecl(Decl *D) { Decls.push_back(D); } }; /// Contains the lexed tokens of a pragma with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. class LateParsedPragma : public LateParsedDeclaration { Parser *Self = nullptr; AccessSpecifier AS = AS_none; CachedTokens Toks; public: explicit LateParsedPragma(Parser *P, AccessSpecifier AS) : Self(P), AS(AS) {} void takeToks(CachedTokens &Cached) { Toks.swap(Cached); } const CachedTokens &toks() const { return Toks; } AccessSpecifier getAccessSpecifier() const { return AS; } void ParseLexedPragmas() override; }; // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { public: LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } bool parseSoon() { return ParseSoon; } private: bool ParseSoon; // Are we planning to parse these shortly after creation? }; /// Contains the lexed tokens of a member function definition /// which needs to be parsed at the end of the class declaration /// after parsing all other member declarations. struct LexedMethod : public LateParsedDeclaration { Parser *Self; Decl *D; CachedTokens Toks; explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {} void ParseLexedMethodDefs() override; }; /// LateParsedDefaultArgument - Keeps track of a parameter that may /// have a default argument that cannot be parsed yet because it /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { explicit LateParsedDefaultArgument(Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr) : Param(P), Toks(std::move(Toks)) { } /// Param - The parameter declaration for this parameter. Decl *Param; /// Toks - The sequence of tokens that comprises the default /// argument expression, not including the '=' or the terminating /// ')' or ','. This will be NULL for parameters that have no /// default argument. std::unique_ptr<CachedTokens> Toks; }; /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration : public LateParsedDeclaration { explicit LateParsedMethodDeclaration(Parser *P, Decl *M) : Self(P), Method(M), ExceptionSpecTokens(nullptr) {} void ParseLexedMethodDeclarations() override; Parser* Self; /// Method - The method declaration. Decl *Method; /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; /// The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; }; /// LateParsedMemberInitializer - An initializer for a non-static class data /// member whose parsing must to be delayed until the class is completely /// defined (C++11 [class.mem]p2). struct LateParsedMemberInitializer : public LateParsedDeclaration { LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) { } void ParseLexedMemberInitializers() override; Parser *Self; /// Field - The field declaration. Decl *Field; /// CachedTokens - The sequence of tokens that comprises the initializer, /// including any leading '='. CachedTokens Toks; }; /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; /// Representation of a class that has been parsed, including /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : TopLevelClass(TopLevelClass), IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) {} /// Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// Whether this class is an __interface. bool IsInterface : 1; /// The class or class template whose definition we are parsing. Decl *TagOrTemplate; /// LateParsedDeclarations - Method declarations, inline definitions and /// nested classes that contain pieces whose parsing will be delayed until /// the top-level class is fully defined. LateParsedDeclarationsContainer LateParsedDeclarations; }; /// The stack of classes that is currently being /// parsed. Nested and local classes will be pushed onto this stack /// when they are parsed, and removed afterward. std::stack<ParsingClass *> ClassStack; ParsingClass &getCurrentClass() { assert(!ClassStack.empty() && "No lexed method stacks!"); return *ClassStack.top(); } /// RAII object used to manage the parsing of a class definition. class ParsingClassDefinition { Parser &P; bool Popped; Sema::ParsingClassState State; public: ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : P(P), Popped(false), State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { } /// Pop this class of the stack. void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(State); } ~ParsingClassDefinition() { if (!Popped) P.PopParsingClass(State); } }; /// Contains information about any template-specific /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, bool isSpecialization, bool lastParameterListWasEmpty = false) : Kind(isSpecialization? ExplicitSpecialization : Template), TemplateParams(TemplateParams), LastParameterListWasEmpty(lastParameterListWasEmpty) { } explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) : Kind(ExplicitInstantiation), TemplateParams(nullptr), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false){ } /// The kind of template we are parsing. enum { /// We are not parsing a template at all. NonTemplate = 0, /// We are parsing a template declaration. Template, /// We are parsing an explicit specialization. ExplicitSpecialization, /// We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// Whether the last template parameter list was empty. bool LastParameterListWasEmpty; SourceRange getSourceRange() const LLVM_READONLY; }; // In ParseCXXInlineMethods.cpp. struct ReenterTemplateScopeRAII; struct ReenterClassScopeRAII; void LexTemplateFunctionForLateParsing(CachedTokens &Toks); void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); Sema::ParsingClassState PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(Sema::ParsingClassState); enum CachedInitKind { CIK_DefaultArgument, CIK_DefaultInitializer }; NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS, SourceLocation PureSpecLoc); void ParseCXXNonStaticMemberInitializer(Decl *VarD); void ParseLexedAttributes(ParsingClass &Class); void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition); void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); void ParseLexedMethodDefs(ParsingClass &Class); void ParseLexedMethodDef(LexedMethod &LM); void ParseLexedMemberInitializers(ParsingClass &Class); void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); void ParseLexedPragmas(ParsingClass &Class); void ParseLexedPragma(LateParsedPragma &LP); bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); bool ConsumeAndStoreConditional(CachedTokens &Toks); bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true) { return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); } bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true); //===--------------------------------------------------------------------===// // C99 6.9: External Definitions. struct ParsedAttributesWithRange : ParsedAttributes { ParsedAttributesWithRange(AttributeFactory &factory) : ParsedAttributes(factory) {} void clear() { ParsedAttributes::clear(); Range = SourceRange(); } SourceRange Range; }; struct ParsedAttributesViewWithRange : ParsedAttributesView { ParsedAttributesViewWithRange() : ParsedAttributesView() {} void clearListOnly() { ParsedAttributesView::clearListOnly(); Range = SourceRange(); } SourceRange Range; }; DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr); bool isDeclarationAfterDeclarator(); bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS); void SkipFunctionBody(); Decl *ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), LateParsedAttrList *LateParsedAttrs = nullptr); void ParseKNRParamDeclarations(Declarator &D); // EndLoc is filled with the location of the last token of the simple-asm. ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc); ExprResult ParseAsmStringLiteral(bool ForAsmLabel); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs); DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &prefixAttrs); class ObjCTypeParamListScope; ObjCTypeParamList *parseObjCTypeParamList(); ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList = true); void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing); void ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc); bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndProtoLoc, bool consumeLastToken); /// Parse the first angle-bracket-delimited clause for an /// Objective-C object or object pointer type, which may be either /// type arguments or protocol qualifiers. void parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols); /// Parse either Objective-C type arguments or protocol qualifiers; if the /// former, also parse protocol qualifiers afterward. void parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken); /// Parse a protocol qualifier type such as '<NSCopying>', which is /// an anachronistic way of writing 'id<NSCopying>'. TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); /// Parse Objective-C type arguments and protocol qualifiers, extending the /// current type with the parsed result. TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc); void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl); DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, ParsedAttributes &prefixAttrs); struct ObjCImplParsingDataRAII { Parser &P; Decl *Dcl; bool HasCFunction; typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; LateParsedObjCMethodContainer LateParsedObjCMethods; ObjCImplParsingDataRAII(Parser &parser, Decl *D) : P(parser), Dcl(D), HasCFunction(false) { P.CurParsedObjCImpl = this; Finished = false; } ~ObjCImplParsingDataRAII(); void finish(SourceRange AtEnd); bool isFinished() const { return Finished; } private: bool Finished; }; ObjCImplParsingDataRAII *CurParsedObjCImpl; void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc, ParsedAttributes &Attrs); DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, objc_nonnull, objc_nullable, objc_null_unspecified, objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; bool isTokIdentifier_in() const; ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx, ParsedAttributes *ParamAttrs); void ParseObjCMethodRequirement(); Decl *ParseObjCMethodPrototype( tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition = true); Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition=true); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); Decl *ParseObjCMethodDefinition(); public: //===--------------------------------------------------------------------===// // C99 6.5: Expressions. /// TypeCastState - State whether an expression is or may be a type cast. enum TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast }; ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpressionInExprEvalContext( TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseCaseExpression(SourceLocation CaseLoc); ExprResult ParseConstraintExpression(); ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause); ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated); ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); /// Control what ParseCastExpression will parse. enum CastParseKind { AnyCastExpr = 0, UnaryExprOnly, PrimaryExprOnly }; ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); /// Returns true if the next token cannot start an expression. bool isNotExpressionStart(); /// Returns true if the next token would start a postfix-expression /// suffix. bool isPostfixExpressionSuffixStart() { tok::TokenKind K = Tok.getKind(); return (K == tok::l_square || K == tok::l_paren || K == tok::period || K == tok::arrow || K == tok::plusplus || K == tok::minusminus); } bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); void checkPotentialAngleBracket(ExprResult &PotentialTemplateName); bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &, const Token &OpToken); bool checkPotentialAngleBracketDelimiter(const Token &OpToken) { if (auto *Info = AngleBrackets.getCurrent(*this)) return checkPotentialAngleBracketDelimiter(*Info, OpToken); return false; } ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); ExprResult ParseUniqueStableNameExpression(); ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange); typedef SmallVector<Expr*, 20> ExprListTy; typedef SmallVector<SourceLocation, 20> CommaLocsTy; /// ParseExpressionList - Used for C/C++ (argument-)expression-list. bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, llvm::function_ref<void()> ExpressionStarts = llvm::function_ref<void()>()); /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs); /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' FoldExpr, // Also allow fold-expression <anything> CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> }; ExprResult ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc); ExprResult ParseCXXAmbiguousParenExpression( ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); ExprResult ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); ExprResult ParseGenericSelectionExpression(); ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); //===--------------------------------------------------------------------===// // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS); bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors, bool EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = false, bool InUsingDeclaration = false); //===--------------------------------------------------------------------===// // C++11 5.1.2: Lambda expressions /// Result of tentatively parsing a lambda-introducer. enum class LambdaIntroducerTentativeParse { /// This appears to be a lambda-introducer, which has been fully parsed. Success, /// This is a lambda-introducer, but has not been fully parsed, and this /// function needs to be called again to parse it. Incomplete, /// This is definitely an Objective-C message send expression, rather than /// a lambda-introducer, attribute-specifier, or array designator. MessageSend, /// This is not a lambda-introducer. Invalid, }; // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); bool ParseLambdaIntroducer(LambdaIntroducer &Intro, LambdaIntroducerTentativeParse *Tentative = nullptr); ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast. ExprResult ParseBuiltinBitCast(); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Type Identification ExprResult ParseCXXTypeid(); //===--------------------------------------------------------------------===// // C++ : Microsoft __uuidof Expression ExprResult ParseCXXUuidof(); //===--------------------------------------------------------------------===// // C++ 5.2.4: C++ Pseudo-Destructor Expressions ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType); //===--------------------------------------------------------------------===// // C++ 9.3.2: C++ 'this' pointer ExprResult ParseCXXThis(); //===--------------------------------------------------------------------===// // C++ 15: C++ Throw Expression ExprResult ParseThrowExpression(); ExceptionSpecificationType tryParseExceptionSpecification( bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens); // EndLoc is filled with the location of the last token of the specification. ExceptionSpecificationType ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges); //===--------------------------------------------------------------------===// // C++0x 8: Function declaration trailing-return-type TypeResult ParseTrailingReturnType(SourceRange &Range, bool MayBeFollowedByDirectInit); //===--------------------------------------------------------------------===// // C++ 2.13.5: C++ Boolean Literals ExprResult ParseCXXBoolLiteral(); //===--------------------------------------------------------------------===// // C++ 5.2.3: Explicit type conversion (functional notation) ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); //===--------------------------------------------------------------------===// // C++ 5.3.4 and 5.3.5: C++ new and delete bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, Declarator &D); void ParseDirectNewDeclarator(Declarator &D); ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start); //===--------------------------------------------------------------------===// // C++ if/switch/while/for condition expression. struct ForRangeInfo; Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, Sema::ConditionKind CK, ForRangeInfo *FRI = nullptr); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // C++ Concepts ExprResult ParseRequiresExpression(); void ParseTrailingRequiresClause(Declarator &D); //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression /// '{' ... ExprResult ParseInitializer() { if (Tok.isNot(tok::l_brace)) return ParseAssignmentExpression(); return ParseBraceInitializer(); } bool MayBeDesignationStart(); ExprResult ParseBraceInitializer(); ExprResult ParseInitializerWithPotentialDesignator( llvm::function_ref<void(const Designation &)> CodeCompleteCB); //===--------------------------------------------------------------------===// // clang Expressions ExprResult ParseBlockLiteralExpression(); // ^{...} //===--------------------------------------------------------------------===// // Objective-C Expressions ExprResult ParseObjCAtExpression(SourceLocation AtLocation); ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); bool isSimpleObjCMessageExpression(); ExprResult ParseObjCMessageExpression(); ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); ExprResult ParseAssignmentExprWithObjCMessageExprStart( SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef SmallVector<Stmt*, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef SmallVector<Expr*, 12> ExprVector; /// A SmallVector of types. typedef SmallVector<ParsedType, 12> TypeVector; StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt); StmtResult ParseStatementOrDeclaration( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(ParsedStmtContext StmtCtx); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs, ParsedStmtContext StmtCtx); StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx, bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); bool ConsumeNullStmt(StmtVector &Stmts); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(StmtResult *InitStmt, Sema::ConditionResult &CondResult, SourceLocation Loc, Sema::ConditionKind CK, SourceLocation *LParenLoc = nullptr, SourceLocation *RParenLoc = nullptr); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// Parse the block; this code is always used. IEB_Parse, /// Skip the block entirely; this code is never used. IEB_Skip, /// Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// The location of the initial keyword. SourceLocation KeywordLoc; /// Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// Nested-name-specifier preceding the name. CXXScopeSpec SS; /// The name we're looking for. UnqualifiedId Name; /// The behavior of this __if_exists or __if_not_exists block /// should. IfExistsBehavior Behavior; }; bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); void ParseMicrosoftIfExistsExternalDeclaration(); void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, ParsedAttributes &AccessAttrs, AccessSpecifier &CurAS); bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk); bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs); //===--------------------------------------------------------------------===// // C++ 6: Statements and Blocks StmtResult ParseCXXTryBlock(); StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); StmtResult ParseCXXCatchBlock(bool FnCatch = false); //===--------------------------------------------------------------------===// // MS: SEH Statements and Blocks StmtResult ParseSEHTryBlock(); StmtResult ParseSEHExceptBlock(SourceLocation Loc); StmtResult ParseSEHFinallyBlock(SourceLocation Loc); StmtResult ParseSEHLeaveStatement(); //===--------------------------------------------------------------------===// // Objective-C Statements StmtResult ParseObjCAtStatement(SourceLocation atLoc, ParsedStmtContext StmtCtx); StmtResult ParseObjCTryStmt(SourceLocation atLoc); StmtResult ParseObjCThrowStmt(SourceLocation atLoc); StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); //===--------------------------------------------------------------------===// // C99 6.7: Declarations. /// A context for parsing declaration specifiers. TODO: flesh this /// out, there are other significant restrictions on specifiers than /// would be best implemented in the parser. enum class DeclSpecContext { DSC_normal, // normal context DSC_class, // class context, enables 'friend' DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list DSC_trailing, // C++11 trailing-type-specifier in a trailing return type DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration DSC_top_level, // top-level/namespace declaration context DSC_template_param, // template parameter context DSC_template_type_arg, // template type argument context DSC_objc_method_result, // ObjC method result context, enables 'instancetype' DSC_condition // condition declaration context }; /// Is this a context in which we are parsing just a type-specifier (or /// trailing-type-specifier)? static bool isTypeSpecifier(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: return false; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return true; } llvm_unreachable("Missing DeclSpecContext case"); } /// Whether a defining-type-specifier is permitted in a given context. enum class AllowDefiningTypeSpec { /// The grammar doesn't allow a defining-type-specifier here, and we must /// not parse one (eg, because a '{' could mean something else). No, /// The grammar doesn't allow a defining-type-specifier here, but we permit /// one for error recovery purposes. Sema will reject. NoButErrorRecovery, /// The grammar allows a defining-type-specifier here, even though it's /// always invalid. Sema will reject. YesButInvalid, /// The grammar allows a defining-type-specifier here, and one can be valid. Yes }; /// Is this a context in which we are parsing defining-type-specifiers (and /// so permit class and enum definitions in addition to non-defining class and /// enum elaborated-type-specifiers)? static AllowDefiningTypeSpec isDefiningTypeSpecifierContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_alias_declaration: case DeclSpecContext::DSC_objc_method_result: return AllowDefiningTypeSpec::Yes; case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_template_param: return AllowDefiningTypeSpec::YesButInvalid; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: return AllowDefiningTypeSpec::NoButErrorRecovery; case DeclSpecContext::DSC_trailing: return AllowDefiningTypeSpec::No; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which an opaque-enum-declaration can appear? static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: return true; case DeclSpecContext::DSC_alias_declaration: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which we can perform class template argument /// deduction? static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_type_specifier: return true; case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Information on a C++0x for-range-initializer found while parsing a /// declaration which turns out to be a for-range-declaration. struct ForRangeInit { SourceLocation ColonLoc; ExprResult RangeExpr; bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } }; struct ForRangeInfo : ForRangeInit { StmtResult LoopVar; }; DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, SourceLocation *DeclSpecStart = nullptr); DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr, SourceLocation *DeclSpecStart = nullptr); bool MightBeDeclarator(DeclaratorContext Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context, SourceLocation *DeclEnd = nullptr, ForRangeInit *FRI = nullptr); Decl *ParseDeclarationAfterDeclarator(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); bool ParseAsmAttributesAfterDeclarator(Declarator &D); Decl *ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ForRangeInit *FRI = nullptr); Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); /// When in code-completion, skip parsing of the function/method body /// unless the body contains the code-completion point. /// /// \returns true if the function body was skipped. bool trySkippingFunctionBody(); bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); void ParseDeclarationSpecifiers( DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal, LateParsedAttrList *LateAttrs = nullptr); bool DiagnoseMissingSemiAfterTagDefinition( DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); void ParseSpecifierQualifierList( DeclSpec &DS, AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType, RecordDecl *TagDecl); void ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); bool isTypeSpecifierQualifier(); /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool isKnownToBeTypeSpecifier(const Token &Tok) const; /// Return true if we know that we are definitely looking at a /// decl-specifier, and isn't part of an expression such as a function-style /// cast. Return false if it's no a decl-specifier, or we're not sure. bool isKnownToBeDeclarationSpecifier() { if (getLangOpts().CPlusPlus) return isCXXDeclarationSpecifier() == TPResult::True; return isDeclarationSpecifier(true); } /// isDeclarationStatement - Disambiguates between a declaration or an /// expression statement, when parsing function bodies. /// Returns true for declaration, false for expression. bool isDeclarationStatement() { if (getLangOpts().CPlusPlus) return isCXXDeclarationStatement(); return isDeclarationSpecifier(true); } /// isForInitDeclaration - Disambiguates between a declaration or an /// expression in the context of the C 'clause-1' or the C++ // 'for-init-statement' part of a 'for' statement. /// Returns true for declaration, false for expression. bool isForInitDeclaration() { if (getLangOpts().OpenMP) Actions.startOpenMPLoop(); if (getLangOpts().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// Starting with a scope specifier, identifier, or /// template-id that refers to the current class, determine whether /// this is a constructor declarator. bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); /// Specifies the context in which type-id/expression /// disambiguation will occur. enum TentativeCXXTypeIdContext { TypeIdInParens, TypeIdUnambiguous, TypeIdAsTemplateArgument }; /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know /// whether the parens contain an expression or a type-id. /// Returns true for a type-id and false for an expression. bool isTypeIdInParens(bool &isAmbiguous) { if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdInParens, isAmbiguous); isAmbiguous = false; return isTypeSpecifierQualifier(); } bool isTypeIdInParens() { bool isAmbiguous; return isTypeIdInParens(isAmbiguous); } /// Checks if the current tokens form type-id or expression. /// It is similar to isTypeIdInParens but does not suppose that type-id /// is in parenthesis. bool isTypeIdUnambiguously() { bool IsAmbiguous; if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); return isTypeSpecifierQualifier(); } /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. bool isCXXDeclarationStatement(); /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. bool isCXXSimpleDeclaration(bool AllowForRangeDecl); /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); struct ConditionDeclarationOrInitStatementState; enum class ConditionOrInitStatement { Expression, ///< Disambiguated as an expression (either kind). ConditionDecl, ///< Disambiguated as the declaration form of condition. InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. ForRangeDecl, ///< Disambiguated as a for-range declaration. Error ///< Can't be any of the above! }; /// Disambiguates between the different kinds of things that can happen /// after 'if (' or 'switch ('. This could be one of two different kinds of /// declaration (depending on whether there is a ';' later) or an expression. ConditionOrInitStatement isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt, bool CanBeForRangeDecl); bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); bool isCXXTypeId(TentativeCXXTypeIdContext Context) { bool isAmbiguous; return isCXXTypeId(Context, isAmbiguous); } /// TPResult - Used as the result value for functions whose purpose is to /// disambiguate C++ constructs by "tentatively parsing" them. enum class TPResult { True, False, Ambiguous, Error }; /// Determine whether we could have an enum-base. /// /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise /// only consider this to be an enum-base if the next token is a '{'. /// /// \return \c false if this cannot possibly be an enum base; \c true /// otherwise. bool isEnumBase(bool AllowSemi); /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a /// declaration specifier, TPResult::False if it is not, /// TPResult::Ambiguous if it could be either a decl-specifier or a /// function-style cast, and TPResult::Error if a parsing error was /// encountered. If it could be a braced C++11 function-style cast, returns /// BracedCastResult. /// Doesn't consume tokens. TPResult isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, bool *InvalidAsDeclSpec = nullptr); /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or /// \c TPResult::Ambiguous, determine whether the decl-specifier would be /// a type-specifier other than a cv-qualifier. bool isCXXDeclarationSpecifierAType(); /// Determine whether the current token sequence might be /// '<' template-argument-list '>' /// rather than a less-than expression. TPResult isTemplateArgumentList(unsigned TokensToSkip); /// Determine whether an '(' after an 'explicit' keyword is part of a C++20 /// 'explicit(bool)' declaration, in earlier language modes where that is an /// extension. TPResult isExplicitBool(); /// Determine whether an identifier has been tentatively declared as a /// non-type. Such tentative declarations should not be found to name a type /// during a tentative parse, but also should not be annotated as a non-type. bool isTentativelyDeclared(IdentifierInfo *II); // "Tentative parsing" functions, used for disambiguation. If a parsing error // is encountered they will return TPResult::Error. // Returning TPResult::True/False indicates that the ambiguity was // resolved and tentative parsing may stop. TPResult::Ambiguous indicates // that more tentative parsing is necessary for disambiguation. // They all consume tokens, so backtracking should be used after calling them. TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); TPResult TryParseTypeofSpecifier(); TPResult TryParseProtocolQualifiers(); TPResult TryParsePtrOperatorSeq(); TPResult TryParseOperatorId(); TPResult TryParseInitDeclaratorList(); TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, bool mayHaveDirectInit = false); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); /// Try to skip a possibly empty sequence of 'attribute-specifier's without /// full validation of the syntactic structure of attributes. bool TrySkipAttributes(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, DeclaratorContext Context = DeclaratorContext::TypeNameContext, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); /// Are [[]] attributes enabled? bool standardAttributesAllowed() const { const LangOptions &LO = getLangOpts(); return LO.DoubleSquareBracketAttributes; } // Check for the start of an attribute-specifier-seq in a context where an // attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!standardAttributesAllowed()) return; if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && Tok.isNot(tok::kw_alignas)) return; DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); } void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation); void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); // FixItLoc = possible correct location for the attributes void ProhibitAttributes(ParsedAttributesWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clear(); } void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clearListOnly(); } void DiagnoseProhibitedAttributes(const SourceRange &Range, SourceLocation FixItLoc); // Forbid C++11 and C2x attributes that appear on certain syntactic locations // which standard permits but we don't supported yet, for example, attributes // appertain to decl specifiers. void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, unsigned DiagID); /// Skip C++11 and C2x attributes and return the end location of the /// last one. /// \returns SourceLocation() if there are no attributes. SourceLocation SkipCXX11Attributes(); /// Diagnose and skip C++11 and C2x attributes that appear in syntactic /// locations where attributes are not allowed. void DiagnoseAndSkipCXX11Attributes(); /// Parses syntax-generic attribute arguments for attributes which are /// known to the implementation, and adds them to the given ParsedAttributes /// list with the given attribute syntax. Returns the number of arguments /// parsed for the attribute. unsigned ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseGNUAttributes(Declarator &D, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributes attrs(AttrFactory); SourceLocation endLoc; ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D); D.takeAttributes(attrs, endLoc); } } void MaybeParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) ParseGNUAttributes(attrs, endLoc, LateAttrs); } void ParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr); void ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); unsigned ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseCXX11Attributes(Declarator &D) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } bool MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); return true; } return false; } void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) ParseCXX11Attributes(attrs, endLoc); } void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, SourceLocation *EndLoc = nullptr); void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *EndLoc = nullptr); /// Parses a C++11 (or C2x)-style attribute argument list. Returns true /// if this results in adding an attribute to the ParsedAttributes list. bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc); IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) ParseMicrosoftAttributes(attrs, endLoc); } void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); void ParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr); void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr) { const auto &LO = getLangOpts(); if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) ParseMicrosoftDeclSpecs(Attrs, End); } void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr); bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs); void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); SourceLocation SkipExtendedMicrosoftTypeAttributes(); void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); void ParseBorlandTypeAttributes(ParsedAttributes &attrs); void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); void ParseOpenCLQualifiers(ParsedAttributes &Attrs); /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0 /// or higher. /// \return false if error happens. bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) { if (getLangOpts().OpenCL) return ParseOpenCLUnrollHintAttribute(Attrs); return true; } /// Parses opencl_unroll_hint attribute. /// \return false if error happens. bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs); /// Parses intelfpga:: and clang:: loop attributes if the language is SYCL bool MaybeParseSYCLLoopAttributes(ParsedAttributes &Attrs) { if (getLangOpts().SYCLIsDevice || getLangOpts().SYCLIsHost) return ParseSYCLLoopAttributes(Attrs); return true; } bool ParseSYCLLoopAttributes(ParsedAttributes &Attrs); void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); VersionTuple ParseVersionTuple(SourceRange &Range); void ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); Optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeofSpecifier(DeclSpec &DS); SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, SourceLocation StartLoc, SourceLocation EndLoc); void ParseUnderlyingTypeSpecifier(DeclSpec &DS); void ParseAtomicSpecifier(DeclSpec &DS); ExprResult ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc); void ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *endLoc = nullptr); ExprResult ParseExtIntegerArgument(); VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { return isCXX11VirtSpecifier(Tok); } void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc); bool isCXX11FinalKeyword() const; /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to /// enter a new C++ declarator scope and exit it when the function is /// finished. class DeclaratorScopeObj { Parser &P; CXXScopeSpec &SS; bool EnteredScope; bool CreatedScope; public: DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} void EnterDeclaratorScope() { assert(!EnteredScope && "Already entered the scope!"); assert(SS.isSet() && "C++ scope was not set!"); CreatedScope = true; P.EnterScope(0); // Not a decl scope. if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) EnteredScope = true; } ~DeclaratorScopeObj() { if (EnteredScope) { assert(SS.isSet() && "C++ scope was cleared ?"); P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); } if (CreatedScope) P.ExitScope(); } }; /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. typedef void (Parser::*DirectDeclParseFunction)(Declarator&); void ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser); enum AttrRequirements { AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. AR_GNUAttributesParsed = 1 << 1, AR_CXX11AttributesParsed = 1 << 2, AR_DeclspecAttributesParsed = 1 << 3, AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed, AR_VendorAttributesParsed = AR_GNUAttributesParsed | AR_DeclspecAttributesParsed }; void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); void InitCXXThisScopeForDeclaratorIfRelevant( const Declarator &D, const DeclSpec &DS, llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( DeclaratorContext DeclaratorContext, ParsedAttributes &attrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc); void ParseBracketDeclarator(Declarator &D); void ParseMisplacedBracketDeclarator(Declarator &D); //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] /// The kind of attribute specifier we have found. enum CXX11AttributeKind { /// This is not an attribute specifier. CAK_NotAttributeSpecifier, /// This should be treated as an attribute-specifier. CAK_AttributeSpecifier, /// The next tokens are '[[', but this is not an attribute-specifier. This /// is ill-formed by C++11 [dcl.attr.grammar]p6. CAK_InvalidAttributeSpecifier }; CXX11AttributeKind isCXX11AttributeSpecifier(bool Disambiguate = false, bool OuterMightBeMessageSend = false); void DiagnoseUnexpectedNamespace(NamedDecl *Context); DeclGroupPtrTy ParseNamespace(DeclaratorContext Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); struct InnerNamespaceInfo { SourceLocation NamespaceLoc; SourceLocation InlineLoc; SourceLocation IdentLoc; IdentifierInfo *Ident; }; using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>; void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs, unsigned int index, SourceLocation &InlineLoc, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context); Decl *ParseExportDeclaration(); DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); struct UsingDeclarator { SourceLocation TypenameLoc; CXXScopeSpec SS; UnqualifiedId Name; SourceLocation EllipsisLoc; void clear() { TypenameLoc = EllipsisLoc = SourceLocation(); SS.clear(); Name.clear(); } }; bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D); DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none); Decl *ParseAliasDeclarationAfterDeclarator( const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, ParsedAttributes &Attrs, Decl **OwnedType = nullptr); Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. bool isValidAfterTypeSpecifier(bool CouldBeBitfield); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl); void ParseCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl); ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc); bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateAttrs); void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, VirtSpecifiers &VS); DeclGroupPtrTy ParseCXXClassMemberDeclaration( AccessSpecifier AS, ParsedAttributes &Attr, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ParsingDeclRAIIObject *DiagsFromTParams = nullptr); DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, DeclSpec::TST TagType, Decl *Tag); void ParseConstructorInitializer(Decl *ConstructorDecl); MemInitResult ParseMemInitializer(Decl *ConstructorDecl); void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl); //===--------------------------------------------------------------------===// // C++ 10: Derived classes [class.derived] TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation); void ParseBaseClause(Decl *ClassDecl); BaseResult ParseBaseSpecifier(Decl *ClassDecl); AccessSpecifier getAccessSpecifierIfPresent() const; bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId); bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result); //===--------------------------------------------------------------------===// // OpenMP: Directives and clauses. /// Parse clauses for '#pragma omp declare simd'. DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse a property kind into \p TIProperty for the selector set \p Set and /// selector \p Selector. void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty, llvm::omp::TraitSet Set, llvm::omp::TraitSelector Selector, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector kind into \p TISelector for the selector set \p Set. void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector set kind into \p TISet. void parseOMPTraitSetKind(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context property. void parseOMPContextProperty(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context selector. void parseOMPContextSelector(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &SeenSelectors); /// Parses an OpenMP context selector set. void parseOMPContextSelectorSet(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets); /// Parses OpenMP context selectors. bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI); /// Parse a `match` clause for an '#pragma omp declare variant'. Return true /// if there was an error. bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI); /// Parse clauses for '#pragma omp declare variant'. void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse clauses for '#pragma omp declare target'. DeclGroupPtrTy ParseOMPDeclareTargetClauses(); /// Parse '#pragma omp end declare target'. void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if /// it is not the current token. void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind); /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error /// that the "end" matching the "begin" directive of kind \p BeginKind was not /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`. void parseOMPEndDirective(OpenMPDirectiveKind BeginKind, OpenMPDirectiveKind ExpectedKind, OpenMPDirectiveKind FoundKind, SourceLocation MatchingLoc, SourceLocation FoundLoc, bool SkipUntilOpenMPEnd); /// Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// Parses initializer for provided omp_priv declaration inside the reduction /// initializer. void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); /// Parses 'omp declare mapper' directive. DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS); /// Parses variable declaration in 'omp declare mapper' directive. TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range, DeclarationName &Name, AccessSpecifier AS = AS_none); /// Tries to parse cast part of OpenMP array shaping operation: /// '[' expression ']' { '[' expression ']' } ')'. bool tryParseOpenMPArrayShapingCastPart(); /// Parses simple list of variables. /// /// \param Kind Kind of the directive. /// \param Callback Callback function to be called for the list elements. /// \param AllowScopeSpecifier true, if the variables can have fully /// qualified names. /// bool ParseOpenMPSimpleVarList( OpenMPDirectiveKind Kind, const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & Callback, bool AllowScopeSpecifier); /// Parses declarative or executable directive. /// /// \param StmtCtx The context in which we're parsing the directive. StmtResult ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx); /// Parses clause of kind \a CKind for directive of a kind \a Kind. /// /// \param DKind Kind of current directive. /// \param CKind Kind of current clause. /// \param FirstClause true, if this is the first clause of a kind \a CKind /// in current directive. /// OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause); /// Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param DKind Directive kind. /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false); /// Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses and creates OpenMP 5.0 iterators expression: /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier = /// <range-specification> }+ ')' ExprResult ParseOpenMPIteratorsExpr(); /// Parses allocators and traits in the context of the uses_allocator clause. /// Expected format: /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')' OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind); public: /// Parses simple expression in parens for single-expression clauses of OpenMP /// constructs. /// \param RLoc Returned location of right paren. ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand = false); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *DepModOrTailExpr = nullptr; SourceLocation ColonLoc; SourceLocation RLoc; CXXScopeSpec ReductionOrMapperIdScopeSpec; DeclarationNameInfo ReductionOrMapperId; int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or ///< lastprivate clause. SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> MapTypeModifiers; SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> MapTypeModifiersLoc; SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers> MotionModifiers; SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc; bool IsMapTypeImplicit = false; SourceLocation ExtraModifierLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result); /// Parses the mapper modifier in map, to, and from clauses. bool parseMapperModifier(OpenMPVarListDataTy &Data); /// Parses map-type-modifiers in map clause. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) bool parseMapTypeModifiers(OpenMPVarListDataTy &Data); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS); Decl *ParseSingleDeclarationAfterTemplate( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams); TPResult isStartOfTemplateTypeParameter(); NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); bool isTypeConstraintAnnotation(); bool TryAnnotateTypeConstraint(); NamedDecl * ParseConstrainedTemplateTypeParameter(unsigned Depth, unsigned Position); void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName); void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D); // C++ 14.3: Template arguments [temp.arg] typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc, SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true, bool TypeConstraint = false); void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS, bool IsClassName = false); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(DeclaratorContext Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); // C++2a: Template, concept definition [temp] Decl * ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl); Decl *ParseModuleImport(SourceLocation AtLoc); bool parseMisplacedModuleImport(); bool tryParseMisplacedModuleImport() { tok::TokenKind Kind = Tok.getKind(); if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include) return parseMisplacedModuleImport(); return false; } bool ParseModuleName( SourceLocation UseLoc, SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, bool IsImport); //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); //===--------------------------------------------------------------------===// // Preprocessor code-completion pass-through void CodeCompleteDirective(bool InConditional) override; void CodeCompleteInConditionalExclusion() override; void CodeCompleteMacroName(bool IsDefinition) override; void CodeCompletePreprocessorExpression() override; void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) override; void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override; void CodeCompleteNaturalLanguage() override; class GNUAsmQualifiers { unsigned Qualifiers = AQ_unspecified; public: enum AQ { AQ_unspecified = 0, AQ_volatile = 1, AQ_inline = 2, AQ_goto = 4, }; static const char *getQualifierName(AQ Qualifier); bool setAsmQualifier(AQ Qualifier); inline bool isVolatile() const { return Qualifiers & AQ_volatile; }; inline bool isInline() const { return Qualifiers & AQ_inline; }; inline bool isGoto() const { return Qualifiers & AQ_goto; } }; bool isGCCAsmStatement(const Token &TokAfterAsm) const; bool isGNUAsmQualifier(const Token &TokAfterAsm) const; GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const; bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ); }; } // end namespace clang #endif
simplex.h
/* Copyright (c) 2007-2012 Eliot Eshelman * * 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 3 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, see <http://www.gnu.org/licenses/>. * */ #ifndef _SIMPLEX_NOISE_H_ #define _SIMPLEX_NOISE_H_ #include "noise.h" // The gradients are the midpoints of the vertices of a cube. static const int grad3[12][3] = { {1,1,0}, {-1,1,0}, {1,-1,0}, {-1,-1,0}, {1,0,1}, {-1,0,1}, {1,0,-1}, {-1,0,-1}, {0,1,1}, {0,-1,1}, {0,1,-1}, {0,-1,-1} }; // Permutation table. The same list is repeated twice. static const int perm[512] = { 151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142, 8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117, 35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71, 134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41, 55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208, 89, 18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226, 250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182, 189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43, 172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97, 228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239, 107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180, 151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142, 8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117, 35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71, 134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41, 55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208, 89, 18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226, 250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182, 189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43, 172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97, 228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239, 107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 }; namespace render_kinect { class SimplexNoise : public Noise { public: SimplexNoise( int width, int height, float scale) : Noise(width , height), scale_(scale) { assert(scale>0.0 && scale_<1.0 ); }; void generateNoiseField( cv::Mat &noise_field) { noise_field = cv::Mat(height_,width_,CV_32FC1); #if HAVE_OMP #pragma omp parallel for #endif for (int r=0; r<height_; ++r) { float* noise_i = noise_field.ptr<float>(r); for (int c=0; c<width_; ++c) { noise_i[c] = raw_noise_2d(r,c) * scale_; //noise_i[c] = octave_noise_2d(2,0.2,5,r,c) * scale_; } } } private: float scale_; // 2D Multi-octave Simplex noise. // // For each octave, a higher frequency/lower amplitude function will be added to the original. // The higher the persistence [0-1], the more of each succeeding octave will be added. float octave_noise_2d( const float octaves, const float persistence, const float scale, const float x, const float y ) { float total = 0; float frequency = scale; float amplitude = 1; // We have to keep track of the largest possible amplitude, // because each octave adds more, and we need a value in [-1, 1]. float maxAmplitude = 0; for (int i=0; i < octaves; i++) { total += raw_noise_2d( x * frequency, y * frequency ) * amplitude; frequency *= 2; maxAmplitude += amplitude; amplitude *= persistence; } return total / maxAmplitude; } // 2D raw Simplex noise float raw_noise_2d( const float x, const float y ) { // Noise contributions from the three corners float n0, n1, n2; // Skew the input space to determine which simplex cell we're in float F2 = 0.5 * (sqrtf(3.0) - 1.0); // Hairy factor for 2D float s = (x + y) * F2; int i = fastfloor( x + s ); int j = fastfloor( y + s ); float G2 = (3.0 - sqrtf(3.0)) / 6.0; float t = (i + j) * G2; // Unskew the cell origin back to (x,y) space float X0 = i-t; float Y0 = j-t; // The x,y distances from the cell origin float x0 = x-X0; float y0 = y-Y0; // For the 2D case, the simplex shape is an equilateral triangle. // Determine which simplex we are in. int i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords if(x0>y0) {i1=1; j1=0;} // lower triangle, XY order: (0,0)->(1,0)->(1,1) else {i1=0; j1=1;} // upper triangle, YX order: (0,0)->(0,1)->(1,1) // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where // c = (3-sqrt(3))/6 float x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords float y1 = y0 - j1 + G2; float x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords float y2 = y0 - 1.0 + 2.0 * G2; // Work out the hashed gradient indices of the three simplex corners int ii = i & 255; int jj = j & 255; int gi0 = perm[ii+perm[jj]] % 12; int gi1 = perm[ii+i1+perm[jj+j1]] % 12; int gi2 = perm[ii+1+perm[jj+1]] % 12; // Calculate the contribution from the three corners float t0 = 0.5 - x0*x0-y0*y0; if (t0<0) n0 = 0.0; else { t0 *= t0; n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient } float t1 = 0.5 - x1*x1-y1*y1; if (t1<0) n1 = 0.0; else { t1 *= t1; n1 = t1 * t1 * dot(grad3[gi1], x1, y1); } float t2 = 0.5 - x2*x2-y2*y2; if (t2<0) n2 = 0.0; else { t2 *= t2; n2 = t2 * t2 * dot(grad3[gi2], x2, y2); } // Add contributions from each corner to get the final noise value. // The result is scaled to return values in the interval [-1,1]. return 70.0 * (n0 + n1 + n2); } int fastfloor( const float x ) { return x > 0 ? (int) x : (int) x - 1; } float dot( const int* g, const float x, const float y ) { return g[0]*x + g[1]*y; } float dot( const int* g, const float x, const float y, const float z ) { return g[0]*x + g[1]*y + g[2]*z; } float dot( const int* g, const float x, const float y, const float z, const float w ) { return g[0]*x + g[1]*y + g[2]*z + g[3]*w; } }; } #endif // _NOISE_H_
traversal_temp.h
#ifndef traversal_h #define traversal_h #include "logger.h" #include "thread.h" #include "types.h" #if EXAFMM_COUNT_KERNEL #define countKernel(N) N++ #else #define countKernel(N) #endif namespace exafmm { template<typename Kernel> class Traversal { typedef typename Kernel::Bodies Bodies; //!< Vector of bodies typedef typename Kernel::Cells Cells; //!< Vector of cells typedef typename Kernel::B_iter B_iter; //!< Iterator of body vector typedef typename Kernel::C_iter C_iter; //!< Iterator of cell vecto private: const int nspawn; //!< Threshold of NBODY for spawning new threads const int images; //!< Number of periodic image sublevels const char * path; //!< Path to save files int (* listOffset)[3]; //!< Offset in interaction lists int (* lists)[3]; //!< Interaction lists #if EXAFMM_COUNT_KERNEL real_t numP2P; //!< Number of P2P kernel calls real_t numM2L; //!< Number of M2L kernel calls #endif C_iter Ci0; //!< Iterator of first target cell C_iter Cj0; //!< Iterator of first source cell private: #if EXAFMM_COUNT_LIST //! Accumulate interaction list size of cells void countList(C_iter Ci, C_iter Cj, bool mutual, bool isP2P) { if (isP2P) Ci->numP2P++; // If P2P, increment P2P counter of target cell else Ci->numM2L++; // Else, increment M2L counter of target cell if (mutual) { // If mutual interaction in on if (isP2P) Cj->numP2P++; // If P2P, increment P2P counter of source cell else Cj->numM2L++; // Else, increment M2L counter of source cell } // End if for mutual interaction } #else void countList(C_iter, C_iter, bool, bool) {} #endif #if EXAFMM_USE_WEIGHT //! Accumulate interaction weights of cells void countWeight(C_iter Ci, C_iter Cj, bool mutual, real_t weight) { Ci->WEIGHT += weight; // Increment weight of target cell if (mutual) Cj->WEIGHT += weight; // Increment weight of source cell } #else void countWeight(C_iter, C_iter, bool, real_t) {} #endif //! Get level from key int getLevel(uint64_t key) { int level = -1; // Initialize level while( int(key) >= 0 ) { // While key has level offsets to subtract level++; // Increment level key -= 1 << 3*level; // Subtract level offset } // End while loop for level offsets return level; // Return level } //! Get 3-D index from key ivec3 getIndex(uint64_t key) { int level = -1; // Initialize level while( int(key) >= 0 ) { // While key has level offsets to subtract level++; // Increment level key -= 1 << 3*level; // Subtract level offset } // End while loop for level offsets key += 1 << 3*level; // Compensate for over-subtraction level = 0; // Initialize level ivec3 iX = 0; // Initialize 3-D index int d = 0; // Initialize dimension while( key > 0 ) { // While key has bits to shift iX[d] += (key % 2) * (1 << level); // Deinterleave key bits to 3-D bits key >>= 1; // Shift bits in key d = (d+1) % 3; // Increment dimension if( d == 0 ) level++; // Increment level } // End while loop for key bits to shift return iX; // Return 3-D index } //! Get 3-D index from periodic key ivec3 getPeriodicIndex(int key) { ivec3 iX; // Initialize 3-D periodic index iX[0] = key % 3; // x periodic index iX[1] = (key / 3) % 3; // y periodic index iX[2] = key / 9; // z periodic index iX -= 1; // {0,1,2} -> {-1,0,1} return iX; // Return 3-D periodic index } //! Get interaction list void getList(int itype, int icell, int * list, int * periodicKey, int & numList) { int ilast = listOffset[icell][itype]; // Initialize list pointer numList = 0; // Initialize list size while (ilast >= 0) { // While pointer exists if (lists[ilast][1] >= 0) { // If pointer is valid list[numList] = lists[ilast][1]; // Load interaction list periodicKey[numList] = lists[ilast][2]; // Load periodic key numList++; // Increment list size } // End if for valid pointer ilast = lists[ilast][0]; // Increment pointer } // End while loop for pointer existence } //! Set one interaction list void setList(int itype, int icell, int list, int periodicKey, int & numLists) { lists[numLists][0] = listOffset[icell][itype]; // Store list pointer lists[numLists][1] = list; // Store list lists[numLists][2] = periodicKey; // Store periodicKey listOffset[icell][itype] = numLists; // Store list size numLists++; // Increment list size } //! Set all interaction lists void setLists(Cells & icells) { int numCells = icells.size(); // Number of cells int childs[216], neighbors[27]; // Array of parents' neighbors' children and neighbors int childKeys[216], neighborKeys[27]; // Periodic keys for (int i=0; i<numCells; i++) { // Loop over number of cells for (int j=0; j<3; j++) { // Loop over list types listOffset[i][j] = -1; // Set initial value to -1 } // End loop over list types } // End loop over number of cells int numLists = 0; // Initialize number of lists if (images == 0) { // If non-periodic boundary condition setList(2, 0, 0, 13, numLists); // Push root cell into list } else { // If periodic boundary condition for (int i=0; i<27; i++) { // Loop over periodic images setList(2, 0, 0, i, numLists); // Push root cell into list } // End loop over periodic images } // End if for periodic boundary condition for (int icell=1; icell<numCells; icell++) { // Loop over target cells C_iter Ci = Ci0 + icell; // Iterator of current target cell int iparent = Ci->IPARENT; // Index of parent target cell int numNeighbors; // Number of neighbor parents getList(2, iparent, neighbors, neighborKeys, numNeighbors);// Get list of neighbors ivec3 iX = getIndex(Ci->ICELL); // Get 3-D index from key int nchilds = 0; // Initialize number of parents' neighbors' children for (int i=0; i<numNeighbors; i++) { // Loop over parents' neighbors int jparent = neighbors[i]; // Index of parent source cell int parentKey = neighborKeys[i]; // Periodic key of parent source cell C_iter Cj = Cj0 + jparent; // Iterator of parent source cell for (int j=0; j<Cj->NCHILD; j++) { // Loop over children of parents' neighbors int jcell = Cj->ICHILD+j; // Index of source cell childs[nchilds] = jcell; // Store index of source cell childKeys[nchilds] = parentKey; // Store periodic key of source cell nchilds++; // Increment number of parents' neighbors' children } // End loop over children of parents' neighbors } // End loop over parents' neighbors for (int i=0; i<nchilds; i++) { // Loop over children of parents' neighbors int jcell = childs[i]; // Index of source cell int periodicKey = childKeys[i]; // Periodic key of source cell C_iter Cj = Cj0 + jcell; // Iterator of source cell ivec3 jX = getIndex(Cj->ICELL); // 3-D index of source cell ivec3 pX = getPeriodicIndex(periodicKey); // 3-D periodic index of source cell int level = getLevel(Cj->ICELL); // Level of source cell jX += pX * (1 << level); // Periodic image shift if (iX[0]-1 <= jX[0] && jX[0] <= iX[0]+1 && // If neighbor in x dimension and iX[1]-1 <= jX[1] && jX[1] <= iX[1]+1 && // in y dimension and iX[2]-1 <= jX[2] && jX[2] <= iX[2]+1) { // in z dimension setList(2, icell, jcell, periodicKey, numLists); // Store neighbor list (not P2P unless leaf) } else { // If non-neighbor setList(1, icell, jcell, periodicKey, numLists); // Store M2L list } // End if for non-neighbor } // End loop over children of parents' neighbors } // End loop over target cells for (int icell=0; icell<numCells; icell++) { // Loop over target cells C_iter Ci = Ci0 + icell; // Iterator of target cell if (Ci->NCHILD == 0) { // If taget cell is leaf int numNeighbors; // Number of neighbors getList(2, icell, neighbors, neighborKeys, numNeighbors);// Get list of neighbor cells for (int j=0; j<numNeighbors; j++) { // Loop over neighbor cells int jcell = neighbors[j]; // Index of source cell int periodicKey = neighborKeys[j]; // Periodic key of source cell C_iter Cj = Cj0 + jcell; // Iterator of source cell if (Cj->NCHILD == 0) { // If source cell is leaf setList(0, icell, jcell, periodicKey, numLists); // Store P2P list } // End if for source cell leaf } // End loop over neighbor cells } // End if for target cell leaf } // End loop over target cells } //! Split cell and call traverse() recursively for child void splitCell(C_iter Ci, C_iter Cj, bool mutual, real_t remote) { if (Cj->NCHILD == 0) { // If Cj is leaf assert(Ci->NCHILD > 0); // Make sure Ci is not leaf for (C_iter ci=Ci0+Ci->ICHILD; ci!=Ci0+Ci->ICHILD+Ci->NCHILD; ci++) {// Loop over Ci's children dualTreeTraversal(ci, Cj, mutual, remote); // Traverse a single pair of cells } // End loop over Ci's children } else if (Ci->NCHILD == 0) { // Else if Ci is leaf assert(Cj->NCHILD > 0); // Make sure Cj is not leaf for (C_iter cj=Cj0+Cj->ICHILD; cj!=Cj0+Cj->ICHILD+Cj->NCHILD; cj++) {// Loop over Cj's children dualTreeTraversal(Ci, cj, mutual, remote); // Traverse a single pair of cells } // End loop over Cj's children } else if (Ci->NBODY + Cj->NBODY >= nspawn || (mutual && Ci == Cj)) {// Else if cells are still large TraverseRange traverseRange(this, Ci0+Ci->ICHILD, Ci0+Ci->ICHILD+Ci->NCHILD,// Instantiate recursive functor Cj0+Cj->ICHILD, Cj0+Cj->ICHILD+Cj->NCHILD, mutual, remote); traverseRange(); // Traverse for range of cell pairs } else if (Ci->R >= Cj->R) { // Else if Ci is larger than Cj for (C_iter ci=Ci0+Ci->ICHILD; ci!=Ci0+Ci->ICHILD+Ci->NCHILD; ci++) {// Loop over Ci's children dualTreeTraversal(ci, Cj, mutual, remote); // Traverse a single pair of cells } // End loop over Ci's children } else { // Else if Cj is larger than Ci for (C_iter cj=Cj0+Cj->ICHILD; cj!=Cj0+Cj->ICHILD+Cj->NCHILD; cj++) {// Loop over Cj's children dualTreeTraversal(Ci, cj, mutual, remote); // Traverse a single pair of cells } // End loop over Cj's children } // End if for leafs and Ci Cj size } //! Dual tree traversal for a single pair of cells void dualTreeTraversal(C_iter Ci, C_iter Cj, bool mutual, real_t remote) { vec3 dX = Ci->X - Cj->X - Kernel::Xperiodic; // Distance vector from source to target real_t R2 = norm(dX); // Scalar distance squared if (R2 > (Ci->R+Cj->R) * (Ci->R+Cj->R) * (1 - 1e-3)) { // If distance is far enough Kernel::M2L(Ci, Cj, mutual); // M2L kernel countKernel(numM2L); // Increment M2L counter countList(Ci, Cj, mutual, false); // Increment M2L list countWeight(Ci, Cj, mutual, remote); // Increment M2L weight } else if (Ci->NCHILD == 0 && Cj->NCHILD == 0) { // Else if both cells are bodies #if EXAFMM_NO_P2P int index = Ci->ICELL; int iX[3] = {0, 0, 0}; int d = 0, level = 0; while( index != 0 ) { iX[d] += (index % 2) * (1 << level); index >>= 1; d = (d+1) % 3; if( d == 0 ) level++; } index = Cj->ICELL; int jX[3] = {0, 0, 0}; d = 0; level = 0; while( index != 0 ) { jX[d] += (index % 2) * (1 << level); index >>= 1; d = (d+1) % 3; if( d == 0 ) level++; } int isNeighbor = 1; for (d=0; d<3; d++) { if (Kernel::Xperiodic[d] > 1e-3) jX[d] += 5; if (Kernel::Xperiodic[d] < -1e-3) jX[d] -= 5; isNeighbor &= abs(iX[d] - jX[d]) <= 1; } #endif if (Cj->NBODY == 0) { // If the bodies weren't sent from remote node //std::cout << "Warning: icell " << Ci->ICELL << " needs bodies from jcell" << Cj->ICELL << std::endl; Kernel::M2L(Ci, Cj, mutual); // M2L kernel countKernel(numM2L); // Increment M2L counter countList(Ci, Cj, mutual, false); // Increment M2L list countWeight(Ci, Cj, mutual, remote); // Increment M2L weight #if EXAFMM_NO_P2P } else if (!isNeighbor) { // If GROAMCS handles neighbors Kernel::M2L(Ci, Cj, mutual); // M2L kernel countKernel(numM2L); // Increment M2L counter countList(Ci, Cj, mutual, false); // Increment M2L list countWeight(Ci, Cj, mutual, remote); // Increment M2L weight } else { countList(Ci, Cj, mutual, true); // Increment P2P list #else } else { if (R2 == 0 && Ci == Cj) { // If source and target are same Kernel::P2P(Ci); // P2P kernel for single cell } else { // Else if source and target are different Kernel::P2P(Ci, Cj, mutual); // P2P kernel for pair of cells } // End if for same source and target countKernel(numP2P); // Increment P2P counter countList(Ci, Cj, mutual, true); // Increment P2P list countWeight(Ci, Cj, mutual, remote); // Increment P2P weight #endif } // End if for bodies } else { // Else if cells are close but not bodies splitCell(Ci, Cj, mutual, remote); // Split cell and call function recursively for child } // End if for multipole acceptance } // //! Recursive functor for dual tree traversal of a range of Ci and Cj // struct TraverseRange { // Traversal * traversal; //!< Traversal object // C_iter CiBegin; //!< Begin iterator of target cells // C_iter CiEnd; //!< End iterator of target cells // C_iter CjBegin; //!< Begin Iterator of source cells // C_iter CjEnd; //!< End iterator of source cells // bool mutual; //!< Flag for mutual interaction // real_t remote; //!< Weight for remote work load // TraverseRange(Traversal * _traversal, C_iter _CiBegin, C_iter _CiEnd,// Constructor // C_iter _CjBegin, C_iter _CjEnd, // bool _mutual, real_t _remote) : // traversal(_traversal), CiBegin(_CiBegin), CiEnd(_CiEnd),// Initialize variables // CjBegin(_CjBegin), CjEnd(_CjEnd), mutual(_mutual), remote(_remote) {} // void operator() () const { // Overload operator() // Tracer tracer; // Instantiate tracer // logger::startTracer(tracer); // Start tracer // if (CiEnd - CiBegin == 1 || CjEnd - CjBegin == 1) { // If only one cell in range // if (CiBegin == CjBegin) { // If Ci == Cj // assert(CiEnd == CjEnd); // Check if mutual & self interaction // traversal->dualTreeTraversal(CiBegin, CjBegin, mutual, remote);// Call traverse for single pair // } else { // If Ci != Cj // for (C_iter Ci=CiBegin; Ci!=CiEnd; Ci++) { // Loop over all Ci cells // for (C_iter Cj=CjBegin; Cj!=CjEnd; Cj++) { // Loop over all Cj cells // traversal->dualTreeTraversal(Ci, Cj, mutual, remote);// Call traverse for single pair // } // End loop over all Cj cells // } // End loop over all Ci cells // } // End if for Ci == Cj // } else { // If many cells are in the range // C_iter CiMid = CiBegin + (CiEnd - CiBegin) / 2; // Split range of Ci cells in half // C_iter CjMid = CjBegin + (CjEnd - CjBegin) / 2; // Split range of Cj cells in half // mk_task_group; // Initialize task group // { // TraverseRange leftBranch(traversal, CiBegin, CiMid, // Instantiate recursive functor // CjBegin, CjMid, mutual, remote); // create_taskc(leftBranch); // Ci:former Cj:former // TraverseRange rightBranch(traversal, CiMid, CiEnd, // Instantiate recursive functor // CjMid, CjEnd, mutual, remote); // rightBranch(); // Ci:latter Cj:latter // wait_tasks; // Synchronize task group // } // { // TraverseRange leftBranch(traversal, CiBegin, CiMid, // Instantiate recursive functor // CjMid, CjEnd, mutual, remote); // create_taskc(leftBranch); // Ci:former Cj:latter // if (!mutual || CiBegin != CjBegin) { // Exclude mutual & self interaction // TraverseRange rightBranch(traversal, CiMid, CiEnd,// Instantiate recursive functor // CjBegin, CjMid, mutual, remote); // rightBranch(); // Ci:latter Cj:former // } else { // If mutual or self interaction // assert(CiEnd == CjEnd); // Check if mutual & self interaction // } // End if for mutual & self interaction // wait_tasks; // Synchronize task group // } // } // End if for many cells in range // logger::stopTracer(tracer); // Stop tracer // } // End overload operator() // }; //! Recursive functor for dual tree traversal of a range of Ci and Cj struct TraverseRange { Traversal * traversal; //!< Traversal object C_iter CiBegin; //!< Begin iterator of target cells C_iter CiEnd; //!< End iterator of target cells C_iter CjBegin; //!< Begin Iterator of source cells C_iter CjEnd; //!< End iterator of source cells bool mutual; //!< Flag for mutual interaction real_t remote; //!< Weight for remote work load TraverseRange(Traversal * _traversal, C_iter _CiBegin, C_iter _CiEnd,// Constructor C_iter _CjBegin, C_iter _CjEnd, bool _mutual, real_t _remote) : traversal(_traversal), CiBegin(_CiBegin), CiEnd(_CiEnd),// Initialize variables CjBegin(_CjBegin), CjEnd(_CjEnd), mutual(_mutual), remote(_remote) {} void operator() () const { // Overload operator() Tracer tracer; // Instantiate tracer logger::startTracer(tracer); // Start tracer if (CiEnd - CiBegin == 3 || CjEnd - CjBegin == 3) { // If only 3 cells in range if (CiBegin == CjBegin) { // If Ci == Cj assert(CiEnd == CjEnd); // Check if mutual & self interaction traversal->dualTreeTraversal(CiBegin, CjBegin, mutual, remote);// Call traverse for single pair } else { // If Ci != Cj for (C_iter Ci=CiBegin; Ci!=CiEnd; Ci++) { // Loop over all Ci cells for (C_iter Cj=CjBegin; Cj!=CjEnd; Cj++) { // Loop over all Cj cells traversal->dualTreeTraversal(Ci, Cj, mutual, remote);// Call traverse for single pair } // End loop over all Cj cells } // End loop over all Ci cells } // End if for Ci == Cj } else { // If many cells are in the range C_iter stepCi = (CiEnd - CiBegin) / 4; C_iter stepCj = (CjEnd - CjBegin) / 4; C_iter CiQuad1 = CiBegin + stepCi; C_iter CiQuad2 = CiQuad1 + stepCi; C_iter CiQuad3 = CiQuad2 + stepCi; C_iter CjQuad1 = CjBegin + stepCj; C_iter CjQuad2 = CjQuad1 + stepCj; C_iter CjQuad3 = CjQuad2 + stepCj; mk_task_group; // Initialize task group { TraverseRange brach1(traversal, CiBegin, CiQuad1,// Instantiate recursive functor CjBegin, CjQuad1, mutual, remote); create_taskc(brach1); // Ci:former Cj:former TraverseRange brach2(traversal, CiQuad1, CiQuad2, // Instantiate recursive functor CjQuad1, CjQuad2, mutual, remote); create_taskc(brach2); // Ci:former Cj:former TraverseRange brach3(traversal, CiQuad2, CiQuad3, // Instantiate recursive functor CjQuad2, CjQuad3, mutual, remote); create_taskc(brach3); // Ci:former Cj:former TraverseRange brach4(traversal, CiQuad3, CiEnd, // Instantiate recursive functor CjQuad3, CjEnd, mutual, remote); brach4(); wait_tasks; } { TraverseRange brach1(traversal, CiBegin, CiQuad1,// Instantiate recursive functor CjQuad1, CjQuad2, mutual, remote); create_taskc(brach1); // Ci:former Cj:former TraverseRange brach2(traversal, CiQuad1, CiQuad2, // Instantiate recursive functor CjBegin, CjQuad1, mutual, remote); create_taskc(brach2); // Ci:former Cj:former TraverseRange brach3(traversal, CiQuad2, CiQuad3, // Instantiate recursive functor CjQuad3, CjEnd, mutual, remote); create_taskc(brach3); // Ci:former Cj:former TraverseRange brach4(traversal, CiQuad3, CiEnd, // Instantiate recursive functor CjQuad2, CjQuad3, mutual, remote); brach4(); wait_tasks; } { TraverseRange brach1(traversal, CiBegin, CiQuad1,// Instantiate recursive functor CjQuad3, CjEnd, mutual, remote); create_taskc(brach1); // Ci:former Cj:former TraverseRange brach2(traversal, CiQuad1, CiQuad2, // Instantiate recursive functor CjQuad2, CjQuad3, mutual, remote); create_taskc(brach2); // Ci:former Cj:former TraverseRange brach3(traversal, CiQuad2, CiQuad3, // Instantiate recursive functor CjBegin, CjQuad1, mutual, remote); create_taskc(brach3); // Ci:former Cj:former TraverseRange brach4(traversal, CiQuad3, CiEnd, // Instantiate recursive functor CjQuad1, CjQuad2, mutual, remote); brach4(); wait_tasks; } { TraverseRange brach1(traversal, CiBegin, CiQuad1,// Instantiate recursive functor CjQuad2, CjQuad3, mutual, remote); create_taskc(brach1); // Ci:former Cj:former TraverseRange brach2(traversal, CiQuad1, CiQuad2, // Instantiate recursive functor CjQuad3, CjEnd, mutual, remote); create_taskc(brach2); // Ci:former Cj:former TraverseRange brach3(traversal, CiQuad2, CiQuad3, // Instantiate recursive functor CjQuad1, CjQuad2, mutual, remote); create_taskc(brach3); // Ci:former Cj:former TraverseRange brach4(traversal, CiQuad3, CiEnd, // Instantiate recursive functor CjBegin, CjQuad1, mutual, remote); brach4(); wait_tasks; } } // End if for many cells in range logger::stopTracer(tracer); // Stop tracer } // End overload operator() }; //! List based traversal void listBasedTraversal(int numCells, vec3 cycle, bool mutual, real_t remote) { int list[189], periodicKeys[189]; // Current interaction list #ifdef _OPENMP #pragma omp parallel for private(list, periodicKeys) schedule(dynamic) #endif for (int icell=0; icell<numCells; icell++) { // Loop over target cells C_iter Ci = Ci0 + icell; // Iterator of target cell int nlist; // Interaction list size getList(1, icell, list, periodicKeys, nlist); // Get M2L interaction list for (int ilist=0; ilist<nlist; ilist++) { // Loop over M2L interaction list int jcell = list[ilist]; // Index of source cell int periodicKey = periodicKeys[ilist]; // Periodic key C_iter Cj = Cj0 + jcell; // Iterator of source cell ivec3 pX = getPeriodicIndex(periodicKey); // 3-D periodic index of source cell for (int d=0; d<3; d++) { // Loop over dimensions Kernel::Xperiodic[d] = pX[d] * cycle[d]; // Periodic coordinate offset } // End loop over dimensions Kernel::M2L(Ci, Cj, mutual); // M2L kernel countKernel(numM2L); // Increment M2L counter countList(Ci, Cj, mutual, false); // Increment M2L list countWeight(Ci, Cj, mutual, remote); // Increment M2L weight } // End loop over M2L interaction list } // End loop over target cells #ifndef EXAFMM_NO_P2P #ifdef _OPENMP #pragma omp parallel for private(list, periodicKeys) schedule(dynamic) #endif for (int icell=0; icell<numCells; icell++) { // Loop over target cells C_iter Ci = Ci0 + icell; // Iterator of target cell if (Ci->NCHILD == 0) { // If target cell is leaf int nlist; // Interaction list size getList(0, icell, list, periodicKeys, nlist); // Get P2P interaction list for (int ilist=0; ilist<nlist; ilist++) { // Loop over P2P interaction list int jcell = list[ilist]; // Index of source cell int periodicKey = periodicKeys[ilist]; // Periodic key C_iter Cj = Cj0 + jcell; // Iterator of source cell ivec3 pX = getPeriodicIndex(periodicKey); // 3-D periodic index of source cell for (int d=0; d<3; d++) { // Loop over dimensions Kernel::Xperiodic[d] = pX[d] * cycle[d]; // Periodic coordinate offset } // End loop over dimensions Kernel::P2P(Ci, Cj, mutual); // P2P kernel countKernel(numP2P); // Increment P2P counter countList(Ci, Cj, mutual, true); // Increment P2P list countWeight(Ci, Cj, mutual, remote); // Increment P2P weight } // End loop over P2P interaction list } // End if for target cell leaf } // End loop over target cells #endif } //! Tree traversal of periodic cells void traversePeriodic(vec3 cycle) { logger::startTimer("Traverse periodic"); // Start timer Cells pcells; pcells.resize(27); // Create cells C_iter Ci = pcells.end()-1; // Last cell is periodic parent cell *Ci = *Cj0; // Copy values from source root Ci->ICHILD = 0; // Child cells for periodic center cell Ci->NCHILD = 26; // Number of child cells for periodic center cell C_iter C0 = Cj0; // Placeholder for Cj0 for (int level=0; level<images-1; level++) { // Loop over sublevels of tree for (int ix=-1; ix<=1; ix++) { // Loop over x periodic direction for (int iy=-1; iy<=1; iy++) { // Loop over y periodic direction for (int iz=-1; iz<=1; iz++) { // Loop over z periodic direction if (ix != 0 || iy != 0 || iz != 0) { // If periodic cell is not at center for (int cx=-1; cx<=1; cx++) { // Loop over x periodic direction (child) for (int cy=-1; cy<=1; cy++) { // Loop over y periodic direction (child) for (int cz=-1; cz<=1; cz++) { // Loop over z periodic direction (child) Kernel::Xperiodic[0] = (ix * 3 + cx) * cycle[0];// Coordinate offset for x periodic direction Kernel::Xperiodic[1] = (iy * 3 + cy) * cycle[1];// Coordinate offset for y periodic direction Kernel::Xperiodic[2] = (iz * 3 + cz) * cycle[2];// Coordinate offset for z periodic direction Kernel::M2L(Ci0, Ci, false); // M2L kernel } // End loop over z periodic direction (child) } // End loop over y periodic direction (child) } // End loop over x periodic direction (child) } // Endif for periodic center cell } // End loop over z periodic direction } // End loop over y periodic direction } // End loop over x periodic direction Cj0 = pcells.begin(); // Redefine Cj0 for M2M C_iter Cj = Cj0; // Iterator of periodic neighbor cells for (int ix=-1; ix<=1; ix++) { // Loop over x periodic direction for (int iy=-1; iy<=1; iy++) { // Loop over y periodic direction for (int iz=-1; iz<=1; iz++) { // Loop over z periodic direction if (ix != 0 || iy != 0 || iz != 0) { // If periodic cell is not at center Cj->X[0] = Ci->X[0] + ix * cycle[0]; // Set new x coordinate for periodic image Cj->X[1] = Ci->X[1] + iy * cycle[1]; // Set new y cooridnate for periodic image Cj->X[2] = Ci->X[2] + iz * cycle[2]; // Set new z coordinate for periodic image Cj->M = Ci->M; // Copy multipoles to new periodic image Cj++; // Increment periodic cell iterator } // Endif for periodic center cell } // End loop over z periodic direction } // End loop over y periodic direction } // End loop over x periodic direction Ci->M = 0; // Reset multipoles of periodic parent Kernel::M2M(Ci,Cj0); // Evaluate periodic M2M kernels for this sublevel cycle *= 3; // Increase center cell size three times Cj0 = C0; // Reset Cj0 back } // End loop over sublevels of tree logger::stopTimer("Traverse periodic"); // Stop timer } public: //! Constructor Traversal(int _nspawn, int _images, const char * _path) : // Constructor nspawn(_nspawn), images(_images), path(_path) // Initialize variables #if EXAFMM_COUNT_KERNEL , numP2P(0), numM2L(0) #endif {} #if EXAFMM_COUNT_LIST //! Initialize size of P2P and M2L interaction lists per cell void initListCount(Cells & cells) { for (C_iter C=cells.begin(); C!=cells.end(); C++) { // Loop over cells C->numP2P = C->numM2L = 0; // Initialize size of interaction list } // End loop over cells } #else void initListCount(Cells) {} #endif #if EXAFMM_USE_WEIGHT //! Initialize interaction weights of bodies and cells void initWeight(Cells & cells) { for (C_iter C=cells.begin(); C!=cells.end(); C++) { // Loop over cells C->WEIGHT = 0; // Initialize cell weights if (C->NCHILD==0) { // If leaf cell for (B_iter B=C->BODY; B!=C->BODY+C->NBODY; B++) { // Loop over bodies in cell B->WEIGHT = 0; // Initialize body weights } // End loop over bodies in cell } // End if for leaf cell } // End loop over cells } #else void initWeight(Cells) {} #endif //! Evaluate P2P and M2L using list based traversal void traverse(Cells & icells, Cells & jcells, vec3 cycle, bool dual, bool mutual, real_t remote=1) { if (icells.empty() || jcells.empty()) return; // Quit if either of the cell vectors are empty logger::startTimer("Traverse"); // Start timer logger::initTracer(); // Initialize tracer Ci0 = icells.begin(); // Iterator of first target cell Cj0 = jcells.begin(); // Iterator of first source cell Kernel::Xperiodic = 0; // Set periodic coordinate offset to 0 if (dual) { // If dual tree traversal if (images == 0) { // If non-periodic boundary condition dualTreeTraversal(Ci0, Cj0, mutual, remote); // Traverse the tree } else { // If periodic boundary condition for (int ix=-1; ix<=1; ix++) { // Loop over x periodic direction for (int iy=-1; iy<=1; iy++) { // Loop over y periodic direction for (int iz=-1; iz<=1; iz++) { // Loop over z periodic direction Kernel::Xperiodic[0] = ix * cycle[0]; // Coordinate shift for x periodic direction Kernel::Xperiodic[1] = iy * cycle[1]; // Coordinate shift for y periodic direction Kernel::Xperiodic[2] = iz * cycle[2]; // Coordinate shift for z periodic direction dualTreeTraversal(Ci0, Cj0, false, remote); // Traverse the tree for this periodic image } // End loop over z periodic direction } // End loop over y periodic direction } // End loop over x periodic direction traversePeriodic(cycle); // Traverse tree for periodic images } // End if for periodic boundary condition } else { // If list based traversal int numCells = icells.size(); // Number of cells mutual = false; // Set mutual interaction flag to false listOffset = new int [numCells][3](); // Offset of interaction lists lists = new int [(216+27)*numCells][3](); // All interaction lists setLists(icells); // Set P2P and M2L interaction lists listBasedTraversal(numCells, cycle, mutual, remote); // Traverse the tree if (images != 0) { // If periodic boundary condition traversePeriodic(cycle); // Traverse tree for periodic images } // End if for periodic boundary condition delete[] listOffset; // Deallocate offset of lists delete[] lists; // Deallocate lists } // End if for dual tree traversal logger::stopTimer("Traverse"); // Stop timer logger::writeTracer(); // Write tracer to file } struct DirectRecursion { C_iter Ci; //!< Iterator of target cell C_iter Cj; //!< Iterator of source cell DirectRecursion(C_iter _Ci, C_iter _Cj) : // Constructor Ci(_Ci), Cj(_Cj) {} // Initialize variables void operator() () const { // Overload operator if (Ci->NBODY < 25) { // If number of target bodies is less than threshold Kernel::P2P(Ci, Cj, false); // Evaluate P2P kernel } else { // If number of target bodies is more than threshold Cells cells; cells.resize(1); // Initialize new cell vector C_iter Ci2 = cells.begin(); // New cell iterator for right branch Ci2->BODY = Ci->BODY + Ci->NBODY / 2; // Set begin iterator to handle latter half Ci2->NBODY = Ci->NBODY - Ci->NBODY / 2; // Set range to handle latter half Ci->NBODY = Ci->NBODY / 2; // Set range to handle first half mk_task_group; // Initialize task group DirectRecursion leftBranch(Ci, Cj); // Instantiate recursive functor create_taskc(leftBranch); // Create new task for left branch DirectRecursion rightBranch(Ci2, Cj); // Instantiate recursive functor rightBranch(); // Use old task for right branch wait_tasks; // Synchronize task group } // End if for NBODY threshold } // End operator }; //! Direct summation void direct(Bodies & ibodies, Bodies & jbodies, vec3 cycle) { Cells cells; cells.resize(2); // Define a pair of cells to pass to P2P kernel C_iter Ci = cells.begin(), Cj = cells.begin()+1; // First cell is target, second cell is source int prange = 0; // Range of periodic images for (int i=0; i<images; i++) { // Loop over periodic image sublevels prange += int(std::pow(3.,i)); // Accumulate range of periodic images } // End loop over perioidc image sublevels for (int ix=-prange; ix<=prange; ix++) { // Loop over x periodic direction for (int iy=-prange; iy<=prange; iy++) { // Loop over y periodic direction for (int iz=-prange; iz<=prange; iz++) { // Loop over z periodic direction Kernel::Xperiodic[0] = ix * cycle[0]; // Coordinate shift for x periodic direction Kernel::Xperiodic[1] = iy * cycle[1]; // Coordinate shift for y periodic direction Kernel::Xperiodic[2] = iz * cycle[2]; // Coordinate shift for z periodic direction Ci->BODY = ibodies.begin(); // Iterator of first target body Ci->NBODY = ibodies.size(); // Number of target bodies Cj->BODY = jbodies.begin(); // Iterator of first source body Cj->NBODY = jbodies.size(); // Number of source bodies DirectRecursion directRecursion(Ci, Cj); // Instantiate recursive functor directRecursion(); // Recursive call for direct summation } // End loop over z periodic direction } // End loop over y periodic direction } // End loop over x periodic direction } //! Normalize bodies after direct summation void normalize(Bodies & bodies) { Kernel::normalize(bodies); // Normalize bodies } //! Write G matrix to file void writeMatrix(Bodies & bodies, Bodies & jbodies) { std::stringstream name; // File name name << path << "matrix.dat"; // Create file name for matrix std::ofstream matrixFile(name.str().c_str()); // Open matrix log file for (B_iter Bi=bodies.begin(); Bi!=bodies.end(); Bi++) { // Loop over target bodies for (B_iter Bj=jbodies.begin(); Bj!=jbodies.end(); Bj++) {// Loop over source bodies vec3 dX = Bi->X - Bj->X; // Distance vector real_t R2 = norm(dX) + Kernel::eps2; // Distance squared real_t G = R2 == 0 ? 0.0 : 1.0 / sqrt(R2); // Green's function matrixFile << G << " "; // Write to matrix data file } // End loop over source bodies matrixFile << std::endl; // Line break } // End loop over target bodies } //! Print traversal statistics void printTraversalData() { #if EXAFMM_COUNT_KERNEL if (logger::verbose) { // If verbose flag is true std::cout << "--- Traversal stats --------------" << std::endl// Print title << std::setw(logger::stringLength) << std::left // Set format << "P2P calls" << " : " // Print title << std::setprecision(0) << std::fixed // Set format << numP2P << std::endl // Print number of P2P calls << std::setw(logger::stringLength) << std::left // Set format << "M2L calls" << " : " // Print title << std::setprecision(0) << std::fixed // Set format << numM2L << std::endl; // Print number of M2L calls } // End if for verbose flag #endif } #if EXAFMM_COUNT_LIST void writeList(Cells cells, int mpirank) { std::stringstream name; // File name name << path << "list" << std::setfill('0') << std::setw(6) // Set format << mpirank << ".dat"; // Create file name for list std::ofstream listFile(name.str().c_str()); // Open list log file for (C_iter C=cells.begin(); C!=cells.end(); C++) { // Loop over all lists listFile << std::setw(logger::stringLength) << std::left// Set format << C->ICELL << " " << C->numP2P << " " << C->numM2L << std::endl; // Print list size } // End loop over all lists } #else void writeList(Cells, int) {} #endif }; } #endif
edge_coloring.c
/* Author: Mohammed Al Farhan Email: mohammed.farhan@kaust.edu.sa */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <omp.h> #include <stdint.h> #include <math.h> #include <limits.h> #include "inc/allocator.h" #include "inc/geometry.h" #include "inc/msh/mesh.h" #include "inc/msh/bit_map.h" #define VEC_LEN 8 void iecoloring(struct geometry *restrict g) { const uint32_t *restrict ie = g->s->ie; const size_t nnodes = g->n->sz; const size_t nedges = g->e->sz; uint32_t *restrict n0 = g->e->eptr->n0; uint32_t *restrict n1 = g->e->eptr->n1; double *restrict x0 = g->e->xyzn->x0; double *restrict x1 = g->e->xyzn->x1; double *restrict x2 = g->e->xyzn->x2; double *restrict x3 = g->e->xyzn->x3; uint32_t *restrict nedges_per_color; kcalloc(nedges, sizeof(uint32_t), (void *) &nedges_per_color); #pragma omp parallel { const uint32_t t = omp_get_thread_num(); const uint32_t ie0 = ie[t]; const uint32_t ie1 = ie[t+1]; const size_t nsz_b = I2B(nnodes); uint8_t *restrict node_bmap; kcalloc(nsz_b, sizeof(uint8_t), (void *) &node_bmap); uint32_t k = ie0; uint32_t c = ie0; uint32_t i; for(i = ie0; i < ie1; i++) { uint32_t j; memset(node_bmap, 0, nsz_b * sizeof(uint8_t)); for(j = i; j < ie1; j++) { uint32_t f0 = 0, f1 = 0; BGET(f0, node_bmap[IOFF(n0[j])], BOFF(n0[j])); BGET(f1, node_bmap[IOFF(n1[j])], BOFF(n1[j])); if(f0 | f1) continue; if(nedges_per_color[c] == VEC_LEN) break; BSET(node_bmap[IOFF(n0[j])], BOFF(n0[j])); BSET(node_bmap[IOFF(n1[j])], BOFF(n1[j])); const uint32_t _n0 = n0[j]; const uint32_t _n1 = n1[j]; const double _x0 = x0[j]; const double _x1 = x1[j]; const double _x2 = x2[j]; const double _x3 = x3[j]; n0[j] = n0[k]; n1[j] = n1[k]; x0[j] = x0[k]; x1[j] = x1[k]; x2[j] = x2[k]; x3[j] = x3[k]; n0[k] = _n0; n1[k] = _n1; x0[k] = _x0; x1[k] = _x1; x2[k] = _x2; x3[k] = _x3; k++; nedges_per_color[c]++; } c++; i = k; } kfree(node_bmap); } kfree(nedges_per_color); }
GB_binop__eq_uint16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__eq_uint16) // A.*B function (eWiseMult): GB (_AemultB_08__eq_uint16) // A.*B function (eWiseMult): GB (_AemultB_02__eq_uint16) // A.*B function (eWiseMult): GB (_AemultB_04__eq_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__eq_uint16) // A*D function (colscale): GB (_AxD__eq_uint16) // D*A function (rowscale): GB (_DxB__eq_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__eq_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__eq_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__eq_uint16) // C=scalar+B GB (_bind1st__eq_uint16) // C=scalar+B' GB (_bind1st_tran__eq_uint16) // C=A+scalar GB (_bind2nd__eq_uint16) // C=A'+scalar GB (_bind2nd_tran__eq_uint16) // C type: bool // A type: uint16_t // A pattern? 0 // B type: uint16_t // B pattern? 0 // BinaryOp: cij = (aij == bij) #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint16_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint16_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x == y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_EQ || GxB_NO_UINT16 || GxB_NO_EQ_UINT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__eq_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__eq_uint16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__eq_uint16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type uint16_t uint16_t bwork = (*((uint16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__eq_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__eq_uint16) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__eq_uint16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint16_t alpha_scalar ; uint16_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint16_t *) alpha_scalar_in)) ; beta_scalar = (*((uint16_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__eq_uint16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__eq_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__eq_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__eq_uint16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__eq_uint16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint16_t bij = GBX (Bx, p, false) ; Cx [p] = (x == bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__eq_uint16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint16_t aij = GBX (Ax, p, false) ; Cx [p] = (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) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB (_bind1st_tran__eq_uint16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB (_bind2nd_tran__eq_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
nqueens.c
/**********************************************************************************************/ /* This program is part of the Barcelona OpenMP Tasks Suite */ /* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */ /* Copyright (C) 2009 Universitat Politecnica de Catalunya */ /* */ /* This program is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 2 of the License, or */ /* (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /**********************************************************************************************/ /* * Original code from the Cilk project (by Keith Randall) * * Copyright (c) 2000 Massachusetts Institute of Technology * Copyright (c) 2000 Matteo Frigo */ #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <alloca.h> #include <assert.h> #include <unistd.h> #include <sys/time.h> #include <omp.h> #include "BenchmarksUtil.h" /* Checking information */ static int solutions[] = { 1, 0, 0, 2, 10, /* 5 */ 4, 40, 92, 352, 724, /* 10 */ 2680, 14200, 73712, 365596, }; #define MAX_SOLUTIONS sizeof(solutions)/sizeof(int) //#ifdef FORCE_TIED_TASKS //int mycount=0; //#pragma omp threadprivate(mycount) int total_count, total_count_seq; int if_cutoff, final_cutoff, manual_cutoff; int cutoff_value =3; /* * <a> contains array of <n> queen positions. Returns 1 * if none of the queens conflict, and returns 0 otherwise. */ int ok(int n, char *a) { int i, j; char p, q; for (i = 0; i < n; i++) { p = a[i]; for (j = i + 1; j < n; j++) { q = a[j]; if (q == p || q == p - (j - i) || q == p + (j - i)) return 0; } } return 1; } void nqueens_ser (int n, int j, char *a, int *solutions) { int res; int i; if (n == j) { /* good solution, count it */ *solutions = 1; return; } *solutions = 0; /* try each possible position for queen <j> */ for (i = 0; i < n; i++) { { /* allocate a temporary array and copy <a> into it */ a[j] = (char) i; if (ok(j + 1, a)) { nqueens_ser(n, j + 1, a,&res); *solutions += res; } } } } void nqueens_if(int n, int j, char *a, int *solutions, int depth) { int *csols; int i; if (n == j) { /* good solution, count it */ *solutions = 1; return; } *solutions = 0; csols = alloca(n*sizeof(int)); memset(csols,0,n*sizeof(int)); /* try each possible position for queen <j> */ for (i = 0; i < n; i++) { #pragma omp task untied if(depth < cutoff_value) { /* allocate a temporary array and copy <a> into it */ char * b = alloca(n * sizeof(char)); memcpy(b, a, j * sizeof(char)); b[j] = (char) i; if (ok(j + 1, b)) nqueens_if(n, j + 1, b,&csols[i],depth+1); } } #pragma omp taskwait for ( i = 0; i < n; i++) *solutions += csols[i]; } void nqueens_final(int n, int j, char *a, int *solutions, int depth) { int *csols; int i; if (n == j) { /* good solution, count it */ *solutions += 1; return; } char final = omp_in_final(); if ( !final ) { *solutions = 0; csols = alloca(n*sizeof(int)); memset(csols,0,n*sizeof(int)); } /* try each possible position for queen <j> */ for (i = 0; i < n; i++) { #pragma omp task untied final(depth+1 >= cutoff_value) mergeable { char *b; int *sol; if ( omp_in_final() && depth+1 > cutoff_value ) { b = a; sol = solutions; } else { /* allocate a temporary array and copy <a> into it */ b = alloca(n * sizeof(char)); memcpy(b, a, j * sizeof(char)); sol = &csols[i]; } b[j] = i; if (ok(j + 1, b)) nqueens_final(n, j + 1, b,sol,depth+1); } } #pragma omp taskwait if ( !final ) { for ( i = 0; i < n; i++) *solutions += csols[i]; } } void nqueens_manual(int n, int j, char *a, int *solutions, int depth) { int *csols; int i; if (n == j) { /* good solution, count it */ *solutions = 1; return; } *solutions = 0; csols = alloca(n*sizeof(int)); memset(csols,0,n*sizeof(int)); /* try each possible position for queen <j> */ for (i = 0; i < n; i++) { if ( depth < cutoff_value ) { #pragma omp task untied { /* allocate a temporary array and copy <a> into it */ char * b = alloca(n * sizeof(char)); memcpy(b, a, j * sizeof(char)); b[j] = (char) i; if (ok(j + 1, b)) nqueens_manual(n, j + 1, b,&csols[i],depth+1); } } else { a[j] = (char) i; if (ok(j + 1, a)) nqueens_ser(n, j + 1, a,&csols[i]); } } #pragma omp taskwait for ( i = 0; i < n; i++) *solutions += csols[i]; } void nqueens(int n, int j, char *a, int *solutions, int depth) { int *csols; int i; if (n == j) { /* good solution, count it */ *solutions = 1; return; } *solutions = 0; csols = alloca(n*sizeof(int)); memset(csols,0,n*sizeof(int)); /* try each possible position for queen <j> */ for (i = 0; i < n; i++) { #pragma omp task untied { /* allocate a temporary array and copy <a> into it */ char * b = alloca(n * sizeof(char)); memcpy(b, a, j * sizeof(char)); b[j] = (char) i; if (ok(j + 1, b)) nqueens(n, j + 1, b,&csols[i],depth); //FIXME: depth or depth+1 ??? } } #pragma omp taskwait for ( i = 0; i < n; i++) *solutions += csols[i]; } void find_queens_seq (int size) { total_count_seq = 0; fprintf(stdout,"Computing N-Queens algorithm (n=%d) ", size); char *a; a = alloca(size * sizeof(char)); nqueens_ser(size, 0, a, &total_count_seq); fprintf(stdout," completed!\n"); } void find_queens (int size) { total_count=0; fprintf(stdout,"Computing N-Queens algorithm (n=%d) ", size); if (if_cutoff) { #pragma omp parallel { #pragma omp single { char *a; a = alloca(size * sizeof(char)); nqueens_if(size, 0, a, &total_count,0); } } } else if (manual_cutoff) { #pragma omp parallel { #pragma omp single { char *a; a = alloca(size * sizeof(char)); nqueens_manual(size, 0, a, &total_count,0); } } } else if (final_cutoff) { #pragma omp parallel { #pragma omp single { char *a; a = alloca(size * sizeof(char)); nqueens_final(size, 0, a, &total_count,0); } } } else { #pragma omp parallel { #pragma omp single { char *a; a = alloca(size * sizeof(char)); nqueens(size, 0, a, &total_count,0); } } } fprintf(stdout," completed!\n"); } int verify_queens (int size) { if ( size > MAX_SOLUTIONS ) return -1; if ( total_count == solutions[size-1] && total_count == total_count_seq) return 1; return 0; } void print_usage() { fprintf(stderr, "\n"); fprintf(stderr, "Usage: %s -[options]\n", "N-Queens"); fprintf(stderr, "\n"); fprintf(stderr, "Where options are:\n"); fprintf(stderr, " -n <number> : Board size\n"); fprintf(stderr, " -a <flag> : Set if-cutoff on\n"); fprintf(stderr, " -b <flag> : Set manual-cutoff on\n"); fprintf(stderr, " -c <flag> : Set final-cutoff on (choose one or none)\n"); fprintf(stderr, " -h : Print program's usage (this help).\n"); fprintf(stderr, "\n"); } int main(int argc, char* argv[]) { int size = 14, i; for (i=1; i<argc; i++) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 'n': /* read argument size 0 */ argv[i][1] = '*'; i++; if (argc == i) { "Erro\n"; exit(100); } size = atoi(argv[i]); break; case 'a': /* read argument size 0 */ argv[i][1] = '*'; //i++; //if (argc == i) { "Erro\n"; exit(100); } if_cutoff = 1; manual_cutoff = 0; final_cutoff = 0; break; case 'b': /* read argument size 0 */ argv[i][1] = '*'; //i++; //if (argc == i) { "Erro\n"; exit(100); } manual_cutoff = 1; if_cutoff = 0; final_cutoff = 0; break; case 'c': /* read argument size 0 */ argv[i][1] = '*'; //i++; //if (argc == i) { "Erro\n"; exit(100); } final_cutoff = 1; if_cutoff = 0; manual_cutoff = 0; break; case 'h': /* print usage */ argv[i][1] = '*'; print_usage(); exit (100); break; } } } double t_start, t_end; t_start = rtclock(); find_queens(size); t_end = rtclock(); fprintf(stdout, "Parallel Runtime: %0.6lfs\n", t_end - t_start); t_start = rtclock(); find_queens_seq(size); t_end = rtclock(); fprintf(stdout, "Sequential Runtime: %0.6lfs\n", t_end - t_start); if (verify_queens(size) == 1) { fprintf(stdout, "Result: Successful\n"); } else { fprintf(stdout, "Result: Unsuccessful\n"); } return 0; }
omp_kmeans.c
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* File: kmeans_clustering.c (OpenMP version) */ /* Description: Implementation of simple k-means clustering algorithm */ /* This program takes an array of N data objects, each with */ /* M coordinates and performs a k-means clustering given a */ /* user-provided value of the number of clusters (K). The */ /* clustering results are saved in 2 arrays: */ /* 1. a returned array of size [K][N] indicating the center */ /* coordinates of K clusters */ /* 2. membership[N] stores the cluster center ids, each */ /* corresponding to the cluster a data object is assigned */ /* */ /* Author: Wei-keng Liao */ /* ECE Department, Northwestern University */ /* email: wkliao@ece.northwestern.edu */ /* Copyright, 2005, Wei-keng Liao */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <stdio.h> #include <stdlib.h> #include <omp.h> #include "kmeans.h" /*----< euclid_dist_2() >----------------------------------------------------*/ /* square of Euclid distance between two multi-dimensional points */ __inline static float euclid_dist_2(int numdims, /* no. dimensions */ float *coord1, /* [numdims] */ float *coord2) /* [numdims] */ { int i; float ans=0.0; for (i=0; i<numdims; i++) ans += (coord1[i]-coord2[i]) * (coord1[i]-coord2[i]); return(ans); } /*----< find_nearest_cluster() >---------------------------------------------*/ __inline static int find_nearest_cluster(int numClusters, /* no. clusters */ int numCoords, /* no. coordinates */ float *distance, float *object, /* [numCoords] */ float **clusters) /* [numClusters][numCoords] */ { int index, i; float dist, min_dist; /* find the cluster id that has min distance to object */ index = 0; min_dist = euclid_dist_2(numCoords, object, clusters[0]); for (i=1; i<numClusters; i++) { dist = euclid_dist_2(numCoords, object, clusters[i]); /* no need square root */ if (dist < min_dist) { /* find the min and its array index */ min_dist = dist; index = i; } } *distance = min_dist; return(index); } /*----< kmeans_clustering() >------------------------------------------------*/ /* return an array of cluster centers of size [numClusters][numCoords] */ float** omp_kmeans(int is_perform_atomic, /* in: */ float **objects, /* in: [numObjs][numCoords] */ int numCoords, /* no. coordinates */ int numObjs, /* no. objects */ int numClusters, /* no. clusters */ float **clustersInit, float threshold, /* % objects change membership */ int *membership, /* out: [numObjs] */ int *loop_iterations) { int i, j, k, index, loop=0; int *newClusterSize; /* [numClusters]: no. objects assigned in each new cluster */ float delta; /* % of objects change their clusters */ float **clusters; /* out: [numClusters][numCoords] */ float **newClusters; /* [numClusters][numCoords] */ double timing; int nthreads; /* no. threads */ int **local_newClusterSize; /* [nthreads][numClusters] */ float ***local_newClusters; /* [nthreads][numClusters][numCoords] */ nthreads = omp_get_max_threads(); /* allocate a 2D space for returning variable clusters[] (coordinates of cluster centers) */ clusters = (float**) malloc(numClusters * sizeof(float*)); assert(clusters != NULL); clusters[0] = (float*) malloc(numClusters * numCoords * sizeof(float)); assert(clusters[0] != NULL); for (i=1; i<numClusters; i++) clusters[i] = clusters[i-1] + numCoords; /* pick clusterInit as initial objects of cluster elements*/ for (i=0; i<numClusters; i++) for (j=0; j<numCoords; j++) clusters[i][j] = clustersInit[i][j]; /* initialize membership[] */ for (i=0; i<numObjs; i++) membership[i] = -1; /* need to initialize newClusterSize and newClusters[0] to all 0 */ newClusterSize = (int*) calloc(numClusters, sizeof(int)); assert(newClusterSize != NULL); newClusters = (float**) malloc(numClusters * sizeof(float*)); assert(newClusters != NULL); newClusters[0] = (float*) calloc(numClusters * numCoords, sizeof(float)); assert(newClusters[0] != NULL); for (i=1; i<numClusters; i++) newClusters[i] = newClusters[i-1] + numCoords; /* initialize dist */ float* dist = (float*) malloc(numObjs * sizeof(float)); float totalDistance = 0.0; if (!is_perform_atomic) { /* each thread calculates new centers using a private space, then thread 0 does an array reduction on them. This approach should be faster */ local_newClusterSize = (int**) malloc(nthreads * sizeof(int*)); assert(local_newClusterSize != NULL); local_newClusterSize[0] = (int*) calloc(nthreads*numClusters, sizeof(int)); assert(local_newClusterSize[0] != NULL); for (i=1; i<nthreads; i++) local_newClusterSize[i] = local_newClusterSize[i-1]+numClusters; /* local_newClusters is a 3D array */ local_newClusters =(float***)malloc(nthreads * sizeof(float**)); assert(local_newClusters != NULL); local_newClusters[0] =(float**) malloc(nthreads * numClusters * sizeof(float*)); assert(local_newClusters[0] != NULL); for (i=1; i<nthreads; i++) local_newClusters[i] = local_newClusters[i-1] + numClusters; for (i=0; i<nthreads; i++) { for (j=0; j<numClusters; j++) { local_newClusters[i][j] = (float*)calloc(numCoords, sizeof(float)); assert(local_newClusters[i][j] != NULL); } } } if (_debug) timing = omp_get_wtime(); do { delta = 0.0; if (is_perform_atomic) { #pragma omp parallel for \ private(i,j,index) \ firstprivate(numObjs,numClusters,numCoords) \ shared(objects,clusters,membership,newClusters,newClusterSize) \ schedule(static) \ reduction(+:delta) for (i=0; i<numObjs; i++) { /* find the array index of nestest cluster center */ index = find_nearest_cluster(numClusters, numCoords, &dist[i], objects[i], clusters); /* if membership changes, increase delta by 1 */ if (membership[i] != index) delta += 1.0; /* assign the membership to object i */ membership[i] = index; /* update new cluster centers : sum of objects located within */ #pragma omp atomic newClusterSize[index]++; for (j=0; j<numCoords; j++) #pragma omp atomic newClusters[index][j] += objects[i][j]; } } else { #pragma omp parallel \ shared(objects,clusters,membership,local_newClusters,local_newClusterSize) { int tid = omp_get_thread_num(); #pragma omp for \ private(i,j,index) \ firstprivate(numObjs,numClusters,numCoords) \ schedule(static) \ reduction(+:delta) for (i=0; i<numObjs; i++) { /* find the array index of nestest cluster center */ index = find_nearest_cluster(numClusters, numCoords, &dist[i], objects[i], clusters); /* if membership changes, increase delta by 1 */ if (membership[i] != index) delta += 1.0; /* assign the membership to object i */ membership[i] = index; /* update new cluster centers : sum of all objects located within (average will be performed later) */ local_newClusterSize[tid][index]++; for (j=0; j<numCoords; j++) local_newClusters[tid][index][j] += objects[i][j]; } } /* end of #pragma omp parallel */ /* let the main thread perform the array reduction */ for (i=0; i<numClusters; i++) { for (j=0; j<nthreads; j++) { newClusterSize[i] += local_newClusterSize[j][i]; local_newClusterSize[j][i] = 0.0; for (k=0; k<numCoords; k++) { newClusters[i][k] += local_newClusters[j][i][k]; local_newClusters[j][i][k] = 0.0; } } } } /* average the sum and replace old cluster centers with newClusters */ for (i=0; i<numClusters; i++) { for (j=0; j<numCoords; j++) { if (newClusterSize[i] > 1) clusters[i][j] = newClusters[i][j] / newClusterSize[i]; newClusters[i][j] = 0.0; /* set back to 0 */ } newClusterSize[i] = 0; /* set back to 0 */ } /* compute total distance and display results*/ totalDistance = 0.0; for (i=0; i<numObjs; i++) totalDistance += dist[i]; delta /= numObjs; if (_debug) printf("Total distance = %f delta = %.3f\n", totalDistance, delta); } while (delta > threshold && loop++ < 500); *loop_iterations = loop + 1; if (_debug) { timing = omp_get_wtime() - timing; printf("nloops = %2d (T = %7.4f)",loop,timing); } if (!is_perform_atomic) { free(local_newClusterSize[0]); free(local_newClusterSize); for (i=0; i<nthreads; i++) for (j=0; j<numClusters; j++) free(local_newClusters[i][j]); free(local_newClusters[0]); free(local_newClusters); } free(newClusters[0]); free(newClusters); free(newClusterSize); return clusters; }
sptree_inl.h
/* * * Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology 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 LAURENS VAN DER MAATEN ''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 LAURENS VAN DER MAATEN 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. * */ /* * * Copyright (c) 2014, Nicola Pezzotti (Delft University of Technology) * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology 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 NICOLA PEZZOTTI ''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 NICOLA PEZZOTTI 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 SPTREE_INL #define SPTREE_INL #include <math.h> #include <float.h> #include <stdlib.h> #include <stdio.h> #include <cmath> #include "sptree.h" #include <math.h> #include <algorithm> namespace hdi{ namespace dr{ //! Constructs cell template <typename scalar_type> SPTree<scalar_type>::Cell::Cell(unsigned int inp__emb_dimension) { _emb_dimension = inp__emb_dimension; corner = (hp_scalar_type*) malloc(_emb_dimension * sizeof(hp_scalar_type)); width = (hp_scalar_type*) malloc(_emb_dimension * sizeof(hp_scalar_type)); } template <typename scalar_type> SPTree<scalar_type>::Cell::Cell(unsigned int inp__emb_dimension, hp_scalar_type* inp_corner, hp_scalar_type* inp_width) { _emb_dimension = inp__emb_dimension; corner = (hp_scalar_type*) malloc(_emb_dimension * sizeof(hp_scalar_type)); width = (hp_scalar_type*) malloc(_emb_dimension * sizeof(hp_scalar_type)); for(int d = 0; d < _emb_dimension; d++) setCorner(d, inp_corner[d]); for(int d = 0; d < _emb_dimension; d++) setWidth( d, inp_width[d]); } //! Destructs cell template <typename scalar_type> SPTree<scalar_type>::Cell::~Cell() { free(corner); free(width); } template <typename scalar_type> typename SPTree<scalar_type>::hp_scalar_type SPTree<scalar_type>::Cell::getCorner(unsigned int d) { return corner[d]; } template <typename scalar_type> typename SPTree<scalar_type>::hp_scalar_type SPTree<scalar_type>::Cell::getWidth(unsigned int d) { return width[d]; } template <typename scalar_type> void SPTree<scalar_type>::Cell::setCorner(unsigned int d, hp_scalar_type val) { corner[d] = val; } template <typename scalar_type> void SPTree<scalar_type>::Cell::setWidth(unsigned int d, hp_scalar_type val) { width[d] = val; } // Checks whether a point lies in a cell template <typename scalar_type> bool SPTree<scalar_type>::Cell::containsPoint(scalar_type point[]) { for(int d = 0; d < _emb_dimension; d++) { if(corner[d] - width[d] > point[d]) return false; if(corner[d] + width[d] < point[d]) return false; } return true; } ///////////////////////////////////////////////////////////////////////////////////////////// //! Default constructor for SPTree -- build tree, too! template <typename scalar_type> SPTree<scalar_type>::SPTree(unsigned int D, scalar_type* inp_data, unsigned int N){ // Compute mean, width, and height of current map (boundaries of SPTree) hp_scalar_type* mean_Y = (hp_scalar_type*) malloc(D * sizeof(hp_scalar_type)); for(unsigned int d = 0; d < D; d++) mean_Y[d] = .0; hp_scalar_type* min_Y = (hp_scalar_type*) malloc(D * sizeof(hp_scalar_type)); for(unsigned int d = 0; d < D; d++) min_Y[d] = DBL_MAX; hp_scalar_type* max_Y = (hp_scalar_type*) malloc(D * sizeof(hp_scalar_type)); for(unsigned int d = 0; d < D; d++) max_Y[d] = -DBL_MAX; for(unsigned int n = 0; n < N; n++) { for(unsigned int d = 0; d < D; d++) { mean_Y[d] += inp_data[n * D + d]; if(inp_data[n * D + d] < min_Y[d]) min_Y[d] = inp_data[n * D + d]; if(inp_data[n * D + d] > max_Y[d]) max_Y[d] = inp_data[n * D + d]; } } for(int d = 0; d < D; d++) mean_Y[d] /= (hp_scalar_type) N; // Construct SPTree hp_scalar_type* width = (hp_scalar_type*) malloc(D * sizeof(hp_scalar_type)); for(int d = 0; d < D; d++) //width[d] = fmax(max_Y[d] - mean_Y[d], mean_Y[d] - min_Y[d]) + 1e-5; //C++11 width[d] = std::max(max_Y[d] - mean_Y[d], mean_Y[d] - min_Y[d]) + 1e-5; init(NULL, D, inp_data, mean_Y, width); fill(N); // Clean up memory free(mean_Y); free(max_Y); free(min_Y); free(width); } //! Constructor for SPTree with particular size and parent -- build the tree, too! template <typename scalar_type> SPTree<scalar_type>::SPTree(unsigned int D, scalar_type* inp_data, unsigned int N, hp_scalar_type* inp_corner, hp_scalar_type* inp_width){ init(NULL, D, inp_data, inp_corner, inp_width); fill(N); } //! Constructor for SPTree with particular size (do not fill the tree) template <typename scalar_type> SPTree<scalar_type>::SPTree(unsigned int D, scalar_type* inp_data, hp_scalar_type* inp_corner, hp_scalar_type* inp_width){ init(NULL, D, inp_data, inp_corner, inp_width); } //! Constructor for SPTree with particular size and parent (do not fill tree) template <typename scalar_type> SPTree<scalar_type>::SPTree(SPTree* inp_parent, unsigned int D, scalar_type* inp_data, hp_scalar_type* inp_corner, hp_scalar_type* inp_width){ init(inp_parent, D, inp_data, inp_corner, inp_width); } //! Constructor for SPTree with particular size and parent -- build the tree, too! template <typename scalar_type> SPTree<scalar_type>::SPTree(SPTree* inp_parent, unsigned int D, scalar_type* inp_data, unsigned int N, hp_scalar_type* inp_corner, hp_scalar_type* inp_width){ init(inp_parent, D, inp_data, inp_corner, inp_width); fill(N); } //! Main initialization function template <typename scalar_type> void SPTree<scalar_type>::init(SPTree* inp_parent, unsigned int D, scalar_type* inp_data, hp_scalar_type* inp_corner, hp_scalar_type* inp_width){ parent = inp_parent; _emb_dimension = D; no_children = 2; for(unsigned int d = 1; d < D; d++) no_children *= 2; _emb_positions = inp_data; is_leaf = true; size = 0; cum_size = 0; boundary = new Cell(_emb_dimension); for(unsigned int d = 0; d < D; d++) boundary->setCorner(d, inp_corner[d]); for(unsigned int d = 0; d < D; d++) boundary->setWidth( d, inp_width[d]); children = (SPTree**) malloc(no_children * sizeof(SPTree*)); for(unsigned int i = 0; i < no_children; i++) children[i] = NULL; _center_of_mass = (hp_scalar_type*) malloc(D * sizeof(hp_scalar_type)); for(unsigned int d = 0; d < D; d++) _center_of_mass[d] = .0; //buff = (hp_scalar_type*) malloc(D * sizeof(hp_scalar_type)); } // Destructor for SPTree template <typename scalar_type> SPTree<scalar_type>::~SPTree() { for(unsigned int i = 0; i < no_children; i++) { if(children[i] != NULL) delete children[i]; } free(children); free(_center_of_mass); //free(buff); delete boundary; } // Update the _emb_positions underlying this tree template <typename scalar_type> void SPTree<scalar_type>::setData(scalar_type* inp_data) { _emb_positions = inp_data; } // Get the parent of the current tree template <typename scalar_type> SPTree<scalar_type>* SPTree<scalar_type>::getParent() { return parent; } // Insert a point into the SPTree template <typename scalar_type> bool SPTree<scalar_type>::insert(unsigned int new_index) { //#pragma critical { // Ignore objects which do not belong in this quad tree scalar_type* point = _emb_positions + new_index * _emb_dimension; if(!boundary->containsPoint(point)) return false; // Online update of cumulative size and center-of-mass cum_size++; hp_scalar_type mult1 = (hp_scalar_type) (cum_size - 1) / (hp_scalar_type) cum_size; hp_scalar_type mult2 = 1.0 / (hp_scalar_type) cum_size; for(unsigned int d = 0; d < _emb_dimension; d++) _center_of_mass[d] *= mult1; for(unsigned int d = 0; d < _emb_dimension; d++) _center_of_mass[d] += mult2 * point[d]; // If there is space in this quad tree and it is a leaf, add the object here if(is_leaf && size < QT_NODE_CAPACITY) { index[size] = new_index; size++; return true; } // Don't add duplicates for now (this is not very nice) bool any_duplicate = false; for(unsigned int n = 0; n < size; n++) { bool duplicate = true; for(unsigned int d = 0; d < _emb_dimension; d++) { if(point[d] != _emb_positions[index[n] * _emb_dimension + d]) { duplicate = false; break; } } any_duplicate = any_duplicate | duplicate; } if(any_duplicate) return true; // Otherwise, we need to subdivide the current cell if(is_leaf) subdivide(); // Find out where the point can be inserted for(unsigned int i = 0; i < no_children; i++) { if(children[i]->insert(new_index)) return true; } // Otherwise, the point cannot be inserted (this should never happen) return false; } } // Create four children which fully divide this cell into four quads of equal area template <typename scalar_type> void SPTree<scalar_type>::subdivide() { // Create new children hp_scalar_type* new_corner = (hp_scalar_type*) malloc(_emb_dimension * sizeof(hp_scalar_type)); hp_scalar_type* new_width = (hp_scalar_type*) malloc(_emb_dimension * sizeof(hp_scalar_type)); for(unsigned int i = 0; i < no_children; i++) { unsigned int div = 1; for(unsigned int d = 0; d < _emb_dimension; d++) { new_width[d] = .5 * boundary->getWidth(d); if((i / div) % 2 == 1) new_corner[d] = boundary->getCorner(d) - .5 * boundary->getWidth(d); else new_corner[d] = boundary->getCorner(d) + .5 * boundary->getWidth(d); div *= 2; } children[i] = new SPTree(this, _emb_dimension, _emb_positions, new_corner, new_width); } free(new_corner); free(new_width); // Move existing points to correct children for(unsigned int i = 0; i < size; i++) { bool success = false; for(unsigned int j = 0; j < no_children; j++) { if(!success) success = children[j]->insert(index[i]); } index[i] = -1; } // Empty parent node size = 0; is_leaf = false; } // Build SPTree on dataset template <typename scalar_type> void SPTree<scalar_type>::fill(unsigned int N) { int i = 0; //#pragma omp parallel for for(i = 0; i < N; i++) insert(i); } // Checks whether the specified tree is correct template <typename scalar_type> bool SPTree<scalar_type>::isCorrect() { for(unsigned int n = 0; n < size; n++) { scalar_type* point = _emb_positions + index[n] * _emb_dimension; if(!boundary->containsPoint(point)) return false; } if(!is_leaf) { bool correct = true; for(int i = 0; i < no_children; i++) correct = correct && children[i]->isCorrect(); return correct; } else return true; } // Build a list of all indices in SPTree template <typename scalar_type> void SPTree<scalar_type>::getAllIndices(unsigned int* indices) { getAllIndices(indices, 0); } // Build a list of all indices in SPTree template <typename scalar_type> unsigned int SPTree<scalar_type>::getAllIndices(unsigned int* indices, unsigned int loc) { // Gather indices in current quadrant for(unsigned int i = 0; i < size; i++) indices[loc + i] = index[i]; loc += size; // Gather indices in children if(!is_leaf) { for(int i = 0; i < no_children; i++) loc = children[i]->getAllIndices(indices, loc); } return loc; } template <typename scalar_type> unsigned int SPTree<scalar_type>::getDepth() { if(is_leaf) return 1; unsigned int depth = 0; for(unsigned int i = 0; i < no_children; i++) //depth = fmax(depth, children[i]->getDepth()); //C++11 depth = std::max(depth, children[i]->getDepth()); return 1 + depth; } // Compute non-edge forces using Barnes-Hut algorithm template <typename scalar_type> void SPTree<scalar_type>::computeNonEdgeForcesOMP(unsigned int point_index, hp_scalar_type theta, hp_scalar_type neg_f[], hp_scalar_type& sum_Q)const { std::vector<hp_scalar_type> buff(_emb_dimension,0); // Make sure that we spend no time on empty nodes or self-interactions if(cum_size == 0 || (is_leaf && size == 1 && index[0] == point_index)) return; // Compute distance between point and center-of-mass hp_scalar_type D = .0; unsigned int ind = point_index * _emb_dimension; for(unsigned int d = 0; d < _emb_dimension; d++) buff[d] = _emb_positions[ind + d] - _center_of_mass[d]; for(unsigned int d = 0; d < _emb_dimension; d++) D += buff[d] * buff[d]; // Check whether we can use this node as a "summary" hp_scalar_type max_width = 0.0; hp_scalar_type cur_width; for(unsigned int d = 0; d < _emb_dimension; d++) { cur_width = boundary->getWidth(d); max_width = (max_width > cur_width) ? max_width : cur_width; } if(is_leaf || max_width / sqrt(D) < theta) { // Compute and add t-SNE force between point and current node D = 1.0 / (1.0 + D); hp_scalar_type mult = cum_size * D; sum_Q += mult; mult *= D; for(unsigned int d = 0; d < _emb_dimension; d++) neg_f[d] += mult * buff[d]; } else { // Recursively apply Barnes-Hut to children for(unsigned int i = 0; i < no_children; i++) children[i]->computeNonEdgeForcesOMP(point_index, theta, neg_f, sum_Q); } } // Compute non-edge forces using Barnes-Hut algorithm template <typename scalar_type> void SPTree<scalar_type>::computeNonEdgeForces(unsigned int point_index, hp_scalar_type theta, hp_scalar_type neg_f[], hp_scalar_type* sum_Q)const { std::vector<hp_scalar_type> buff(_emb_dimension,0); // Make sure that we spend no time on empty nodes or self-interactions if(cum_size == 0 || (is_leaf && size == 1 && index[0] == point_index)) return; // Compute distance between point and center-of-mass hp_scalar_type D = .0; unsigned int ind = point_index * _emb_dimension; for(unsigned int d = 0; d < _emb_dimension; d++) buff[d] = _emb_positions[ind + d] - _center_of_mass[d]; for(unsigned int d = 0; d < _emb_dimension; d++) D += buff[d] * buff[d]; // Check whether we can use this node as a "summary" hp_scalar_type max_width = 0.0; hp_scalar_type cur_width; for(unsigned int d = 0; d < _emb_dimension; d++) { cur_width = boundary->getWidth(d); max_width = (max_width > cur_width) ? max_width : cur_width; } if(is_leaf || max_width / sqrt(D) < theta) { // Compute and add t-SNE force between point and current node D = 1.0 / (1.0 + D); hp_scalar_type mult = cum_size * D; *sum_Q += mult; mult *= D; for(unsigned int d = 0; d < _emb_dimension; d++) neg_f[d] += mult * buff[d]; } else { // Recursively apply Barnes-Hut to children for(unsigned int i = 0; i < no_children; i++) children[i]->computeNonEdgeForces(point_index, theta, neg_f, sum_Q); } } // Computes edge forces template <typename scalar_type> void SPTree<scalar_type>::computeEdgeForces(unsigned int* row_P, unsigned int* col_P, hp_scalar_type* val_P, hp_scalar_type multiplier, int N, hp_scalar_type* pos_f)const { #ifdef __USE_GCD__ std::cout << "GCD dispatch, sptree_inl 468.\n"; dispatch_apply(N, dispatch_get_global_queue(0, 0), ^(size_t n) { #else #pragma omp parallel for for(int n = 0; n < N; n++) { #endif //__USE_GCD__ std::vector<hp_scalar_type> buff(_emb_dimension,0); // Loop over all edges in the graph unsigned int ind1, ind2; hp_scalar_type D; ind1 = n * _emb_dimension; for(unsigned int i = row_P[n]; i < row_P[n + 1]; i++) { // Compute pairwise distance and Q-value D = 1.0; ind2 = col_P[i] * _emb_dimension; for(unsigned int d = 0; d < _emb_dimension; d++) buff[d] = _emb_positions[ind1 + d] - _emb_positions[ind2 + d]; for(unsigned int d = 0; d < _emb_dimension; d++) D += buff[d] * buff[d]; D = val_P[i] * multiplier / D; // Sum positive force for(unsigned int d = 0; d < _emb_dimension; d++) pos_f[ind1 + d] += D * buff[d]; } } #ifdef __USE_GCD__ ); #endif } /* void SPTree::computeEdgeForces(const KNNSparseMatrix<hp_scalar_type>& sparse_matrix, hp_scalar_type multiplier, hp_scalar_type* pos_f)const{ const int N = sparse_matrix._symmetric_matrix.size(); //std::lock_guard<std::mutex> lock(sparse_matrix._write_mutex); // Loop over all edges in the graph int n = 0; #pragma omp parallel for for(n = 0; n < N; n++) { std::vector<hp_scalar_type> buff(_emb_dimension,0); unsigned int ind1, ind2; hp_scalar_type q_ij_1; ind1 = n * _emb_dimension; for(auto idx: sparse_matrix._symmetric_matrix[n]) { // Compute pairwise distance and Q-value q_ij_1 = 1.0; ind2 = idx.first * _emb_dimension; for(unsigned int d = 0; d < _emb_dimension; d++) buff[d] = _emb_positions[ind1 + d] - _emb_positions[ind2 + d]; //buff contains (yi-yj) per each _emb_dimension for(unsigned int d = 0; d < _emb_dimension; d++) q_ij_1 += buff[d] * buff[d]; auto a = std::get<0>(idx.second); auto b = std::get<1>(idx.second); hp_scalar_type p_ij = std::get<1>(a)/sparse_matrix._row_normalization[std::get<0>(a)] + std::get<1>(b)/sparse_matrix._row_normalization[std::get<0>(b)]; hp_scalar_type res = p_ij * multiplier / q_ij_1 / sparse_matrix._normalization_factor; // Sum positive force for(unsigned int d = 0; d < _emb_dimension; d++) pos_f[ind1 + d] += res * buff[d]; //(p_ij*q_j*mult) * (yi-yj) } } } void SPTree::computeEdgeForces(const KNNSparseMatrix<hp_scalar_type>& sparse_matrix, hp_scalar_type* pos_f)const{ const int N = sparse_matrix._symmetric_matrix.size(); //std::lock_guard<std::mutex> lock(sparse_matrix._write_mutex); // Loop over all edges in the graph int n = 0; #pragma omp parallel for for(n = 0; n < N; n++) { std::vector<hp_scalar_type> buff(_emb_dimension,0); unsigned int ind1, ind2; hp_scalar_type q_ij_1; ind1 = n * _emb_dimension; for(auto idx: sparse_matrix._symmetric_matrix[n]) { // Compute pairwise distance and Q-value q_ij_1 = 1.0; ind2 = idx.first * _emb_dimension; for(unsigned int d = 0; d < _emb_dimension; d++) buff[d] = _emb_positions[ind1 + d] - _emb_positions[ind2 + d]; //buff contains (yi-yj) per each _emb_dimension for(unsigned int d = 0; d < _emb_dimension; d++) q_ij_1 += buff[d] * buff[d]; auto a = std::get<0>(idx.second); auto b = std::get<1>(idx.second); hp_scalar_type p_ij = std::get<1>(a)/sparse_matrix._row_normalization[std::get<0>(a)] + std::get<1>(b)/sparse_matrix._row_normalization[std::get<0>(b)]; hp_scalar_type res = p_ij * sparse_matrix._exaggeration_factors[n] / q_ij_1 / sparse_matrix._normalization_factor; // Sum positive force for(unsigned int d = 0; d < _emb_dimension; d++) pos_f[ind1 + d] += res * buff[d]; //(p_ij*q_j*mult) * (yi-yj) } } } */ //! Print out tree template <typename scalar_type> void SPTree<scalar_type>::print() { if(cum_size == 0) { printf("Empty node\n"); return; } if(is_leaf) { printf("Leaf node; _emb_positions = ["); for(int i = 0; i < size; i++) { scalar_type* point = _emb_positions + index[i] * _emb_dimension; for(int d = 0; d < _emb_dimension; d++) printf("%f, ", point[d]); printf(" (index = %d)", index[i]); if(i < size - 1) printf("\n"); else printf("]\n"); } } else { printf("Intersection node with center-of-mass = ["); for(int d = 0; d < _emb_dimension; d++) printf("%f, ", _center_of_mass[d]); printf("]; children are:\n"); for(int i = 0; i < no_children; i++) children[i]->print(); } } } } #endif
GB_unop__identity_uint32_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_uint32_fc64 // op(A') function: GB_unop_tran__identity_uint32_fc64 // C type: uint32_t // A type: GxB_FC64_t // cast: uint32_t cij = GB_cast_to_uint32_t (creal (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint32_t z = GB_cast_to_uint32_t (creal (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint32_t z = GB_cast_to_uint32_t (creal (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT32 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_uint32_fc64 ( uint32_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; uint32_t z = GB_cast_to_uint32_t (creal (aij)) ; Cx [p] = z ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_uint32_fc64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__ainv_int64_int64.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__ainv_int64_int64) // op(A') function: GB (_unop_tran__ainv_int64_int64) // C type: int64_t // A type: int64_t // cast: int64_t cij = aij // unaryop: cij = -aij #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 = -x ; // 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] = -z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__ainv_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] = -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 ; int64_t aij = Ax [p] ; int64_t z = aij ; Cx [p] = -z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__ainv_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
4.c
#include <stdio.h> #include <omp.h> int main() { int x=0, size=16; omp_set_num_threads(size); #pragma omp parallel shared(x) { x=x+1; } printf("%d\n",x); return 0; }
gemm_mkl_ref.h
/* Copyright (c) 2018 NoobsHPC Authors All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef NBHPC_ICESWORD_OPERATOR_X86_GEMM_REF_H #define NBHPC_ICESWORD_OPERATOR_X86_GEMM_REF_H #pragma once #include "mkl.h" #include "omp_thread.h" #include "icesword/operator/gemm.h" #include <iostream> namespace noobshpc { namespace icesword { /* row major: mem_a: dim_m * dim_k mem_b: dim_k * dim_n mem_c: dim_m * dim_n col major: mem_a: dim_k * dim_m mem_b: dim_n * dim_k mem_c: dim_n * dim_m matrix(C) = beta * matrix(C) + offset_c + alpha * { matrix(A) + offset_a } * { op(B) + offset_b } */ template<DataType a_dtype, DataType b_dtype, DataType c_dtype> class GEMM_REF <X86, a_dtype, b_dtype, c_dtype> { public: typedef typename DataTrait<X86, a_dtype>::Dtype A_DType; typedef typename DataTrait<X86, b_dtype>::Dtype B_DType; typedef typename DataTrait<X86, c_dtype>::Dtype C_DType; GEMM_REF() : thread_num(ice_get_max_threads()) {} ~GEMM_REF() {} Status execute(const void* a_mem, const void* b_mem, const void* oc_mem, void* c_mem, const char oc_mode, const bool col_major, const size_t oa, const size_t ob, const size_t m, const size_t n, const size_t k, const bool trans_a, const bool trans_b, const float beta, const float alpha) { size_t lda, ldb, ldc; if (col_major) { lda = trans_a ? k : m; ldb = trans_b ? n : k; ldc = m; } else { lda = trans_a ? m : k; ldb = trans_b ? k : n; ldc = n; } return execute(a_mem, b_mem, oc_mem, c_mem, col_major, oa, ob, m, n, k, lda, ldb, ldc, trans_a, trans_b, beta, alpha, oc_mode); } Status execute(const void* a_mem, const void* b_mem, const void* oc_mem, void* c_mem, const bool col_major, const size_t oa, const size_t ob, const size_t m, // mem_c -> col_major ? width : hight const size_t n, // mem_c -> col_major ? hight : width const size_t k, // matrix a,b common dim const size_t lda, // len(mem_a) / m const size_t ldb, // len(mem_b) / n const size_t ldc, // len(mem_c) / k const bool trans_a, const bool trans_b, const float beta, const float alpha, const char oc_mode) { auto status = execute_check(a_mem, b_mem, oc_mem, c_mem, oc_mode); if (status != S_Success) { return S_InvalidValue; } bool a_trans = false; bool b_trans = false; size_t dim_m = 0; size_t dim_n = 0; size_t dim_k = 0; size_t stride_a = 0; size_t stride_b = 0; size_t offset_a = 0; size_t offset_b = 0; size_t oc_method = 1; const A_DType * mem_a = nullptr; const B_DType * mem_b = nullptr; const C_DType * mem_o = nullptr; C_DType * mem_c = nullptr; /* ROW_MAJOR : mem_a : {m, k} mem_b : {k, n} mem_c : {m, n} COL_MAJOR : mem_a : {k, m} mem_b : {n, k} mem_c : {n, m} Convert to row major */ if (col_major) { mem_a = static_cast<const A_DType *>(b_mem); mem_b = static_cast<const B_DType *>(a_mem); mem_o = static_cast<const C_DType *>(oc_mem); mem_c = static_cast<C_DType *>(c_mem); a_trans = trans_b; b_trans = trans_a; offset_a = ob; offset_b = oa; dim_m = n; dim_n = m; dim_k = k; stride_a = ldb; stride_b = lda; oc_method = oc_mode == 'F' ? 2 : oc_mode == 'R' ? 4 : oc_mode == 'C' ? 3 : oc_mode == 'A' ? 5 : 1; } else { mem_a = static_cast<const A_DType *>(a_mem); mem_b = static_cast<const B_DType *>(b_mem); mem_o = static_cast<const C_DType *>(oc_mem); mem_c = static_cast<C_DType *>(c_mem); a_trans = trans_a; b_trans = trans_b; offset_a = oa; offset_b = ob; dim_m = m; dim_n = n; dim_k = k; stride_a = lda; stride_b = ldb; oc_method = oc_mode == 'F' ? 2 : oc_mode == 'R' ? 3 : oc_mode == 'C' ? 4 : oc_mode == 'A' ? 5 : 1; } #ifdef ICESWORD_VERBOSE // compute as row major, row message LOG(INFO) << "GEMM_REF_VERBOSE {" << " transa:" << (a_trans ? "true" : "false") << " transb:" << (b_trans ? "true" : "false") << " m:" << dim_m << " n:" << dim_n << " k:" << dim_k << " oa:" << offset_a << " ob:" << offset_b << " lda:" << stride_a << " ldb:" << stride_b << " ldc:" << ldc << " beta:" << beta << " alpha:" << alpha << " }"; #endif // compute as row major #pragma omp parallel for collapse(2) num_threads(thread_num) for (auto m = 0; m < dim_m; ++m) { for (auto n = 0; n < dim_n; ++n) { C_DType ip_a_b = 0; auto c_index = m * ldc + n; float mem_c_beta = beta * mem_c[c_index]; #pragma omp simd for (auto k = 0; k < dim_k; ++k) { auto ab_index = index_calculate(stride_a, stride_b, m, n, k, a_trans, b_trans); auto a_index = ab_index[0]; auto b_index = ab_index[1]; ip_a_b += (mem_a[a_index] + offset_a) * (mem_b[b_index] + offset_b); } float alpha_ab_beta_c = alpha * ip_a_b + mem_c_beta; switch (oc_method) { case 1 : mem_c[c_index] = alpha_ab_beta_c; break; case 2 : mem_c[c_index] = alpha_ab_beta_c + mem_o[0]; break; case 3 : mem_c[c_index] = alpha_ab_beta_c + mem_o[n]; break; case 4 : mem_c[c_index] = alpha_ab_beta_c + mem_o[m]; break; } } } return S_Success; } private: size_t thread_num; Status execute_check(const void* mem_a, const void* mem_b, const void* mem_oc, void* mem_c, const char oc_mode) { if (mem_a == nullptr || mem_b == nullptr || mem_b == nullptr) { LOG(ERROR) << "wrong empty pointer !"; return S_InvalidValue; } if (oc_mode != 'N' && oc_mode != 'F' && oc_mode != 'C' && oc_mode != 'R' && oc_mode != 'A') { LOG(ERROR) << "wrong mem_oc mode !"; return S_InvalidValue; } if (oc_mode != 'N' && mem_oc == nullptr) { LOG(ERROR) << "wrong mem_oc pointer !"; return S_InvalidValue; } return S_Success; } std::vector<size_t> index_calculate(const size_t lda, const size_t ldb, const size_t m, const size_t n, const size_t k, const bool trans_a, const bool trans_b) { if (trans_a == false && trans_b == false) { // dim_m * dim_k, dim_k * dim_n return {m * lda + k, k * ldb + n}; } else if (trans_a == true && trans_b == false) { // dim_k * dim_m, dim_k * dim_n return {k * lda + m, k * ldb + n}; } else if (trans_a == false && trans_b == true) { // dim_m * dim_k, dim_n * dim_k return {m * lda + k, n * ldb + k}; } else if (trans_a == true && trans_b == true) { // dim_k * dim_m, dim_n * dim_k return {k * lda + m, n * ldb + k}; } return {0, 0}; }; }; // class end } // namespace icesword } // namespace noobshpc #endif // NBHPC_ICESWORD_OPERATOR_X86_GEMM_REF_H
ktruss.c
//------------------------------------------------------------------------------ // ktruss: construct the k_truss of a graph //------------------------------------------------------------------------------ // C = ktruss (A,k), the k-truss of the graph A // On input, A is the adjacency matrix of a graph, which must be square with // symmetric pattern, and no diagonal entries. These conditions are not // checked. A is treated as if binary on input so the content of Ax is ignored // on input. The matrix A is represented in compressed sparse column form as // Ap, Ai, and n on input. That is, the pattern of column A(:,j) is held in // Ai [Ap [j] ... Ap [j+1]-1], where Ap [0] = 0 and Ap [n] = nnz (A). // The value of k for the requested k-truss is provided as the scalar input, // support = k-2, which must be > 0. // On output, the input graph A is overwitten with the graph C, which is the // k-truss subgraph of A. Its edges are a subset of the input graph A. Each // edge in C is part of at least k-2 triangles in C. The pattern of C, (that // is, spones(C) in MATLAB notation), is the adjacency matrix of the k-truss // subgraph of A. The edge weights of C are the support of each edge. That // is, C(i,j)=nt if the edge (i,j) is part of nt triangles in C. All edges in // C have support of at least k-2. The total number of triangles in C is // sum(sum(C))/6 in MATLAB notation. The number of edges in C is nnz(C)/2, in // MATLAB notation, or Ap [n]/2. C is returned as symmetric with a zero-free // diagonal, with all entries greater than or equal to k-2. The matrix C is // returned on output in compressed sparse column form in Ap, Ai, Ax, and n (n // doesn't change). That is, the pattern and values of C(:,j) are held in Ai // [Ap [j] ... Ap [j+1]-1] and Ax [Ap [j] ... Ap [j+1]-1], where Ap [0] = 0 and // Ap [n] = nnz (C). // The return value is the # of steps the algorithm performed, or <= 0 on // error, where 0 indicates that the support input was invalid, and -1 // indicates an out-of-memory condition. #include "ktruss_def.h" _Thread_local Index *restrict w = NULL ; _Thread_local bool *restrict Mark = NULL ; int64_t ktruss // # steps taken, or <= 0 if error ( // input/output: int64_t *restrict Ap, // column pointers, size n+1 Index *restrict Ai, // row indices, size anz = Ap [n] // output, content not defined on input: Index *restrict Ax, // values // input, not modified: const Index n, // A is n-by-n const Index support, // support = (k-2) for a k-truss, must be > 0 const int threads, // # of threads const Index chunk // scheduler chunk size ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- if (support <= 0) return (0) ; int nthreads = (n < chunk) ? 1 : threads ; //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- bool ok = true ; #pragma omp parallel num_threads(nthreads) reduction(&&:ok) { w = (Index *) calloc (n, sizeof (Index)) ; Mark = (bool *) calloc (n, sizeof (bool )) ; ok = (Mark != NULL && w != NULL) ; } #pragma omp parallel num_threads(nthreads) { if (!ok) { // out of memory if (w != NULL) free (w ) ; if (Mark != NULL) free (Mark) ; } } if (!ok) return (-1) ; double tmult = 0 ; double tsel = 0 ; //-------------------------------------------------------------------------- // C = ktruss (A) //-------------------------------------------------------------------------- for (int64_t nsteps = 1 ; ; nsteps++) { //---------------------------------------------------------------------- // C = (A*A) .* A //---------------------------------------------------------------------- // This step computes the values of C in Ax. The pattern of A and C // are the same, and are in Ap, Ai, and n. A is treated as if binary // so its values are ignored. This computation is a mimic for // GrB_mxm (C, A, NULL, GxB_PLUS_LAND_INT64, A, A, NULL), except that // here, the output C can overwrite the input A. printf ("step %" PRId64"\n", nsteps) ; double t1 = omp_get_wtime ( ) ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,chunk) for (Index j = 0 ; j < n ; j++) { // scatter A(:,j) into Mark. All of w is zero. for (int64_t p = Ap [j] ; p < Ap [j+1] ; p++) { Mark [Ai [p]] = 1 ; } // C(:,j) = (A * A(:,j)) .* Mark for (int64_t p = Ap [j] ; p < Ap [j+1] ; p++) { const Index k = Ai [p] ; // (row k, not k-truss) // C(:,j) += (A(:,k) * A(k,j)) .* Mark for (int64_t pa = Ap [k] ; pa < Ap [k+1] ; pa++) { // C(i,j) += (A(i,k) * A(k,j)) .* Mark Index i = Ai [pa] ; if (Mark [i]) w [i]++ ; } } // gather C(:,j) from the workspace and clear the Mark for (int64_t p = Ap [j] ; p < Ap [j+1] ; p++) { Index i = Ai [p] ; Ax [p] = w [i] ; Mark [i] = 0 ; w [i] = 0 ; } } double t2 = omp_get_wtime ( ) ; printf ("C<C>=C*C time: %g\n", t2-t1) ; tmult += (t2-t1) ; //---------------------------------------------------------------------- // anz = nnz (A) //---------------------------------------------------------------------- int64_t anz = Ap [n] ; //---------------------------------------------------------------------- // C = C .* (C >= support) //---------------------------------------------------------------------- // C is now in Ap, Ai, Ax, and n. Prune all entries C(i,j) < support. // This code snippet is a mimic for // GxB_select (T, NULL, NULL, supportop, C, Support, NULL) // except that this code can operate on C in-place. int64_t cnz = 0 ; for (Index j = 0 ; j < n ; j++) { // log the start of column C(:,j) int64_t p1 = Ap [j] ; Ap [j] = cnz ; for (int64_t p = p1 ; p < Ap [j+1] ; p++) { // consider the edge C(i,j) Index i = Ai [p] ; Index cij = Ax [p] ; if (cij >= support) { // the edge C(i,j) has enough support; keep it Ai [cnz ] = i ; Ax [cnz++] = cij ; } } } Ap [n] = cnz ; double t3 = omp_get_wtime ( ) ; printf ("select time: %g\n", t3-t2) ; tsel += (t3-t2) ; //---------------------------------------------------------------------- // if (nnz (C) == nnz (A)) return //---------------------------------------------------------------------- if (cnz == anz) { // k-truss has been found, free workspace and return result printf ("ktruss nthreads %d done: tmult %g tsel %g\n", nthreads, tmult, tsel) ; #pragma omp parallel num_threads(nthreads) { free (w) ; free (Mark) ; } return (nsteps) ; } } }
3d7pt.c
/* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; 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; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k]) + beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] + A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
concat_ref.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2021, OPEN AI LAB * Author: jjzeng@openailab.com */ #include "concat_param.h" #include "graph/tensor.h" #include "graph/node.h" #include "graph/graph.h" #include "module/module.h" #include "operator/op.h" #include "device/cpu/cpu_node.h" #include "device/cpu/cpu_graph.h" #include "device/cpu/cpu_module.h" #include "utility/float.h" #include "utility/sys_port.h" #include "utility/log.h" #include <math.h> #include <string.h> struct shape_dim { int dim[4]; float scale; int zero; }; struct concat_op_param { struct shape_dim* input_shape; int input_counts; int input_dim; struct shape_dim output_shape; int output_dim; int axis; float out_scale; void** input_data; }; static int ref_concat_fp32(const float** in_data, float* out_data, const struct concat_op_param* param) { int axis = param->axis; int concat_dim = 0; for (int ii = 0; ii < param->input_counts; ++ii) { concat_dim += param->input_shape[ii].dim[axis]; } if (concat_dim != param->output_shape.dim[axis]) { TLOG_ERR("concant dimensions[%d] is not same output[%d]\n", concat_dim, param->output_shape.dim[axis]); return -1; } int out_size, in_size; out_size = 1; for (int ii = 0; ii < axis; ++ii) { out_size *= param->output_shape.dim[ii]; } in_size = 1; for (int ii = axis + 1; ii < param->output_dim; ++ii) { in_size *= param->input_shape[0].dim[ii]; } float* output_ptr = out_data; for (int k = 0; k < out_size; ++k) { // #pragma omp parallel for num_threads(num_thread) for (int j = 0; j < param->input_counts; ++j) { int cp_size = param->input_shape[j].dim[axis] * in_size; memcpy(output_ptr, in_data[j] + k * cp_size, cp_size * sizeof(float)); output_ptr += cp_size; } } return 0; } static int ref_concat_fp16(const fp16_t** in_data, fp16_t* out_data, const struct concat_op_param* param) { int axis = param->axis; int concat_dim = 0; for(int ii = 0; ii < param->input_counts; ++ii) { concat_dim += param->input_shape[ii].dim[axis]; } if(concat_dim != param->output_shape.dim[axis]) { TLOG_ERR("concat dimensions is not same output: ( %d -- %d )\n", concat_dim, param->output_shape.dim[axis]); return -1; } int out_size, in_size; out_size = 1; for(int ii = 0; ii < axis; ++ii) { out_size *= param->output_shape.dim[ii]; } in_size = 1; for(int ii = axis + 1; ii < param->output_dim; ++ii) { in_size *= param->input_shape[0].dim[ii]; } fp16_t* output_ptr = out_data; for(int k = 0; k < out_size; ++k) { for(int j = 0; j < param->input_counts; ++j) { int cp_size = param->input_shape[j].dim[axis] * in_size; memcpy(output_ptr, in_data[j] + k * cp_size, cp_size * sizeof(fp16_t)); output_ptr += cp_size; } } return 0; } static int ref_concat_uint8(const uint8_t** in_data, uint8_t* out_data, const struct concat_op_param* param) { int axis = param->axis; int concat_dim = 0; for (int ii = 0; ii < param->input_counts; ++ii) { concat_dim += param->input_shape[ii].dim[axis]; } if (concat_dim != param->output_shape.dim[axis]) { TLOG_ERR("concat dimensions is not same output: ( %d -- %d )\n", concat_dim, param->output_shape.dim[axis]); return -1; } int outer_size, in_size; outer_size = 1; for (int ii = 0; ii < axis; ++ii) { outer_size *= param->output_shape.dim[ii]; } in_size = 1; for (int ii = axis + 1; ii < param->output_dim; ++ii) { in_size *= param->output_shape.dim[ii]; } int output_size = 1; for (int ii = 0; ii < param->output_dim; ++ii) { output_size *= param->output_shape.dim[ii]; } uint8_t* output_ptr = out_data; float out_scale = param->output_shape.scale; uint8_t out_zero = param->output_shape.zero; for (int k = 0; k < outer_size; ++k) { for (int j = 0; j < param->input_counts; ++j) { int cp_size = param->input_shape[j].dim[axis] * in_size; float scale = param->input_shape[j].scale; uint8_t input_zero = param->input_shape[j].zero; const uint8_t* input_ptr = ( const uint8_t* )(in_data[j] + k * cp_size); if (scale == out_scale && input_zero == out_zero) { memcpy(output_ptr, input_ptr, cp_size); } else { float t_scale = scale / out_scale; for (int ii = 0; ii < cp_size; ++ii) { output_ptr[ii] = round((input_ptr[ii] - input_zero) * t_scale) + out_zero; } } output_ptr += cp_size; } } return 0; } static int ref_concat_int8(const int8_t** in_data, int8_t* out_data, const struct concat_op_param* param) { int axis = param->axis; int concat_dim = 0; for (int ii = 0; ii < param->input_counts; ++ii) { concat_dim += param->input_shape[ii].dim[axis]; } if (concat_dim != param->output_shape.dim[axis]) { TLOG_ERR("concat dimensions is not same output: ( %d -- %d )\n", concat_dim, param->output_shape.dim[axis]); return -1; } int outer_size, in_size; outer_size = 1; for (int ii = 0; ii < axis; ++ii) { outer_size *= param->output_shape.dim[ii]; } in_size = 1; for (int ii = axis + 1; ii < param->output_dim; ++ii) { in_size *= param->output_shape.dim[ii]; } int output_size = 1; for (int ii = 0; ii < param->output_dim; ++ii) { output_size *= param->output_shape.dim[ii]; } int8_t* output_ptr = out_data; float output_scale = param->output_shape.scale; for (int k = 0; k < outer_size; ++k) { for (int j = 0; j < param->input_counts; ++j) { int cp_size = param->input_shape[j].dim[axis] * in_size; float input_scale = param->input_shape[j].scale; const int8_t* input_ptr = ( const int8_t* )(in_data[j] + k * cp_size); if (input_scale == output_scale) { memcpy(output_ptr, input_ptr, cp_size); } else { float requant_scale = input_scale / output_scale; for (int ii = 0; ii < cp_size; ++ii) { int data_i32 = (int)roundf((float )input_ptr[ii] * requant_scale); if (data_i32 > 127) data_i32 = 127; else if (data_i32 < -127) data_i32 = -127; output_ptr[ii] = (int8_t)data_i32; } } output_ptr += cp_size; } } return 0; } static int init_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct concat_op_param* concat_op_param = ( struct concat_op_param* )sys_malloc(sizeof(struct concat_op_param)); concat_op_param->axis = 0; concat_op_param->input_counts = 1; concat_op_param->input_dim = 1; concat_op_param->input_shape = NULL; concat_op_param->out_scale = 0.1f; concat_op_param->output_dim = 1; exec_node->ops_priv = concat_op_param; return 0; } static int release_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { sys_free(exec_node->ops_priv); return 0; } static int prerun(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct node* ir_node = exec_node->ir_node; struct graph* ir_graph = ir_node->graph; struct tensor* output_tensor; output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]); struct concat_op_param* concat_op_param = ( struct concat_op_param* )exec_node->ops_priv; struct concat_param* concat_param = ( struct concat_param* )ir_node->op.param_mem; concat_op_param->axis = concat_param->axis; concat_op_param->input_counts = ir_node->input_num; concat_op_param->input_shape = ( struct shape_dim* )sys_malloc(sizeof(struct shape_dim) * ir_node->input_num); concat_op_param->output_dim = output_tensor->dim_num; for (int ii = 0; ii < output_tensor->dim_num; ii++) { concat_op_param->output_shape.dim[ii] = output_tensor->dims[ii]; concat_op_param->output_shape.scale = output_tensor->scale; concat_op_param->output_shape.zero = output_tensor->zero_point; } concat_op_param->input_data = ( void* )sys_malloc(sizeof(void*) * ir_node->input_num); return 0; } static int run(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct node* ir_node = exec_node->ir_node; struct graph* ir_graph = ir_node->graph; struct tensor* input_tensor; struct tensor* output_tensor; output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]); struct concat_op_param* concat_op_param = ( struct concat_op_param* )exec_node->ops_priv; void* out_data = output_tensor->data; for (int i = 0; i < ir_node->input_num; i++) { input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[i]); int number = input_tensor->dim_num; for (int j = 0; j < number; j++) { concat_op_param->input_shape[i].dim[j] = input_tensor->dims[j]; concat_op_param->input_shape[i].scale = input_tensor->scale; concat_op_param->input_shape[i].zero = input_tensor->zero_point; } concat_op_param->input_data[i] = input_tensor->data; } int ret = -1; if (input_tensor->data_type == TENGINE_DT_FP32) ret = ref_concat_fp32(( const float** )concat_op_param->input_data, out_data, concat_op_param); else if (input_tensor->data_type == TENGINE_DT_FP16) ret = ref_concat_fp16(( const fp16_t** )concat_op_param->input_data, out_data, concat_op_param); else if (input_tensor->data_type == TENGINE_DT_UINT8) ret = ref_concat_uint8(( const uint8_t** )concat_op_param->input_data, out_data, concat_op_param); else if (input_tensor->data_type == TENGINE_DT_INT8) ret = ref_concat_int8(( const int8_t** )concat_op_param->input_data, out_data, concat_op_param); else TLOG_ERR("Input data type %d not to be supported.\n", input_tensor->data_type); return ret; } static int postrun(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph) { struct concat_op_param* concat_op_param = ( struct concat_op_param* )exec_node->ops_priv; sys_free(concat_op_param->input_shape); sys_free(concat_op_param->input_data); return 0; } static int score(struct node_ops* node_ops, struct exec_graph* exec_graph, struct node* exec_node) { return OPS_SCORE_CANDO; } static struct node_ops hcl_node_ops = {.prerun = prerun, .run = run, .reshape = NULL, .postrun = postrun, .init_node = init_node, .release_node = release_node, .score = score}; int register_concat_ref_op(void* arg) { return register_builtin_node_ops(OP_CONCAT, &hcl_node_ops); } int unregister_concat_ref_op(void* arg) { return unregister_builtin_node_ops(OP_CONCAT, &hcl_node_ops); }
pr33880.c
/* PR middle-end/33880 */ /* { dg-do run } */ extern void abort (void); void test1 (void) { int i = 0, j = 0; void bar (void) { i++; j++; } bar (); #pragma omp parallel for num_threads(4) for (i = 0; i < 100; i++) #pragma omp atomic j += 1; if (j != 101) abort (); #pragma omp parallel for lastprivate(i) num_threads(2) for (i = 0; i < 100; i++) #pragma omp atomic j += 1; if (i != 100) abort (); i = 3; bar (); if (j != 202) abort (); if (i != 4) abort (); } void test2 (void) { int i = -1, j = 99, k, l = 9, m = 0; void bar (void) { i++; j++; l++; m++; } bar (); #pragma omp parallel for num_threads(4) for (k = i; k < j; k += l) #pragma omp atomic m += 1; bar (); if (i != 1 || j != 101 || l != 11 || m != 12) abort (); } void test3 (void) { int i, j, k, l, m; void bar (void) { #pragma omp parallel for num_threads(4) for (i = j; i < k; i += l) #pragma omp atomic m += 1; } void baz (void) { #pragma omp parallel for num_threads(2) lastprivate(i) for (i = j; i < k * 2; i += l / 2) #pragma omp atomic m += 1; } i = 7; j = 0; k = 100; l = 2; m = 0; bar (); if (j != 0 || k != 100 || l != 2 || m != 50) abort (); baz (); if (i != 200 || j != 0 || k != 100 || l != 2 || m != 250) abort (); } void test4 (void) { int i, j, k, l, m = 0; int foo (void) { return j; } int bar (void) { return k; } int baz (void) { return l; } j = 0; k = 1000; l = 2; #pragma omp parallel for num_threads(8) lastprivate(i) for (i = foo (); i < bar (); i += baz ()) #pragma omp atomic m += 1; if (i != 1000 || m != 500 || j != 0 || k != 1000 || l != 2) abort (); } int main (void) { test1 (); test2 (); test3 (); test4 (); return 0; }
GB_binop__bxnor_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the 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__bxnor_int16) // A.*B function (eWiseMult): GB (_AemultB_08__bxnor_int16) // A.*B function (eWiseMult): GB (_AemultB_02__bxnor_int16) // A.*B function (eWiseMult): GB (_AemultB_04__bxnor_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bxnor_int16) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bxnor_int16) // C+=b function (dense accum): GB (_Cdense_accumb__bxnor_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bxnor_int16) // C=scalar+B GB (_bind1st__bxnor_int16) // C=scalar+B' GB (_bind1st_tran__bxnor_int16) // C=A+scalar GB (_bind2nd__bxnor_int16) // C=A'+scalar GB (_bind2nd_tran__bxnor_int16) // C type: int16_t // A type: int16_t // A pattern? 0 // B type: int16_t // B pattern? 0 // BinaryOp: cij = ~((aij) ^ (bij)) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ 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) \ int16_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int16_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ 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 = ~((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_BXNOR || GxB_NO_INT16 || GxB_NO_BXNOR_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__bxnor_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__bxnor_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__bxnor_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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bxnor_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__bxnor_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__bxnor_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__bxnor_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__bxnor_int16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bxnor_int16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else 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] = ~((x) ^ (bij)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bxnor_int16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = GBX (Ax, p, false) ; Cx [p] = ~((aij) ^ (y)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ~((x) ^ (aij)) ; \ } GrB_Info GB (_bind1st_tran__bxnor_int16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ~((aij) ^ (y)) ; \ } GrB_Info GB (_bind2nd_tran__bxnor_int16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
bfs.c
/* * Imports */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <mpi.h> #include <omp.h> #include "filing.c" #include "queue.c" /* Constants */ #define PRINT_VECS 1 // flag so we can turn off printing when N is large #define MAX_RAND 100 // max value of elements generated for array /* Prototypes */ void init_vec(int *vec, int len); void print_vec(const char *label, int *vec, int len); /* Functions */ // Fills a vector with random integers in the range [0, MAX_RAND) void init_vec(int *vec, int len) { int i; for (i = 0; i < len; i++) { vec[i] = rand() % MAX_RAND; } } // Prints the given vector to stdout void print_vec(const char *label, int *vec, int len) { #if PRINT_VECS printf("%s", label); int i; for (i = 0; i < len; i++) { printf("%d ", vec[i]); } printf("\n\n"); #endif } void bfs_sequential(int** graph, int source, int n) { int visited[n]; struct Queue* q = createQueue(); for(int i = 0; i < n; i++) visited[i] = 0; visited[source] = 1; enqueue(q, source); while(!isEmpty(q)){ int u = dequeue(q); for(int v = 0; v < n; v++) { if(graph[u][v] == 1) { if(visited[v] == 0){ visited[v] = 1; enqueue(q, v); } } } } } void bfs_sequential_top_down(int** graph, int source, int n) { int parent[n]; for(int i = 0; i < n; i++) parent[i] = -1; parent[source] = source; struct Queue* frontier = createQueue(); enqueue(frontier, source); struct Queue* next = NULL; while(frontier != NULL) { while(!isEmpty(frontier)){ int u = dequeue(frontier); for(int v = 0; v < n; v++) { if(graph[u][v] == 1) { if(next == NULL) { next = createQueue(); } if(parent[v] == -1) { enqueue(next, v); parent[v] = u; } } } } frontier = next; next = NULL; } } void bfs_sequential_bottom_up(int** graph, int source, int n) { int parent[n]; for(int i = 0; i < n; i++) parent[i] = -1; parent[source] = source; struct Queue* frontier = createQueue(); enqueue(frontier, source); struct Queue* next = NULL; while(frontier != NULL) { for(int u = 0; u < n; u++) { if(parent[u] == -1) { for(int v = 0; v < n; v++) { if(graph[u][v] == 1 && isVInQueue(frontier, v) == 1) { if(next == NULL) { next = createQueue(); } enqueue(next, u); parent[u] = v; break; } } } } frontier = next; next = NULL; } } int main(int argc, char *argv[]) { // Declare process-related vars // and initialize MPI int rank; int num_procs; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); //grab this process's rank MPI_Comm_size(MPI_COMM_WORLD, &num_procs); //grab the total num of processes int** graph; double start_time; double stop_time; char* file_name = "Sparse500.txt"; int n = get_n(file_name); // init graph nxn matrix graph = (int **)malloc(n * sizeof(int *)); for (int i = 0; i < n; i++) { graph[i] = (int *)malloc(n * sizeof(int)); for (int j = 0; j < n; j++) { graph[i][j] = 0; } } load(graph, file_name); if(!rank) { int edges = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if(graph[i][j] == 1) edges++; } } printf("Edges: %d\n", edges); printf("Procs: %d\n", num_procs); printf("File: %s\n", file_name); } srand(time(NULL)); start_time = MPI_Wtime(); int chunk_size = n / num_procs; int owner[n]; // assign first chunk to proc 0 for(int i = 0; i < chunk_size; i++) { owner[i] = 0; } // assign othe chunks to respective processors int curr_owner = 0; for(int i = chunk_size; i < n; i++) { if(i % chunk_size == 0 && curr_owner < num_procs - 1) curr_owner++; owner[i] = curr_owner; } int source = 0; int visited[n]; // init visited array for each proc for(int i = 0; i < n; i++) visited[i] = 0; // init queue for each proc struct Queue* frontier = createQueue(); // if proc 0, enqueue root if(rank == 0) { for(int v = 0; v < n; v++) { if(graph[source][v] == 1) { enqueue(frontier, v); } } visited[source] = 1; } // init 2D send buffer for each proc int **sendBuf = (int **)malloc(num_procs * sizeof(int *)); for (int i = 0; i < num_procs; i++) { sendBuf[i] = (int *)malloc(n * sizeof(int)); for(int j = 0; j < n; j++) sendBuf[i][j] = 0; } // init 1D recv buffer for each proc int* recvBuf = (int *)malloc(n * sizeof(int)); int sendTo[n]; for(int i = 0; i < n; i++) sendTo[i] = 0; // BFS while(frontier != NULL) { struct Queue* remote = createQueue(); struct Queue* local = createQueue(); // set local and remote vertices assignLocalAndRemoteVertices(local, remote, frontier, rank, owner); free(frontier); frontier = NULL; // add vertices from remote to send buf while(!isEmpty(remote)) { int v = dequeue(remote); sendBuf[owner[v]][v] = 1; sendTo[owner[v]] = 1; } // send respective remote vertices MPI_Request request; for(int proc = 0; proc < num_procs; proc++) { if(proc != rank && sendTo[proc] == 1) { MPI_Isend(sendBuf[proc], n, MPI_INT, proc, 1, MPI_COMM_WORLD, &request); sendTo[proc] = 0; } } // process local vertices while(!isEmpty(local)) { int v = dequeue(local); if(visited[v] == 0) { int u; #pragma omp parallel for private(u) for(u = 0; u < n; u++) if(graph[v][u] == 1) { #pragma omp critical { if(frontier == NULL) { frontier = createQueue(); } enqueue(frontier, u); } } visited[v] = 1; } } // recv vertices from remote and enqueue neighbours in frontier MPI_Status status; MPI_Recv(recvBuf, n, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); int j; #pragma omp parallel for private(j) for(j = 0; j < n; j++) { if(recvBuf[j] == 1) { if(visited[j] == 0) { for(int k = 0; k < n; k++) { if(graph[j][k] == 1) { #pragma omp critical { if(frontier == NULL) { frontier = createQueue(); } enqueue(frontier, k); } } } visited[j] = 1; } } } } // wait for all procs to finish -- so execution time noted is correct MPI_Barrier(MPI_COMM_WORLD); if (!rank) { stop_time = MPI_Wtime(); printf("Total time (sec): %f\n", stop_time - start_time); start_time = MPI_Wtime(); bfs_sequential(graph, 0, n); stop_time = MPI_Wtime(); printf("Total time BFS_Sequential (sec): %f\n", stop_time - start_time); printf("BFS TOP DOWN\n"); start_time = MPI_Wtime(); bfs_sequential_top_down(graph, 0, n); stop_time = MPI_Wtime(); printf("Total time BFS_Sequential Top-Down (sec): %f\n", stop_time - start_time); printf("BFS BOTTOM UP\n"); start_time = MPI_Wtime(); bfs_sequential_bottom_up(graph, 0, n); stop_time = MPI_Wtime(); printf("Total time BFS_Sequential Bottom-Up (sec): %f\n", stop_time - start_time); } // Shutdown MPI (important - don't forget!) MPI_Finalize(); return EXIT_SUCCESS;; }
l1b2l1c.c
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ /* GRACE L1B to L1C & L2 Version: 20 Dec 2011 fixed and stochastic constraint solution Copyright (c) 2011 Kun Shang (shang.34@osu.edu) All Right Reserved */ /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ #ifndef _L1B2L1C_H_ #include "l1b2l1c.h" #endif #define MAXLINE 500 double accgr (double *tjd, double *p, double *v, double *fgr) { double GME, GMS, J, Jv[3], beta, gamma, r, v2, pv, pJ, a, b, pxv[3], vxJ[3], ps[3], vs[3], rs, vsxps[3], vsxpsxv[3], term1[3], term2[3], term3[3]; int n; GME = GMA[0]; //m^3/s^2 r = modvect(p); J = 9.8e8; //m^2/s gamma = 1; beta = 1; GMS = 1.32712442076e20; //m^3/s^2 Jv[0] = 0; Jv[1] = 0; Jv[2] = J; v2 = dotvect(v, v); pv = dotvect(p, v); pJ = dotvect(p, Jv); crsvect(p, v, pxv); crsvect(v, Jv, vxJ); planet_ephemeris (tjd, 2, 10, ps, vs); for (n = 0; n < 3; n++) { ps[n] = ps[n] * AU; vs[n] = vs[n] * AU / 86400.0; } rs = modvect(ps); crsvect(vs, ps, vsxps); crsvect(vsxps, v, vsxpsxv); a = 2 * (beta + gamma) * GME / r - gamma * v2; b = 2 * (1 + gamma) * pv; for (n = 0; n < 3; n++) { term1[n] = GME / C / C / r / r / r * ( a * p[n] + b * v[n] ); term2[n] = GME / C / C / r / r / r * (1 + gamma) * ( 3/r/r * pxv[n] * pJ + vxJ[n] ); term3[n] = - GMS / C / C / rs / rs / rs * (1 + 2 * gamma) * vsxpsxv[n]; fgr[n] = term1[n] + term2[n] + term3[n]; } return 0; } double kbrvel2pos (int i) { int n, iter; double rou, rp[3], rv[3], rvp[3], rvpv[3], pos, vel, rpnew[3], ev[3],evt[3]; for (n = 0; n < 3; n ++) { rp[n] = sat12[i].rp[n]; rv[n] = sat12[i].rv[n]; } iter = 0; while(1) { iter ++; crsvect(rv, rp, rvp); crsvect(rvp, rv, rvpv); pos = modvect(rp); vel = modvect(rv); if (kbrx[i].rate != 0) rou = sat12[i].rate * pos / vel; else rou = dotvect(rp, rv) / vel; for (n = 0; n < 3; n++) { evt[n] = rvpv[n] / modvect(rvpv); ev[n] = rv[n] / modvect(rv); } for (n = 0; n < 3; n ++) { rpnew[n] = rou * ev[n] + sqrt(pos * pos - rou * rou) * evt[n]; } // printf ("iter = %d rx = %f ry = %f rz = %f dx = %f dy = %f dz = %f\n", // iter, rp[0], rp[1], rp[2], rp[0] - rpnew[0], rp[1] - rpnew[1], rp[2] - rpnew[2]); if (iter > 1) break; for (n = 0; n < 3; n ++) { rp[n] = rpnew[n]; } } for (n = 0; n < 3; n ++) { sat12[i].rp[n] = rpnew[n]; sat2b[i].rp[n] = sat1a[i].rp[n] + sat12[i].rp[n]; } return 0; } double kbrpos2vel (int i) { int n, iter; double rou, vel, pos, rvnew[3], ep[3], ept[3], rp[3], rv[3], rpv[3], rpvp[3]; rou = sat12[i].rate; for (n = 0; n < 3; n ++) { rp[n] = sat12[i].rp[n]; rv[n] = sat12[i].rv[n]; } iter = 0; while(1) { iter ++; crsvect(rp, rv, rpv); crsvect(rpv, rp, rpvp); // vel = modvect(rv); vel = sat12[i].vel; pos = modvect(rp); for (n = 0; n < 3; n++) { ept[n] = rpvp[n] / modvect(rpvp); ep[n] = rp[n] / modvect(rp); } for (n = 0; n < 3; n ++) { rvnew[n] = rou * ep[n] + sqrt(vel * vel - rou * rou) * ept[n]; } // printf ("iter = %d vx = %f vy = %f vz = %f dvx = %e dvy = %e dvz = %e\n", // iter, rv[0], rv[1], rv[2], rv[0] - rvnew[0], rv[1] - rvnew[1], rv[2] - rvnew[2]); if (iter > 1) break; for (n = 0; n < 3; n ++) { rv[n] = rvnew[n]; } } for (n = 0; n < 3; n ++) { sat12[i].rv[n] = rvnew[n]; sat2b[i].rv[n] = sat1a[i].rv[n] + sat12[i].rv[n]; } return 0; } double stidev (int num, double *llr1, double *vs, double *dvts, double *as) { double gp1, *stcs, dv1, acc1[3], p1e[3], p1[3], p1e_a[3], p1e_b[3], llr1_b[3], llr1_a[3], *stcs_b, gp1_b, *stcs_a, gp1_a; int num_b, num_a, nmax; nmax = 4; stcs = (double *) calloc ( (nmax + 1) * (nmax + 1), sizeof(double)); // id_perm = PERM; // stidecs(num, 1, stcs); // stidecs_Anelastic(num, 1, stcs); stidecs_earth(&info[num], stcs, C20PERM, 1,1,0); // stidecs_Anelastic(&info[num], 1, stcs); cs2acc (num, llr1, stcs, GMA[0], GMA[1], nmax, &gp1, &dv1, acc1); *vs = gp1; as[0] = acc1[0]; as[1] = acc1[1]; as[2] = acc1[2]; if (num != 0) { num_b = num - 1; } else { num_b = 0; } if (num != NDATA - 1) { num_a = num + 1; } else { num_a = NDATA - 1; } stcs_b = (double *) calloc ( (nmax + 1) * (nmax + 1), sizeof(double)); stcs_a = (double *) calloc ( (nmax + 1) * (nmax + 1), sizeof(double)); // stidecs(num_b, id_perm, stcs_b); // stidecs(num_a, id_perm, stcs_a); // stidecs_Anelastic(num_b, 1, stcs_b); // stidecs_Anelastic(num_a, 1, stcs_a); stidecs_earth(&info[num_b], stcs_b, C20PERM, 1,1,0); stidecs_earth(&info[num_a], stcs_a, C20PERM, 1,1,0); // stidecs_Anelastic(&info[num_b], 1, stcs_b); // stidecs_Anelastic(&info[num_a], 1, stcs_a); llr2xyz (llr1, p1e); brmul(info[num].c_ei, p1e, 3, 3, 1, p1); brmul(info[num_b].c_ie, p1, 3, 3, 1, p1e_b); brmul(info[num_a].c_ie, p1, 3, 3, 1, p1e_a); xyz2llr(p1e_b, llr1_b); xyz2llr(p1e_a, llr1_a); cs2acc (num_b, llr1_b, stcs_b, GMA[0], GMA[1], nmax, &gp1_b, &dv1, acc1); cs2acc (num_a, llr1_a, stcs_a, GMA[0], GMA[1], nmax, &gp1_a, &dv1, acc1); *dvts = (gp1_a - gp1_b)/DT/2.0; free(stcs); free(stcs_b); free(stcs_a); return 0; } double getinfo_1day(char *infile) { double jd0, tjd[2]; int mjd0, i; jd0 = GPS_S / 86400.0 + T0; mjd0 = (int)(jd0 - 2400000.5); eop_open(infile, mjd0, mjd0 + 1); for (i = 0; i < NDATA; i++) { tjd[0] = jd0; tjd[1] = gps_GRACE2tt(jd0,sat12[i].t) / 86400.0; // tjd[0] = T0; // tjd[1] = gps2tt(sat12[i].t) / 86400.0; getinfo(tjd, 2, &info[i]); } eop_close(); return 0; } double nbodyv (double *tjd, double *rp, double *vn, double *dvtn, double *an) { double tjd_s[2], tjd_e[2], pte, pts, pt, acc[3], dt; dt = 5.0; nbodypt (tjd, rp, &pt, acc); *vn = pt; an[0] = acc[0]; an[1] = acc[1]; an[2] = acc[2]; tjd_s[0] = tjd[0]; tjd_s[1] = tjd[1] - dt / 86400.0; tjd_e[0] = tjd[0]; tjd_e[1] = tjd[1] + dt / 86400.0; nbodypt (tjd_s, rp, &pts, acc); nbodypt (tjd_e, rp, &pte, acc); *dvtn = (pte - pts) / dt / 2.0; return 0; } double nbodypt (double *tjd, double *pi, double *ptt, double *acc) { double pj[3],vj[3], pij[3],f[3], rij, ri, rj, gm[11], ptt1, ptt2, coszt, zt; short int earth, j, n; gm[0] = 2.203208082807623e+13; gm[1] = 3.248586038641429e+14; gm[2] = 398600.44180E+09; gm[3] = 4.28283719012840e+13; gm[4] = 1.267127698227696e+17; gm[5] = 3.794062664949063e+16; gm[6] = 5.794549096929744e+15; gm[7] = 6.836534169987595e+15; gm[8] = 9.816009029289940e+11; gm[9] = 4.902801056E+12; gm[10] = 1.32712442076e20; earth = 2; ptt1 = 0; ptt2 = 0; f[0] = 0; f[1] = 0; f[2] = 0; for (j = 0; j <= 10; j++) { if (j == earth) continue; planet_ephemeris (tjd, j, earth, pj, vj); for (n = 0; n < 3; n++) { pj[n] = pj[n] * AU; pij[n] = pj[n] - pi[n]; } rij= sqrt(pij[0] * pij[0] + pij[1] * pij[1] + pij[2] * pij[2]); ri = sqrt(pi[0] * pi[0] + pi[1] * pi[1] + pi[2] * pi[2]); rj = sqrt(pj[0] * pj[0] + pj[1] * pj[1] + pj[2] * pj[2]); coszt = (pi[0] * pj[0] + pi[1] * pj[1] + pi[2] * pj[2]) / ri/ rj; zt = acos(coszt); ptt1 = ptt1 + gm[j] * (1 / rij - 1 / rj - 1 / rj / rj * ri * coszt); // ptt1 = ptt1 + gm[j] * (1 / rij); ptt2 = ptt2 + gm[j] * ( + pow(ri,2)/pow(rj,3) * ( 0.75*cos(2.0*zt) + 0.25) + pow(ri,3)/pow(rj,4) * ( 5.0/8.0*cos(3.0*zt) + 3.0/8.0*cos(zt) ) ); for (n = 0; n < 3; n++) f[n] = f[n] + gm[j] / (rij * rij * rij) * pij[n] - gm[j] / (rj * rj * rj) * pj[n]; } *ptt = ptt1; for (n = 0; n < 3; n++) acc[n] = f[n]; return 0; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ double disse_a (double *v1, int i, double *ef1i, double *f1) { double mat1[9], mtt1[9], qvec1[4], acc1[3]; if (scaa[i].gps_time == 0 || scab[i].gps_time == 0) { *ef1i = 0; return 1; } qvec1[0] = scaa[i].quatangle; qvec1[1] = scaa[i].quaticoeff; qvec1[2] = scaa[i].quatjcoeff; qvec1[3] = scaa[i].quatkcoeff; acc1[0] = acca[i].lin_accl_x; acc1[1] = acca[i].lin_accl_y; acc1[2] = acca[i].lin_accl_z; quat2mat_i2s (qvec1, mat1); // brmul(mat1, acc1, 3,3,1, f1); mt(mat1, 3, 3, mtt1); brmul(mtt1, acc1, 3,3,1, f1); *ef1i = (f1[0] * v1[0] + f1[1] * v1[1] + f1[2] * v1[2]); // *ef1i = (f1[0] * v1[0] + f1[1] * v1[1] + f1[2] * v1[2]) * DT; // brmul(mat1, v1, 3, 3, 1, v1s); // *ef1i = (acc1[0] * v1s[0] + acc1[1] * v1s[1] + acc1[2] * v1s[2]) * DT; return 0; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ double disse_b (double *v1, int i, double *ef1i, double *f1) { double mat1[9], mtt1[9], qvec1[4], acc1[3]; if (scaa[i].gps_time == 0 || scab[i].gps_time == 0) { *ef1i = 0; return 1; } qvec1[0] = scab[i].quatangle; qvec1[1] = scab[i].quaticoeff; qvec1[2] = scab[i].quatjcoeff; qvec1[3] = scab[i].quatkcoeff; acc1[0] = accb[i].lin_accl_x; acc1[1] = accb[i].lin_accl_y; acc1[2] = accb[i].lin_accl_z; quat2mat_i2s (qvec1, mat1); // brmul(mat1, acc1, 3,3,1, f1); mt(mat1, 3, 3, mtt1); brmul(mtt1, acc1, 3,3,1, f1); *ef1i = (f1[0] * v1[0] + f1[1] * v1[1] + f1[2] * v1[2]); // *ef1i = (f1[0] * v1[0] + f1[1] * v1[1] + f1[2] * v1[2]) * DT; // brmul(mat1, v1, 3, 3, 1, v1s); // *ef1i = (acc1[0] * v1s[0] + acc1[1] * v1s[1] + acc1[2] * v1s[2]) * DT; return 0; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ double accia (double *tjd, int label, double *acc) { double tt, as[3], qvec[4], c_is[9], c_si[9]; tt = tjd[1] * 86400.0; if (label == 1) { // lagrangelow (ACA_EPH, DIM_ACA, 4, tt, as); // lagrangelow (SCA_EPH, DIM_SCA, 5, tt, qvec); lgr_order (ACA_EPH, DIM_ACA, 4, tt, as, 4); lgr_order (SCA_EPH, DIM_SCA, 5, tt, qvec, 4); } if (label == 2) { // lagrangelow (ACB_EPH, DIM_ACB, 4, tt, as); // lagrangelow (SCB_EPH, DIM_SCB, 5, tt, qvec); lgr_order (ACB_EPH, DIM_ACB, 4, tt, as, 4); lgr_order (SCB_EPH, DIM_SCB, 5, tt, qvec, 4); } quat2mat_i2s (qvec, c_is); mt(c_is, 3, 3, c_si); brmul(c_si, as, 3,3,1, acc); return 0; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ double quat2mat_i2s (double *qvec, double *mat) /* * SCA_1B data file containing edited quaternion * rotating inertial frame to SRF (5-sec data interval) * Page 17 in * Algorithm Theoretical Basis Document for GRACE Level-1B Data Processing V1.2 * Sien-Chong Wu Gerhard Kruizinga Willy Bertiger * May 9, 2006 */ { double q[4]; q[0]=qvec[0]; q[1]=qvec[1]; q[2]=qvec[2]; q[3]=qvec[3]; mat[0] = q[0] * q[0] + q[1] * q[1] - q[2] * q[2] - q[3] * q[3]; mat[1] = 2.0 * (q[1]*q[2] + q[3]*q[0]); mat[2] = 2.0 * (q[1]*q[3] - q[2]*q[0]); mat[3] = 2.0 * (q[1]*q[2] - q[3]*q[0]); mat[4] = q[0] * q[0] + q[2] * q[2] - q[1] * q[1] - q[3] * q[3]; mat[5] = 2.0 * (q[2]*q[3] + q[0]*q[1]); mat[6] = 2.0 * (q[1]*q[3] + q[2]*q[0]); mat[7] = 2.0 * (q[2]*q[3] - q[0]*q[1]); mat[8] = q[0] * q[0] + q[3] * q[3] - q[1] * q[1] - q[2] * q[2]; return 0; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ void fitl1c_mv (int nply, int ncpr, int nplycpr, int ndt) { int np, np2, is, ie, i, n, j, nlsf; double t0, x, *xlsf, *ylsf, *prd, tpmean; t0 = sat12[0].t; np = (int)(ndt / DT); np2 = (int) (np/2); xlsf = (double *) calloc ( np, sizeof(double)); ylsf = (double *) calloc ( np, sizeof(double)); prd = (double *) calloc ( np, sizeof(double)); for (i = 0; i < NDATA; i ++) { t0 = sat12[i].t; x = (sat12[i].t - t0) / 86400.0; is = i - np2; ie = i + np2 - 1; if (is < 0) { is = 0; ie = np - 1; } if (ie > NDATA - 1) { ie = NDATA - 1; is = NDATA - np; } n = 0; for (j = is; j <= ie; j ++) { if (sat12[j].error == 9) continue; xlsf[n] = (sat12[j].t - t0) / 86400.0; ylsf[n] = sat12[j].vl1c; ylsf[n] = ylsf[n] - sat12[j].vref; ///////////////!!!!!!!!!!!////////// // prd[n] = (gnva[i].Tp + gnvb[i].Tp) / 2.0; prd[n] = (gnva[j].Tp + gnvb[j].Tp) / 2.0; n ++; } if (n < np2) { sat12[i].vmvfit = 0; sat12[i].vmvfitres = 999; continue; } nlsf = n; tpmean = mean (prd, nlsf); sat12[i].Tp2 = tpmean; // printf ("n = %d\t i = %d\t tpmean = %f\n", n, i, tpmean); sat12[i].vmvfitres = lsfl1c1d (&x, xlsf, ylsf, 1, nlsf, tpmean, &sat12[i].vmvfit, nply, ncpr, nplycpr); // sat12[i].ystd = fabs(sat12[i].res - sat12[i].y - (sat12[i].vcsr + sat12[i].vgfz + sat12[i].vjpl - 3 * sat12[i].vbl) / 3.0); } return; } void fitlos_mv (int nply, int ncpr, int nplycpr, int ndt) { int np, np2, is, ie, i, n, j, nlsf; double t0, x, *xlsf, *ylsf, *prd, tpmean; t0 = sat12[0].t; np = (int)(ndt / DT); np2 = (int) (np/2); xlsf = (double *) calloc ( np, sizeof(double)); ylsf = (double *) calloc ( np, sizeof(double)); prd = (double *) calloc ( np, sizeof(double)); for (i = 0; i < NDATA; i ++) { x = (sat12[i].t - t0) / 86400.0; is = i - np2; ie = i + np2 - 1; if (is < 0) { is = 0; ie = np - 1; } if (ie > NDATA - 1) { ie = NDATA - 1; is = NDATA - np; } n = 0; for (j = is; j <= ie; j ++) { if (sat12[j].error == 9) continue; xlsf[n] = (sat12[j].t - t0) / 86400.0; ylsf[n] = sat12[j].glos; ylsf[n] = ylsf[n] - sat12[j].gref; ///////////////!!!!!!!!!!!////////// // prd[n] = (gnva[i].Tp + gnvb[i].Tp) / 2.0; prd[n] = (gnva[j].Tp + gnvb[j].Tp) / 2.0; n ++; } if (n < np2) { sat12[i].gmvfit = 0; sat12[i].gmvfitres = 999; continue; } nlsf = n; tpmean = mean (prd, nlsf); sat12[i].gmvfitres = lsfl1c1d (&x, xlsf, ylsf, 1, nlsf, tpmean, &sat12[i].gmvfit, nply, ncpr, nplycpr); // sat12[i].ystd = fabs(sat12[i].res - sat12[i].y - (sat12[i].vcsr + sat12[i].vgfz + sat12[i].vjpl - 3 * sat12[i].vbl) / 3.0); } return; } void fitl1c_pw (int order_poly, int order_cpr) { int i, n, in, nmax; double *xn, *xi, *res, *resm, *prd, *fit, *fitm, tpmean, t0, stdres, stdresm; nmax = 5400/DT; // nmax = 3600/DT; xn = (double *) calloc ( nmax, sizeof(double)); res = (double *) calloc ( nmax, sizeof(double)); resm = (double *) calloc ( nmax, sizeof(double)); prd = (double *) calloc ( nmax, sizeof(double)); fit = (double *) calloc ( nmax, sizeof(double)); fitm = (double *) calloc ( nmax, sizeof(double)); xi = (double *) calloc ( nmax, sizeof(double)); n = 0; t0 = sat12[0].t; for (i = 0; i < NDATA; i ++) { // t0 = sat12[i].t; if (sat12[i].error == 0) { xn[n] = (sat12[i].t - t0) / 86400.0; prd[n] = (gnva[i].Tp + gnvb[i].Tp) / 2.0; res[n] = sat12[i].vl1c; res[n] = res[n] - sat12[i].vref; ///////////////!!!!!!!!!!!////////// resm[n] = sat12[i].vl1cm; n++; } xi[(i)%nmax] = (sat12[i].t - t0) / 86400.0; if (i == 0) continue; if (((i+1)%(5400/DT)) == 0) // possible useful for GPS orbit (orbit cut at 86399s) // if (((i)%(5400/DT)) == 0) { if (n < nmax / 2) { for (in = 0; in < nmax; in ++) { sat12[i - (nmax-1) + in].vpwfit = 0; // sat12[i - (nmax-1) + in].error = 3; } t0 = sat12[i+1].t; n = 0; continue; } tpmean = mean (prd, n); // tpmean = 5633.5; // printf ("n = %d\t i = %d\t tpmean = %f\n", n, i, tpmean); stdres = lsf_cpr_new (xi, xn, res, nmax, n, tpmean, fit, order_poly, order_cpr); stdresm =lsf_cpr_new (xi, xn, resm, nmax, n, tpmean, fitm, order_poly, order_cpr); // printf ("n = %d\t i = %d\t tpmean = %f\t, stdres = %f\n", n, i, tpmean, stdres); for (in = 0; in < nmax; in ++) { sat12[i - (nmax-1) + in].vpwfit = fit[in]; // possible useful for GPS orbit sat12[i - (nmax-1) + in].vpwfitm = fitm[in]; // possible useful for GPS orbit sat12[i - (nmax-1) + in].vpwfitres = stdres; sat12[i - (nmax-1) + in].Tp1 = tpmean; // if (stdres > 0.003) // sat12[i - (nmax-1) + in].error = 2; // sat12[i - nmax + in].fit = fit[in]; } t0 = sat12[i+1].t; n = 0; } } free(xi); free(xn); free(res); free(resm); free(prd); free(fit); free(fitm); } void fitlos_pw (int order_poly, int order_cpr) { int i, n, in, nmax; double *xn, *xi, *res, *resm, *prd, *fit, *fitm, tpmean, t0, stdres; nmax = 5400/DT; // nmax = 3600/DT; xn = (double *) calloc ( nmax, sizeof(double)); res = (double *) calloc ( nmax, sizeof(double)); resm = (double *) calloc ( nmax, sizeof(double)); prd = (double *) calloc ( nmax, sizeof(double)); fit = (double *) calloc ( nmax, sizeof(double)); fitm = (double *) calloc ( nmax, sizeof(double)); xi = (double *) calloc ( nmax, sizeof(double)); n = 0; t0 = sat12[0].t; for (i = 0; i < NDATA; i ++) { if (sat12[i].error == 0) { xn[n] = (sat12[i].t - t0) / 86400.0; prd[n] = (gnva[i].Tp + gnvb[i].Tp) / 2.0; res[n] = sat12[i].glos; res[n] = res[n] - sat12[i].gref; ///////////////!!!!!!!!!!!////////// // resm[n] = sat12[i].resm; n++; } xi[(i)%nmax] = (sat12[i].t - t0) / 86400.0; if (i == 0) continue; if (((i+1)%(5400/DT)) == 0) // possible useful for GPS orbit (orbit cut at 86399s) // if (((i)%(5400/DT)) == 0) { if (n < nmax / 2) { for (in = 0; in < nmax; in ++) { sat12[i - (nmax-1) + in].gpwfit = 0; // sat12[i - (nmax-1) + in].error = 3; } t0 = sat12[i+1].t; n = 0; continue; } tpmean = mean (prd, n); // printf ("n = %d\t i = %d\t tpmean = %f\n", n, i, tpmean); stdres = lsf_cpr_new (xi, xn, res, nmax, n, tpmean, fit, order_poly, order_cpr); // stdresm =lsf_cpr_new (xi, xn, resm, nmax, n, tpmean, fitm, order_poly, order_cpr); // printf ("n = %d\t i = %d\t tpmean = %f\t, stdres = %f\n", n, i, tpmean, stdres); for (in = 0; in < nmax; in ++) { sat12[i - (nmax-1) + in].gpwfit = fit[in]; // possible useful for GPS orbit // sat12[i - (nmax-1) + in].fitm = fitm[in]; // possible useful for GPS orbit sat12[i - (nmax-1) + in].gpwfitres = stdres; // if (stdres > 0.003) // sat12[i - (nmax-1) + in].error = 2; // sat12[i - nmax + in].fit = fit[in]; } t0 = sat12[i+1].t; n = 0; } } free(xi); free(xn); free(res); free(resm); free(prd); free(fit); free(fitm); } void fitres_new_overlap (int order_poly, int order_cpr, int overlap) { int i, n, in, nmax; double *xn, *xi, *res, *resm, *prd, *fit, *fitm, tpmean, t0, stdres, stdresm; nmax = 5400/DT; xn = (double *) calloc ( nmax, sizeof(double)); res = (double *) calloc ( nmax, sizeof(double)); resm = (double *) calloc ( nmax, sizeof(double)); prd = (double *) calloc ( nmax, sizeof(double)); fit = (double *) calloc ( nmax, sizeof(double)); fitm = (double *) calloc ( nmax, sizeof(double)); xi = (double *) calloc ( nmax, sizeof(double)); n = 0; t0 = sat12[0].t; for (i = 0; i < NDATA; i ++) { if (sat12[i].error == 0) { xn[n] = (sat12[i].t - t0) / 86400.0; prd[n] = (gnva[i].Tp + gnvb[i].Tp) / 2.0; res[n] = sat12[i].vl1c; resm[n] = sat12[i].vl1cm; n++; } xi[(i)%nmax] = (sat12[i].t - t0) / 86400.0; if (i == 0) continue; if (((i+1)%(5400/DT)) == 0) // possible useful for GPS orbit (orbit cut at 86399s) // if (((i)%(5400/DT)) == 0) { if (n < nmax / 2) { for (in = 0; in < nmax; in ++) { sat12[i - (nmax-1) + in].vpwfit = 0; sat12[i - (nmax-1) + in].error = 3; } t0 = sat12[i+1].t; n = 0; continue; } tpmean = mean (prd, n); // printf ("n = %d\t i = %d\t tpmean = %f\n", n, i, tpmean); stdres = lsf_cpr_new (xi, xn, res, nmax, n, tpmean, fit, order_poly, order_cpr); stdresm =lsf_cpr_new (xi, xn, resm, nmax, n, tpmean, fitm, order_poly, order_cpr); // printf ("n = %d\t i = %d\t tpmean = %f\t, stdres = %f\n", n, i, tpmean, stdres); for (in = 0; in < nmax; in ++) { sat12[i - (nmax-1) + in].vpwfit = fit[in]; // possible useful for GPS orbit sat12[i - (nmax-1) + in].vpwfitm = fitm[in]; // possible useful for GPS orbit if (stdres > 0.003) sat12[i - (nmax-1) + in].error = 2; // sat12[i - nmax + in].fit = fit[in]; } t0 = sat12[i+1].t; n = 0; } } free(xi); free(xn); free(res); free(resm); free(prd); free(fit); free(fitm); } void fitres (int order_poly, int order_cpr, int offsetcyc) { int i, is, ie, n, cnum, ofs, ofe, offset; double *xt, *res, *prd, *fit, tpmean; // offset = 5400/DT; offset = offsetcyc; is = 0; for (i = 0; i < NDATA; i ++) { if (i == 0 || gnva[i].r == 0) continue; // if ( ((gnva[i+1].lat > gnva[i].lat) && (gnva[i-1].lat > gnva[i].lat)) if ( ((i%(5400/DT)) == 0) || i == NDATA - 1) { ie = i + 1; cnum = ie - is; if (is - offset < 0) { ofs = 0; ofe = offset * 2; } else if (ie + offset >=NDATA) { ofs = offset * 2; ofe = 0; } else { ofs = offset; ofe = offset; } xt = (double *) calloc ( cnum + offset * 2, sizeof(double)); res = (double *) calloc ( cnum + offset * 2, sizeof(double)); prd = (double *) calloc ( cnum + offset * 2, sizeof(double)); fit = (double *) calloc ( cnum + offset * 2, sizeof(double)); for (n = 0; n < cnum + offset * 2; n ++) { xt[n] = (gnva[is - ofs + n].gps_time - gnva[is].gps_time) / 86400.0; prd[n] = gnva[is - ofs + n].Tp; res[n] = sat12[is - ofs + n].vl1c; } tpmean = mean (prd, cnum + offset * 2); // tpmean = 5633.13; // printf ("cnum = %d\t is = %d\t ie = %d\t tpmean = %f\n", cnum, is, ie, tpmean); lsf_cpr (xt, res, cnum + offset * 2, tpmean, fit, order_poly, order_cpr); // lsf_cpr_day (xt, res, cnum + offset * 2, tpmean, fit, order_poly, order_cpr); for (n = 0; n < cnum; n ++) { sat12[is + n].vpwfit = fit[n + ofs]; } free(xt); free(res); free(prd); free(fit); is = ie; } } } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ int calbias(char *infile_a, char *infile_b) { double x0a, y0a, z0a, x0b, y0b, z0b; FILE *fpACC_a, *fpACC_b; int i; char line[MAXLINE]; /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ if ( (fpACC_a = fopen (infile_a,"r")) == NULL) { printf ("Cannot open fpin_a file!\n"); //getch(); exit (0); } if ( (fpACC_b = fopen (infile_b,"r")) == NULL) { printf ("Cannot open fpin_b file!\n"); //getch(); exit (0); } fgets(line, 100, fpACC_a); sscanf (line, "%lf", &x0a); fgets(line, 100, fpACC_a); sscanf (line, "%lf", &y0a); fgets(line, 100, fpACC_a); sscanf (line, "%lf", &z0a); fgets(line, 100, fpACC_b); sscanf (line, "%lf", &x0b); fgets(line, 100, fpACC_b); sscanf (line, "%lf", &y0b); fgets(line, 100, fpACC_b); sscanf (line, "%lf", &z0b); // printf ("%e\n%e\n%e\n%e\n%e\n%e\n", x0a, y0a, z0a, x0b, y0b, z0b); for (i = 0; i < DIM_ACA; i++) { ACA_EPH[i * 4 + 1] = ACA_EPH[i * 4 + 1] + x0a; ACA_EPH[i * 4 + 2] = ACA_EPH[i * 4 + 2] + y0a; ACA_EPH[i * 4 + 3] = ACA_EPH[i * 4 + 3] + z0a; } for (i = 0; i < DIM_ACB; i++) { ACB_EPH[i * 4 + 1] = ACB_EPH[i * 4 + 1] + x0b; ACB_EPH[i * 4 + 2] = ACB_EPH[i * 4 + 2] + y0b; ACB_EPH[i * 4 + 3] = ACB_EPH[i * 4 + 3] + z0b; } return 0; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ int calbiaseph(char *infile_a, char *infile_b) { double *MACC_EPBS = NULL, *MACC_EPSL = NULL, tt; FILE *fpACC_A, *fpACC_B; int i,k,m,n, lbs, lsl, MACC_ARBS = 0, MACC_ARSL = 0, MACC_NOBS = 0, MACC_NOSL = 0, MACC_PRBS = 0, MACC_PRSL = 0; // char line[MAXLINE]; /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ if ( (fpACC_A = fopen (infile_a,"r")) == NULL) { printf ("Cannot open fpin_a file!\n"); //getch(); exit (0); } if ( (fpACC_B = fopen (infile_b,"r")) == NULL) { printf ("Cannot open fpin_b file!\n"); //getch(); exit (0); } if (MACC_BIAS != 0) { MACC_ARBS = (int)(86400 / MACC_DTBS); MACC_NOBS = 3 * MACC_BIAS; MACC_PRBS = MACC_NOBS * MACC_ARBS; MACC_EPBS = (double *) calloc (MACC_PRBS, sizeof(double)); } if (MACC_SCAL != 0) { MACC_ARSL = (int)(86400 / MACC_DTSL); MACC_NOSL = 3 * MACC_SCAL; MACC_PRSL = MACC_NOSL * MACC_ARSL; MACC_EPSL = (double *) calloc (MACC_PRSL, sizeof(double)); } /*A*/ if (MACC_BIAS != 0) { for (i = 0; i < MACC_ARBS; i ++) { fscanf (fpACC_A, "%*s%*d"); for (n = 0; n < MACC_NOBS; n++) { fscanf(fpACC_A, "%lf", &MACC_EPBS[i * MACC_NOBS + n]); } } } if (MACC_SCAL != 0) { for (i = 0; i < MACC_ARSL; i ++) { fscanf (fpACC_A, "%*s%*d"); for (n = 0; n < MACC_NOSL; n++) { fscanf(fpACC_A, "%lf", &MACC_EPSL[i * MACC_NOSL + n]); } } } for (i = 0; i < DIM_ACA; i++) { tt = ACA_EPH[i * 4] / 86400.0; // tt = ( ACA_EPH[i * 4] - 51.184) / 86400.0; if (MACC_SCAL != 0) { lsl = (int)((ACA_EPH[i * 4] - 51.184)/MACC_DTSL); if (lsl < 0) lsl = 0; if (lsl > MACC_ARSL - 1) lsl = MACC_ARSL - 1; for (k = 0; k < 3; k ++) { ACA_EPH[i * 4 + k + 1] = ACA_EPH[i * 4 + k + 1] * MACC_EPSL[lsl * MACC_NOSL + k]; } } if (MACC_BIAS != 0) { lbs = (int)((ACA_EPH[i * 4] - 51.184)/MACC_DTBS); if (lbs < 0) lbs = 0; if (lbs > MACC_ARBS - 1) lbs = MACC_ARBS - 1; for (k = 0; k < 3; k ++) { for (m = 0; m < MACC_BIAS; m ++) { ACA_EPH[i * 4 + k + 1] = ACA_EPH[i * 4 + k + 1] + MACC_EPBS[lbs * MACC_NOBS + k + 3 * m] * pow (tt, m); } } } } /*B*/ if (MACC_BIAS != 0) { for (i = 0; i < MACC_ARBS; i ++) { fscanf (fpACC_B, "%*s%*d"); for (n = 0; n < MACC_NOBS; n++) { fscanf(fpACC_B, "%lf", &MACC_EPBS[i * MACC_NOBS + n]); } } } if (MACC_SCAL != 0) { for (i = 0; i < MACC_ARSL; i ++) { fscanf (fpACC_B, "%*s%*d"); for (n = 0; n < MACC_NOSL; n++) { fscanf(fpACC_B, "%lf", &MACC_EPSL[i * MACC_NOSL + n]); } } } for (i = 0; i < DIM_ACB; i++) { tt = ACB_EPH[i * 4] / 86400.0; if (MACC_SCAL != 0) { lsl = (int)((ACB_EPH[i * 4] - 19 - 32.184)/MACC_DTSL); if (lsl < 0) lsl = 0; if (lsl > MACC_ARSL - 1) lsl = MACC_ARSL - 1; for (k = 0; k < 3; k ++) { ACB_EPH[i * 4 + k + 1] = ACB_EPH[i * 4 + k + 1] * MACC_EPSL[lsl * MACC_NOSL + k]; } } if (MACC_BIAS != 0) { lbs = (int)((ACB_EPH[i * 4] - 19 - 32.184)/MACC_DTBS); if (lbs < 0) lbs = 0; if (lbs > MACC_ARBS - 1) lbs = MACC_ARBS - 1; for (k = 0; k < 3; k ++) { for (m = 0; m < MACC_BIAS; m ++) { ACB_EPH[i * 4 + k + 1] = ACB_EPH[i * 4 + k + 1] + MACC_EPBS[lbs * MACC_NOBS + k + 3 * m] * pow (tt, m); } } } } if (MACC_BIAS != 0) free (MACC_EPBS); if (MACC_SCAL != 0) free (MACC_EPSL); fclose (fpACC_A); fclose (fpACC_B); return 0; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ double cal_acc_01(void) { double scale_x_A, scale_y_A, scale_z_A, scale_x_B, scale_y_B, scale_z_B, bias_x_A, bias_y_A, bias_z_A, bias_x_B, bias_y_B, bias_z_B, mjd, mjd0, mjdm, gps, gpss, mjds; int i; scale_x_A = 0.9595; scale_y_A = 0.9797; scale_z_A = 0.9485; scale_x_B = 0.9465; scale_y_B = 0.9842; scale_z_B = 0.9303; gpss = ACA_EPH[0] + GPS_S - 19 - 32.184; mjds = gpss / 86400.0 + T0 - 2400000.5; if (mjds > 55562) // Jan. 1, 2011 { scale_x_A = scale_x_A * 0.98; scale_z_A = scale_z_A * 0.98; scale_x_B = scale_x_B * 0.98; scale_z_B = scale_z_B * 0.98; } mjdm = 52705; //March 7, 2003 for (i = 0; i < DIM_ACA; i++) { gps = ACA_EPH[i * 4] + GPS_S - 19 - 32.184; mjd = gps / 86400.0 + T0 - 2400000.5; if ( mjd < mjdm) { mjd0 = 52532; bias_x_A = - 1.106 + 2.233e-4 * ( mjd - mjd0 ) + 2.5e-7 * ( mjd - mjd0 ) * ( mjd - mjd0 ); bias_y_A = 27.042 + 4.46e-3 * ( mjd - mjd0 ) + 1.1e-6 * ( mjd - mjd0 ) * ( mjd - mjd0 ); bias_z_A = - 0.5486 - 1.139e-6 * ( mjd - mjd0 ) + 1.7e-7 * ( mjd - mjd0 ) * ( mjd - mjd0 ); } else { mjd0 = 53736; bias_x_A = - 1.2095 - 4.128e-5 * ( mjd - mjd0 ) + 9.7e-9 * ( mjd - mjd0 ) * ( mjd - mjd0 ); bias_y_A = 29.3370 + 6.515e-4 * ( mjd - mjd0 ) - 3.9e-7 * ( mjd - mjd0 ) * ( mjd - mjd0 ); bias_z_A = - 0.5606 - 2.352e-6 * ( mjd - mjd0 ) + 3.8e-9 * ( mjd - mjd0 ) * ( mjd - mjd0 ); } ACA_EPH[i * 4 + 1] = bias_x_A * 1e-6 + scale_x_A * ACA_EPH[i * 4 + 1]; ACA_EPH[i * 4 + 2] = bias_y_A * 1e-6 + scale_y_A * ACA_EPH[i * 4 + 2]; ACA_EPH[i * 4 + 3] = bias_z_A * 1e-6 + scale_z_A * ACA_EPH[i * 4 + 3]; } for (i = 0; i < DIM_ACB; i++) { gps = ACA_EPH[i * 4] + GPS_S - 19 - 32.184; mjd = gps / 86400.0 + T0 - 2400000.5; if ( mjd < mjdm) { mjd0 = 52532; bias_x_B = - 0.5647 - 7.788e-5 * ( mjd - mjd0 ) + 2.4E-7 * ( mjd - mjd0 ) * ( mjd - mjd0 ); bias_y_B = 7.5101 + 7.495E-3 * ( mjd - mjd0 ) - 9.6E-6 * ( mjd - mjd0 ) * ( mjd - mjd0 ); bias_z_B = - 0.8602 + 1.399E-4 * ( mjd - mjd0 ) + 2.5E-7 * ( mjd - mjd0 ) * ( mjd - mjd0 ); } else { mjd0 = 53736; bias_x_B = - 0.6049 - 1.982E-5 * ( mjd - mjd0 ) + 3.5E-9 * ( mjd - mjd0 ) * ( mjd - mjd0 ); bias_y_B = 10.6860 + 1.159E-3 * ( mjd - mjd0 ) - 4.3E-7 * ( mjd - mjd0 ) * ( mjd - mjd0 ); bias_z_B = - 0.7901 + 4.783E-5 * ( mjd - mjd0 ) - 6.5E-9 * ( mjd - mjd0 ) * ( mjd - mjd0 ); } ACB_EPH[i * 4 + 1] = bias_x_B * 1e-6 + scale_x_B * ACB_EPH[i * 4 + 1]; ACB_EPH[i * 4 + 2] = bias_y_B * 1e-6 + scale_y_B * ACB_EPH[i * 4 + 2]; ACB_EPH[i * 4 + 3] = bias_z_B * 1e-6 + scale_z_B * ACB_EPH[i * 4 + 3]; } return 0; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ int readgnv (char *infile_a, char *infile_b, int *n_a, int *n_b) { FILE *fpGNV_a, *fpGNV_b; int n_gnva, n_gnvb, i, gps_i; char line[MAXLINE]; /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ if ( (fpGNV_a = fopen (infile_a,"r")) == NULL) { printf ("Cannot open fpin_a file!\n"); ////getch(); exit (0); } if ( (fpGNV_b = fopen (infile_b,"r")) == NULL) { printf ("Cannot open fpin_b file!\n"); ////getch(); exit (0); } n_gnva = 0; while (1) { if (fgets(line,MAXLINE, fpGNV_a) ==NULL) break; n_gnva ++; sscanf (line, "%d", &gps_i); // printf ("%d \t %d \t %d \n", GPS_S, gps_i, DT); if ((gps_i - GPS_S) % DT == 0 && (gps_i - GPS_S) / DT < NDATA) { i = (gps_i - GPS_S) / DT; sscanf (line, "%d%s%s%lf%lf%lf%lf%lf%lf%lf", &gnva[i].gps_time, &gnva[i].GRACE_id, &gnva[i].coord_ref, &gnva[i].xpos, &gnva[i].ypos, &gnva[i].zpos, &gnva[i].xvel, &gnva[i].yvel, &gnva[i].zvel, &gnva[i].r); gnva[i].pos[0] = gnva[i].xpos; gnva[i].pos[1] = gnva[i].ypos; gnva[i].pos[2] = gnva[i].zpos; gnva[i].vel[0] = gnva[i].xvel; gnva[i].vel[1] = gnva[i].yvel; gnva[i].vel[2] = gnva[i].zvel; gnva[i].Tp = xyz2aei(gnva[i].pos, gnva[i].vel,GMA[0], gnva[i].ele); // printf ("%f\n", gnva[i].Tp); } } n_gnvb = 0; while (1) { if (fgets(line,MAXLINE, fpGNV_b) ==NULL) break; n_gnvb ++; sscanf (line, "%d", &gps_i); if ((gps_i - GPS_S) % DT == 0 && (gps_i - GPS_S) / DT < NDATA) { i = (gps_i - GPS_S) / DT; sscanf (line, "%d%s%s%lf%lf%lf%lf%lf%lf%lf", &gnvb[i].gps_time, &gnvb[i].GRACE_id, &gnvb[i].coord_ref, &gnvb[i].xpos, &gnvb[i].ypos, &gnvb[i].zpos, &gnvb[i].xvel, &gnvb[i].yvel, &gnvb[i].zvel, &gnvb[i].r); gnvb[i].pos[0] = gnvb[i].xpos; gnvb[i].pos[1] = gnvb[i].ypos; gnvb[i].pos[2] = gnvb[i].zpos; gnvb[i].vel[0] = gnvb[i].xvel; gnvb[i].vel[1] = gnvb[i].yvel; gnvb[i].vel[2] = gnvb[i].zvel; gnvb[i].Tp = xyz2aei(gnvb[i].pos, gnvb[i].vel,GMA[0], gnvb[i].ele); // printf ("%f\n", gnvb[i].Tp); } } fclose(fpGNV_a); fclose(fpGNV_b); *n_a = n_gnva; *n_b = n_gnvb; return 0; } int readkbr (char *infile, int *n) { FILE *fpKBR; int i = 0, n_kbr, gps_i; char line[MAXLINE]; /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ if ( (fpKBR = fopen (infile,"r")) == NULL) { printf ("Cannot open fpKBR file!\n"); ////getch(); exit (0); } n_kbr = 0; while (1) { if (fgets(line,MAXLINE, fpKBR) ==NULL) break; n_kbr ++; sscanf (line, "%d", &gps_i); if ((gps_i - GPS_S) % DT == 0 && (gps_i - GPS_S) / DT < NDATA) { i = (gps_i - GPS_S) / DT; sscanf (line, "%d%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%d%d%d%d%d", &kbrx[i].gps_time, &kbrx[i].biased_range, &kbrx[i].range_rate, &kbrx[i].range_accl, &kbrx[i].iono_corr, &kbrx[i].lighttime_corr, &kbrx[i].lighttime_rate, &kbrx[i].lighttime_accl, &kbrx[i].ant_centr_corr, &kbrx[i].ant_centr_rate, &kbrx[i].ant_centr_accl, &kbrx[i].K_A_SNR, &kbrx[i].Ka_A_SNR, &kbrx[i].K_B_SNR, &kbrx[i].Ka_B_SNR, &kbrx[i].qualflg); } kbrx[i].range = kbrx[i].biased_range + kbrx[i].lighttime_corr + kbrx[i].ant_centr_corr; kbrx[i].rate = kbrx[i].range_rate + kbrx[i].lighttime_rate + kbrx[i].ant_centr_rate; kbrx[i].accl = kbrx[i].range_accl + kbrx[i].lighttime_accl + kbrx[i].ant_centr_accl; } fclose(fpKBR); *n = n_kbr; return 0; } int readacc (char *infile_a, char *infile_b) { FILE *fpACC_a, *fpACC_b; int i, gps; char line[MAXLINE]; /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ if ( (fpACC_a = fopen (infile_a,"r")) == NULL) { printf ("Cannot open fpin_a file!\n"); //getch(); exit (0); } if ( (fpACC_b = fopen (infile_b,"r")) == NULL) { printf ("Cannot open fpin_b file!\n"); //getch(); exit (0); } i = 0; while (1) { if (fgets(line,MAXLINE, fpACC_a) ==NULL) break; // sscanf (line, "%d%*s%lf%lf%lf", sscanf (line, "%d%lf%lf%lf", &gps, &ACA_EPH[i * 4 + 1], &ACA_EPH[i * 4 + 2], &ACA_EPH[i * 4 + 3]); ACA_EPH[i * 4] = gps - GPS_S + 19 + 32.184; i++; } DIM_ACA = i; i = 0; while (1) { if (fgets(line,MAXLINE, fpACC_b) ==NULL) break; // sscanf (line, "%d%*s%lf%lf%lf", sscanf (line, "%d%lf%lf%lf", &gps, &ACB_EPH[i * 4 + 1], &ACB_EPH[i * 4 + 2], &ACB_EPH[i * 4 + 3]); ACB_EPH[i * 4] = gps - GPS_S + 19 + 32.184; i++; } DIM_ACB = i; fclose(fpACC_a); fclose(fpACC_b); return 0; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ int readsca (char *infile_a, char *infile_b) { FILE *fpSCA_a, *fpSCA_b; int i, gps; char line[MAXLINE]; /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ if ( (fpSCA_a = fopen (infile_a,"r")) == NULL) { printf ("Cannot open fpin_a file!\n"); //getch(); exit (0); } if ( (fpSCA_b = fopen (infile_b,"r")) == NULL) { printf ("Cannot open fpin_b file!\n"); //getch(); exit (0); } i = 0; while (1) { if (fgets(line,MAXLINE, fpSCA_a) ==NULL) break; // sscanf (line, "%d%*s%*d%lf%lf%lf%lf", sscanf (line, "%d%lf%lf%lf%lf", &gps, &SCA_EPH[i * 5 + 1], &SCA_EPH[i * 5 + 2], &SCA_EPH[i * 5 + 3], &SCA_EPH[i * 5 + 4]); SCA_EPH[i * 5] = gps - GPS_S + 19 + 32.184; i++; } DIM_SCA = i; i = 0; while (1) { if (fgets(line,MAXLINE, fpSCA_b) ==NULL) break; // sscanf (line, "%d%*s%*d%lf%lf%lf%lf", sscanf (line, "%d%lf%lf%lf%lf", &gps, &SCB_EPH[i * 5 + 1], &SCB_EPH[i * 5 + 2], &SCB_EPH[i * 5 + 3], &SCB_EPH[i * 5 + 4]); SCB_EPH[i * 5] = gps - GPS_S + 19 + 32.184; i++; } DIM_SCB = i; fclose(fpSCA_a); fclose(fpSCA_b); return 0; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ /* */ /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ double cs2acc (int num, double *llr, double *cs, double gm, double a, int nmax, double *v, double *dvdt, double *acc) { int n, m, k, l, ind; double a2r, sinf, cosf, sinlon, coslon, sincolat, coscolat, *cosml, *sinml, *aprn, *pbar, *pbar1, *pbar2, accn[3], c_en[9], c_in[9], *pt, *ptt, lat, lon, r, vi, dvdr, dvdcolat, dvdlon, t; /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ lat = llr[0]; lon = llr[1]; r = llr[2]; sinf = sin(lat * DEG2RAD); cosf = cos(lat * DEG2RAD); sinlon = sin(lon * DEG2RAD); coslon = cos(lon * DEG2RAD); sincolat = cosf; coscolat = sinf; // #pragma omp parallel private(cosml, sinml, aprn, pbar, pbar1, pbar2, n, m, k, l, ind, sinf, cosf) cosml = (double *) calloc ( nmax + 1, sizeof(double)); //cos(m*lamta) sinml = (double *) calloc ( nmax + 1, sizeof(double)); //sin(m*lamta) aprn = (double *) calloc ( nmax + 1, sizeof(double)); //sin(m*lamta) pbar = (double *) calloc ( nmax + 1, sizeof(double)); pbar1 = (double *) calloc ( nmax + 1, sizeof(double)); pbar2 = (double *) calloc ( nmax + 1, sizeof(double)); pt = (double *) calloc ( (nmax + 1) * (nmax + 1), sizeof(double)); ptt = (double *) calloc ( (nmax + 1) * (nmax + 1), sizeof(double)); /* for (m = 0; m <= nmax; m++) { cosml[m] = cos(m * lon * DEG2RAD); sinml[m] = sin(m * lon * DEG2RAD); } for (n = 0; n <= nmax; n++) { aprn[n] = pow (a / r, n) * gm / r; } */ cosml[0] = 1; sinml[0] = 0; cosml[1] = cos(lon * DEG2RAD); sinml[1] = sin(lon * DEG2RAD); for (m = 2; m <= nmax; m++) { cosml[m] = 2.0 * cosml[1] * cosml[m-1] - cosml[m-2]; sinml[m] = 2.0 * cosml[1] * sinml[m-1] - sinml[m-2]; } aprn[0] = gm / r; a2r = a / r; for (n = 1; n <= nmax; n++) { aprn[n] = aprn[n - 1] * a2r; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ t = coscolat; vi = 0; dvdlon = 0; dvdcolat = 0; dvdr = 0; for (m = 0; m <= nmax; m ++) { l = nmax - m + 1; // lgdr2(t, nmax, m, pbar, pbar1, pbar2); lgdr1i(t, nmax, m, pbar, pbar1); // lgdr(t, nmax, m, pbar); for (k = 0; k < l; k++) { if (m==0) { // ind = 0; n = k + m; pt[k] = aprn[n] * pbar[k]; ptt[k] = aprn[n] * pbar1[k]; vi = vi + pt[k] * cs[k]; // if (n>=2) { dvdr = dvdr + (n+1) * pt[k] * cs[k]; dvdcolat = dvdcolat + ptt[k] * cs[k]; } } else { ind = nmax + 1 + (2 * nmax - m + 2) * (m - 1); n = k + m; pt[ind + n - m] = aprn[n] * pbar[k] * cosml[m]; pt[ind + n - m + l] = aprn[n] * pbar[k] * sinml[m]; ptt[ind + n - m] = aprn[n] * pbar1[k] * cosml[m]; ptt[ind + n - m + l] = aprn[n] * pbar1[k] * sinml[m]; vi = vi + pt[ind + n - m] * cs[ind + n - m]; vi = vi + pt[ind + n - m + l] * cs[ind + n - m + l]; dvdcolat = dvdcolat + ptt[ind + n - m] * cs[ind + n - m]; dvdcolat = dvdcolat + ptt[ind + n - m + l] * cs[ind + n - m + l]; dvdlon = dvdlon - m * pt[ind + n - m + l] * cs[ind + n - m]; dvdlon = dvdlon + m * pt[ind + n - m] * cs[ind + n - m + l]; dvdr = dvdr + (n+1) * pt[ind + n - m] * cs[ind + n - m]; dvdr = dvdr + (n+1) * pt[ind + n - m + l] * cs[ind + n - m + l]; } } } // dvdcolat = - dvdcolat * sincolat; //tmd!! dvdcolat = dvdcolat; dvdlon = + dvdlon; dvdr = - dvdr / r; accn[0] = - dvdcolat / r; accn[1] = + dvdlon / r / sincolat; accn[2] = - dvdr; c_en[0] = - sinf * coslon; //from fixed to up-east-north system: rmat c_en[1] = - sinlon; c_en[2] = - cosf * coslon; c_en[3] = - sinf * sinlon; c_en[4] = coslon; c_en[5] = - cosf * sinlon; c_en[6] = cosf; c_en[7] = 0; c_en[8] = - sinf; // mt(info[num].c_ie, 3, 3, info[num].c_ei); brmul (info[num].c_ei, c_en, 3, 3, 3, c_in); //inertial to fixed matrix gmat = rmat*tbt brmul(c_in, accn, 3, 3, 1, acc); //from fixed acc to inertial acc *v = vi; // *v = gm/r + gm/r * a/r * a/r * (sqrt(5.0) * (1.5 * t * t - 0.5)) * cs[2]; *dvdt = - ANGVEL * dvdlon; // if (lon < 180) *dvdt = - ANGVEL * dvdlon - 3.08e-12 * dvdcolat; // if (lon >=180) *dvdt = - ANGVEL * dvdlon + 3.08e-12 * dvdcolat; free (pbar); free (pbar1); free (pbar2); free (pt); free (ptt); free (cosml); free (sinml); free (aprn); return 1; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ /* */ /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ double cs2vdvdt (double *llr, double *cs, double gm, double a, int NMAX, double *v, double *dvdt, double *pt) { int n, m, k, l, ind; double sinf, cosf, *cosml, *sinml, *aprn, *pbar, lat, lon, r, vi, dvdti, t; /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ lat = llr[0]; lon = llr[1]; r = llr[2]; sinf = sin(lat * DEG2RAD); cosf = cos(lat * DEG2RAD); // #pragma omp parallel private(cosml, sinml, aprn, pbar, pbar1, pbar2, n, m, k, l, ind, sinf, cosf) cosml = (double *) calloc ( NMAX + 1, sizeof(double)); //cos(m*lamta) sinml = (double *) calloc ( NMAX + 1, sizeof(double)); //sin(m*lamta) aprn = (double *) calloc ( NMAX + 1, sizeof(double)); //sin(m*lamta) pbar = (double *) calloc ( NMAX + 1, sizeof(double)); for (m = 0; m <= NMAX; m++) { cosml[m] = cos(m * lon * DEG2RAD); sinml[m] = sin(m * lon * DEG2RAD); } for (n = 0; n <= NMAX; n++) { aprn[n] = pow (a / r, n) * gm / r; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/ t = sinf; vi = 0; dvdti = 0; for (m = 0; m <= NMAX; m ++) { l = NMAX - m + 1; // lgdr2(t, NMAX, m, pbar, pbar1, pbar2); lgdr(t, NMAX, m, pbar); for (k = 0; k < l; k++) { if (m==0) { // ind = 0; n = k + m; pt[k] = aprn[n] * pbar[k]; vi = vi + pt[k] * cs[k]; } else { ind = NMAX + 1 + (2 * NMAX - m + 2) * (m - 1); n = k + m; pt[ind + n - m] = aprn[n] * pbar[k] * cosml[m]; pt[ind + n - m + l] = aprn[n] * pbar[k] * sinml[m]; vi = vi + pt[ind + n - m] * cs[ind + n - m]; vi = vi + pt[ind + n - m + l] * cs[ind + n - m + l]; dvdti = dvdti + m * pt[ind + n - m + l] * cs[ind + n - m]; dvdti = dvdti - m * pt[ind + n - m] * cs[ind + n - m + l]; } } } //! ATPA // gpti = 0; // for(k = 0; k < (NMAX + 1) * (NMAX + 1); k++) // { // gpti = gpti + pt[k] * cs[k]; // pt[k] = pnmc[k]; // } *v = vi; *dvdt = dvdti * ANGVEL; free (pbar); free (cosml); free (sinml); free (aprn); return 1; } /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
ext_kernels.c
#include <stdbool.h> #include <math.h> #include "ext_sweep.h" #include "ext_macros.h" #include "ext_problem.h" #include "ext_profiler.h" #include "ext_kernels.h" // Calculate the inverted denominator for all the energy groups void calc_denominator(void) { START_PROFILING; #pragma omp target if(OFFLOAD) device(MIC_DEVICE) #pragma omp parallel for for (unsigned int ind = 0; ind < nx*ny*nz; ind++) { for (unsigned int g = 0; g < ng; ++g) { for (unsigned int a = 0; a < nang; ++a) { denom[a+g*nang+ind*ng*nang] = 1.0 / (total_cross_section[g+ind*ng] + time_delta(g) + mu(a)*dd_i + dd_j(a) + dd_k(a)); } } } STOP_PROFILING(__func__, true); } // Calculate the time delta void calc_time_delta(void) { START_PROFILING; #pragma omp target if(OFFLOAD) device(MIC_DEVICE) for(int g = 0; g < ng; ++g) { time_delta(g) = 2.0 / (dt * velocity(g)); } STOP_PROFILING(__func__, true); } // Calculate the diamond difference coefficients void calc_dd_coefficients(void) { START_PROFILING; #pragma omp target if(OFFLOAD) device(MIC_DEVICE) { dd_i = 2.0 / dx; for(int a = 0; a < nang; ++a) { dd_j(a) = (2.0/dy)*eta(a); dd_k(a) = (2.0/dz)*xi(a); } } STOP_PROFILING(__func__, true); } // Calculate the total cross section from the spatial mapping void calc_total_cross_section(void) { START_PROFILING; #pragma omp target if(OFFLOAD) device(MIC_DEVICE) #pragma omp parallel for for(int k = 0; k < nz; ++k) { for(int j = 0; j < ny; ++j) { for(int i = 0; i < nx; ++i) { for(int g = 0; g < ng; ++g) { total_cross_section(g,i,j,k) = xs(mat(i,j,k)-1,g); } } } } STOP_PROFILING(__func__, true); } void calc_scattering_cross_section(void) { START_PROFILING; #pragma omp target if(OFFLOAD) device(MIC_DEVICE) #pragma omp parallel for for(unsigned int g = 0; g < ng; ++g) { for (unsigned int k = 0; k < nz; k++) { for (unsigned int j = 0; j < ny; j++) { for (unsigned int i = 0; i < nx; i++) { for (unsigned int l = 0; l < nmom; l++) { scat_cs(l,i,j,k,g) = gg_cs(mat(i,j,k)-1,l,g,g); } } } } } STOP_PROFILING(__func__, true); } // Calculate the outer source void calc_outer_source(void) { START_PROFILING; #pragma omp target if(OFFLOAD) device(MIC_DEVICE) #pragma omp parallel for collapse(4) for (unsigned int g1 = 0; g1 < ng; g1++) { for(int k = 0; k < nz; ++k) { for(int j = 0; j < ny; ++j) { for(int i = 0; i < nx; ++i) { g2g_source(0,i,j,k,g1) = fixed_source(i,j,k,g1); for (unsigned int g2 = 0; g2 < ng; g2++) { if (g1 == g2) { continue; } g2g_source(0,i,j,k,g1) += gg_cs(mat(i,j,k)-1,0,g2,g1) * scalar_flux(g2,i,j,k); unsigned int mom = 1; for (unsigned int l = 1; l < nmom; l++) { for (int m = 0; m < lma(l); m++) { g2g_source(mom,i,j,k,g1) += gg_cs(mat(i,j,k)-1,l,g2,g1) * scalar_mom(g2,mom-1,i,j,k); mom++; } } } } } } } STOP_PROFILING(__func__, true); } // Calculate the inner source void calc_inner_source(void) { START_PROFILING; #pragma omp target if(OFFLOAD) device(MIC_DEVICE) #pragma omp parallel for collapse(4) for (unsigned int g = 0; g < ng; g++) { for(int k = 0; k < nz; ++k) { for(int j = 0; j < ny; ++j) { for(int i = 0; i < nx; ++i) { source(0,i,j,k,g) = g2g_source(0,i,j,k,g) + scat_cs(0,i,j,k,g) * scalar_flux(g,i,j,k); unsigned int mom = 1; for (unsigned int l = 1; l < nmom; l++) { for (int m = 0; m < lma(l); m++) { source(mom,i,j,k,g) = g2g_source(mom,i,j,k,g) + scat_cs(l,i,j,k,g) * scalar_mom(g,mom-1,i,j,k); mom++; } } } } } } STOP_PROFILING(__func__, true); } void zero_flux_in_out(void) { #pragma omp target if(OFFLOAD) device(MIC_DEVICE) #pragma omp parallel for for(int i = 0; i < flux_in_len; ++i) { flux_in[i] = 0.0; } #pragma omp target if(OFFLOAD) device(MIC_DEVICE) #pragma omp parallel for for(int i = 0; i < flux_out_len; ++i) { flux_out[i] = 0.0; } } void zero_edge_flux_buffers(void) { int fi_len = nang*ng*ny*nz; int fj_len = nang*ng*nx*nz; int fk_len = nang*ng*nx*ny; #define MAX(A,B) (((A) > (B)) ? (A) : (B)) int max_length = MAX(MAX(fi_len, fj_len), fk_len); #pragma omp target if(OFFLOAD) device(MIC_DEVICE) #pragma omp parallel for for(int i = 0; i < max_length; ++i) { if(i < fi_len) flux_i[i] = 0.0; if(i < fj_len) flux_j[i] = 0.0; if(i < fk_len) flux_k[i] = 0.0; } } void zero_flux_moments_buffer(void) { #pragma omp target if(OFFLOAD) device(MIC_DEVICE) #pragma omp parallel for for(int i = 0; i < scalar_mom_len; ++i) { scalar_mom[i] = 0.0; } } void zero_scalar_flux(void) { #pragma omp target if(OFFLOAD) device(MIC_DEVICE) #pragma omp parallel for for(int i = 0; i < scalar_flux_len; ++i) { scalar_flux[i] = 0.0; } } bool check_convergence( double *old, double *new, double epsi, unsigned int *groups_todo, unsigned int *num_groups_todo, bool inner) { START_PROFILING; bool r = true; int ngt = 0; #pragma omp target if(OFFLOAD) device(MIC_DEVICE) #pragma omp parallel for for (unsigned int g = 0; g < ng; g++) { for (unsigned int ind = 0; ind < nx*ny*nz; ind++) { double val = (fabs(old[g+(ng*ind)] > tolr)) ? fabs(new[g+(ng*ind)]/old[g+(ng*ind)] - 1.0) : fabs(new[g+(ng*ind)] - old[g+(ng*ind)]); if (val > epsi) { r = false; if (inner) { #pragma omp critical { // Add g to the list of groups to do if we need to do it groups_todo[ngt] = g; ngt++; } } break; } } } *num_groups_todo = ngt; STOP_PROFILING(__func__, true); return r; } void initialise_device_memory(void) { zero_scalar_flux(); zero_flux_moments_buffer(); zero_flux_in_out(); zero_edge_flux_buffers(); #pragma omp target if(OFFLOAD) device(MIC_DEVICE) { #pragma omp parallel for for(int ii = 0; ii < g2g_source_len; ++ii) { g2g_source[ii] = 0.0; } #pragma omp parallel for for(int ii = 0; ii < source_len; ++ii) { source[ii] = 0.0; } } } // Copies the value of scalar flux void store_scalar_flux(double* to) { START_PROFILING; #pragma omp target if(OFFLOAD) device(MIC_DEVICE) #pragma omp parallel for for(int i = 0; i < scalar_flux_len; ++i) { to[i] = scalar_flux[i]; } STOP_PROFILING(__func__, true); }
mafillpmain.c
/* CalculiX - A 3-dimensional finite element program */ /* Copyright (C) 1998-2015 Guido Dhondt */ /* This program is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU General Public License as */ /* published by the Free Software Foundation(version 2); */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* You should have received a copy of the GNU General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <unistd.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <pthread.h> #include "CalculiX.h" static char *lakonf1; static ITG num_cpus,*nef1,*ipnei1,*neifa1,*neiel1,*jq1,*irow1,*ielfa1, *ifabou1,*neq1,*nzs1,*neij1; static double *vfa1,*area1,*advfa1,*xlet1,*cosa1,*volume1,*au1=NULL,*ad1=NULL, *ap1,*xle1,*b1=NULL,*xxn1,*hfa1,*gradpel1,*bp1,*xxi1,*xlen1,*cosb1; void mafillpmain(ITG *nef,char *lakonf,ITG *ipnei, ITG *neifa,ITG *neiel,double *vfa,double *area,double *advfa, double *xlet,double *cosa,double *volume,double *au,double *ad, ITG *jq,ITG *irow,double *ap,ITG *ielfa,ITG *ifabou, double *xle,double *b,double *xxn,ITG *neq, ITG *nzs,double *hfa,double *gradpel, double *bp,double *xxi,ITG *neij,double *xlen,double *cosb, ITG *iatleastonepressurebc){ ITG i,j; /* variables for multithreading procedure */ ITG sys_cpus,*ithread=NULL; char *env,*envloc,*envsys; num_cpus = 0; sys_cpus=0; /* explicit user declaration prevails */ envsys=getenv("NUMBER_OF_CPUS"); if(envsys){ sys_cpus=atoi(envsys); if(sys_cpus<0) sys_cpus=0; } /* automatic detection of available number of processors */ if(sys_cpus==0){ sys_cpus = getSystemCPUs(); if(sys_cpus<1) sys_cpus=1; } /* local declaration prevails, if strictly positive */ envloc = getenv("CCX_NPROC_CFD"); if(envloc){ num_cpus=atoi(envloc); if(num_cpus<0){ num_cpus=0; }else if(num_cpus>sys_cpus){ num_cpus=sys_cpus; } } /* else global declaration, if any, applies */ env = getenv("OMP_NUM_THREADS"); if(num_cpus==0){ if (env) num_cpus = atoi(env); if (num_cpus < 1) { num_cpus=1; }else if(num_cpus>sys_cpus){ num_cpus=sys_cpus; } } // next line is to be inserted in a similar way for all other paralell parts if(*nef<num_cpus) num_cpus=*nef; pthread_t tid[num_cpus]; /* allocating fields for lhs and rhs matrix */ NNEW(ad1,double,num_cpus**neq); NNEW(au1,double,(long long)num_cpus**nzs); NNEW(b1,double,num_cpus**neq); /* calculating the stiffness and/or mass matrix (symmetric part) */ nef1=nef;lakonf1=lakonf;ipnei1=ipnei;neifa1=neifa;neiel1=neiel; vfa1=vfa;area1=area;advfa1=advfa;xlet1=xlet,cosa1=cosa;volume1=volume; jq1=jq;irow1=irow;ap1=ap;ielfa1=ielfa;ifabou1=ifabou;xle1=xle; xxn1=xxn;neq1=neq;nzs1=nzs;hfa1=hfa;gradpel1=gradpel;bp1=bp;xxi1=xxi; neij1=neij;xlen1=xlen;cosb1=cosb; /* create threads and wait */ NNEW(ithread,ITG,num_cpus); for(i=0; i<num_cpus; i++) { ithread[i]=i; pthread_create(&tid[i], NULL, (void *)mafillpmt, (void *)&ithread[i]); } for(i=0; i<num_cpus; i++) pthread_join(tid[i], NULL); SFREE(ithread); /* copying and accumulating the stiffnes and/or mass matrix */ #pragma omp parallel \ default(none) \ shared(neq,ad,ad1,num_cpus,nzs,au,au1,b,b1) \ private(i,j) { #pragma omp for for(i=0;i<*neq;i++){ ad[i]=ad1[i]; for(j=1;j<num_cpus;j++){ ad[i]+=ad1[i+j**neq]; } } #pragma omp for for(i=0;i<*nzs;i++){ au[i]=au1[i]; for(j=1;j<num_cpus;j++){ au[i]+=au1[i+(long long)j**nzs]; } } #pragma omp for for(i=0;i<*neq;i++){ b[i]=b1[i]; for(j=1;j<num_cpus;j++){ b[i]+=b1[i+j**neq]; } } } SFREE(ad1); SFREE(au1); SFREE(b1); FORTRAN(mafillpbc,(nef,au,ad,jq,irow,b,iatleastonepressurebc,nzs)); return; } /* subroutine for multithreading of mafillp */ void *mafillpmt(ITG *i){ ITG indexad,indexb,nefa,nefb,nefdelta; long long indexau; indexad=*i**neq1; indexau=(long long)*i**nzs1; indexb=*i**neq1; // ceil -> floor nefdelta=(ITG)floor(*nef1/(double)num_cpus); nefa=*i*nefdelta+1; nefb=(*i+1)*nefdelta; // next line! -> all parallel sections if((*i==num_cpus-1)&&(nefb<*nef1)) nefb=*nef1; FORTRAN(mafillp,(nef1,lakonf1,ipnei1,neifa1,neiel1,vfa1,area1, advfa1,xlet1,cosa1,volume1,&au1[indexau],&ad1[indexad], jq1,irow1,ap1,ielfa1,ifabou1,xle1,&b1[indexb],xxn1,neq1,nzs1, hfa1,gradpel1,bp1,xxi1,neij1,xlen1,cosb1,&nefa,&nefb)); return NULL; }
TrackingFromPersistenceDiagrams.h
/// \ingroup base /// \class ttk::TrackingFromPersistenceDiagrams /// \author Maxime Soler <soler.maxime@total.com> /// \date August 2018. #ifndef _TRACKINGFROMP_H #define _TRACKINGFROMP_H // base code includes #include <Wrapper.h> #include <PersistenceDiagram.h> #include <BottleneckDistance.h> namespace ttk { class TrackingFromPersistenceDiagrams : public Debug { public: TrackingFromPersistenceDiagrams(); ~TrackingFromPersistenceDiagrams(); /// Execute the package. /// \return Returns 0 upon success, negative values otherwise. template <class dataType> int execute(); template <typename dataType> int performSingleMatching( int i, std::vector<std::vector<diagramTuple>>& inputPersistenceDiagrams, std::vector<std::vector<matchingTuple>>& outputMatchings, std::string algorithm, std::string wasserstein, double tolerance, bool is3D, double alpha, double px, double py, double pz, double ps, double pe, const ttk::Wrapper *wrapper); template <typename dataType> int performMatchings( int numInputs, std::vector<std::vector<diagramTuple>>& inputPersistenceDiagrams, std::vector<std::vector<matchingTuple>>& outputMatchings, const std::string& algorithm, const std::string& wasserstein, double tolerance, bool is3D, double alpha, double px, double py, double pz, double ps, double pe, const ttk::Wrapper *wrapper); template <typename dataType> int performTracking( std::vector<std::vector<diagramTuple>>& allDiagrams, std::vector<std::vector<matchingTuple>>& allMatchings, std::vector<trackingTuple>& trackings); template <typename dataType> int performPostProcess( std::vector<std::vector<diagramTuple>>& allDiagrams, std::vector<trackingTuple>& trackings, std::vector<std::set<int>>& trackingTupleToMerged, double postProcThresh); /// Pass a pointer to an input array representing a scalarfield. /// The array is expected to be correctly allocated. idx in [0,numberOfInputs_[ /// \param idx Index of the input scalar field. /// \param data Pointer to the data array. /// \return Returns 0 upon success, negative values otherwise. /// \sa setNumberOfInputs() and setVertexNumber(). inline int setInputDataPointer(int idx, void *data){ if (idx < numberOfInputs_) inputData_[idx] = data; else return -1; return 0; } /// Set the number of input scalar fields /// \param numberOfInputs Number of input scalar fields. /// \return Returns 0 upon success, negative values otherwise inline int setNumberOfInputs(int numberOfInputs){ numberOfInputs_ = numberOfInputs; return 0; } protected: int numberOfInputs_; void **inputData_; }; } // template functions template <class dataType> int ttk::TrackingFromPersistenceDiagrams::execute() { ttk::Timer t; // Check the consistency of the variables #ifndef TTK_ENABLE_KAMIKAZE if (!numberOfInputs_) return -1; if (!inputData_) return -3; for (int i = 0; i < numberOfInputs_; i++) { if (!inputData_[i]) return -4; } #endif { std::stringstream msg; msg << "[TrackingFromPersistenceDiagrams] Data-set " << "processed in " << t.getElapsedTime() << " s. (" << threadNumber_ << " thread(s))." << std::endl; dMsg(std::cout, msg.str(), timeMsg); } return 0; } template <typename dataType> int ttk::TrackingFromPersistenceDiagrams::performSingleMatching( int i, std::vector<std::vector<diagramTuple>>& inputPersistenceDiagrams, std::vector<std::vector<matchingTuple>>& outputMatchings, std::string algorithm, std::string wasserstein, double tolerance, bool is3D, double alpha, double px, double py, double pz, double ps, double pe, const ttk::Wrapper *wrapper) { ttk::BottleneckDistance bottleneckDistance_; bottleneckDistance_.setWrapper(wrapper); bottleneckDistance_.setPersistencePercentThreshold(tolerance); bottleneckDistance_.setPX(px); bottleneckDistance_.setPY(py); bottleneckDistance_.setPZ(pz); bottleneckDistance_.setPS(ps); bottleneckDistance_.setPE(pe); bottleneckDistance_.setAlgorithm(algorithm); bottleneckDistance_.setWasserstein(wasserstein); bottleneckDistance_.setCTDiagram1(&inputPersistenceDiagrams[i]); bottleneckDistance_.setCTDiagram2(&inputPersistenceDiagrams[i + 1]); bottleneckDistance_.setOutputMatchings(&outputMatchings[i]); bottleneckDistance_.execute<dataType>(false); return 0; } template <typename dataType> int ttk::TrackingFromPersistenceDiagrams::performMatchings( int numInputs, std::vector<std::vector<diagramTuple>>& inputPersistenceDiagrams, std::vector<std::vector<matchingTuple>>& outputMatchings, const std::string& algorithm, const std::string& wasserstein, double tolerance, bool is3D, double alpha, double px, double py, double pz, double ps, double pe, const ttk::Wrapper *wrapper) { #pragma omp parallel for num_threads(threadNumber_) for (int i = 0; i < numInputs - 1; ++i) { performSingleMatching<dataType>( i, inputPersistenceDiagrams, outputMatchings, algorithm, // Not from paraview, from enclosing tracking plugin wasserstein, tolerance, is3D, alpha, // Blending px, py, pz, ps, pe, // Coefficients wrapper // Wrapper for accessing threadNumber ); } // Never from PV, // Alaways activate output matchings. return 0; } template <typename dataType> int ttk::TrackingFromPersistenceDiagrams::performTracking( std::vector<std::vector<diagramTuple>>& allDiagrams, std::vector<std::vector<matchingTuple>>& allMatchings, std::vector<trackingTuple>& trackings) { auto numPersistenceDiagramsInput = (int) allDiagrams.size(); for (int in = 1; in < numPersistenceDiagramsInput - 1; ++in) { std::vector<matchingTuple> matchings1 = allMatchings[in - 1]; std::vector<matchingTuple> matchings2 = allMatchings[in]; auto matchingsSize1 = (int) matchings1.size(); auto matchingsSize2 = (int) matchings2.size(); int endIndex = numPersistenceDiagramsInput - 2; for (int i = 0; i < matchingsSize1; ++i) { auto m1ai0 = (int) std::get<0>(matchings1[i]); auto m1ai1 = (int) std::get<1>(matchings1[i]); for (int j = 0; j < matchingsSize2; ++j) { auto m2aj0 = (int) std::get<0>(matchings2[j]); auto m2aj1 = (int) std::get<1>(matchings2[j]); if (m1ai1 != m2aj0) continue; // Detect in trackings and push. bool found = false; for (trackingTuple &tt : trackings) { int chainStart = std::get<0>(tt); int chainEnd = std::get<1>(tt); std::vector<BIdVertex> &chain = std::get<2>(tt); if (chainEnd == -1) { auto chainSize = (int) chain.size(); if (chainSize == 0) { // Should not happen std::cout << "Brain error." << std::endl; } else if (chainStart + chainSize == in && chain.at((unsigned long) chainSize - 1) == m1ai0) { found = true; chain.push_back(m1ai1); int numEnd = in == endIndex ? endIndex : -1; if (in == endIndex) { chain.push_back(m2aj1); std::get<1>(tt) = numEnd; } std::get<2>(tt) = chain; } } tt = std::make_tuple(chainStart, chainEnd, chain); } if (!found) { std::vector<BIdVertex> chain; chain.push_back(m1ai0); chain.push_back(m1ai1); if (in == endIndex) { chain.push_back(m2aj1); } int numEnd = in == endIndex ? endIndex : -1; trackingTuple tt = std::make_tuple(in - 1, numEnd, chain); trackings.push_back(tt); } // Create new. } } // End non-matched chains. for (trackingTuple &tt : trackings) { int chainStart = std::get<0>(tt); int chainEnd = std::get<1>(tt); if (chainEnd == -1) { std::vector<BIdVertex> &chain = std::get<2>(tt); auto chainSize = (int) chain.size(); if (chainStart + chainSize - 1 < in) std::get<1>(tt) = in - 1; } } } // Post-processing std::sort(trackings.begin(), trackings.end(), [](const trackingTuple &a, const trackingTuple &b) -> bool { return std::get<0>(a) < std::get<0>(b); }); return 0; } template <typename dataType> int ttk::TrackingFromPersistenceDiagrams::performPostProcess( std::vector<std::vector<diagramTuple>>& allDiagrams, std::vector<trackingTuple>& trackings, std::vector<std::set<int>>& trackingTupleToMerged, double postProcThresh) { auto numPersistenceDiagramsInput = (int) allDiagrams.size(); // Merge close connected components with threshold. for (unsigned int k = 0; k < trackings.size(); ++k) { trackingTuple tk = trackings[k]; int startK = std::get<0>(tk); int endK = std::get<1>(tk); if (endK < 0) endK = numPersistenceDiagramsInput - 1; std::vector<BIdVertex> chainK = std::get<2>(tk); std::vector<diagramTuple> &diagramStartK = allDiagrams[startK]; std::vector<diagramTuple> &diagramEndK = allDiagrams[endK]; auto n1 = (int) chainK.at(0); auto n2 = (int) chainK.at(chainK.size() - 1); diagramTuple &tuple1 = diagramStartK[n1]; diagramTuple &tuple2 = diagramEndK[n2]; double x1, y1, z1, x2, y2, z2; BNodeType point1Type1 = std::get<1>(tuple1); BNodeType point1Type2 = std::get<3>(tuple1); bool t11Min = point1Type1 == BLocalMin; bool t11Max = point1Type1 == BLocalMax; bool t12Min = point1Type2 == BLocalMin; bool t12Max = point1Type2 == BLocalMax; // bool bothEx1 = t11Ex && t12Ex; bool t1Max = t11Max || t12Max; bool t1Min = !t1Max && (t11Min || t12Min); x1 = t1Max ? std::get<11>(tuple1) : t1Min ? std::get<7>(tuple1) : 0; y1 = t1Max ? std::get<12>(tuple1) : t1Min ? std::get<8>(tuple1) : 0; z1 = t1Max ? std::get<13>(tuple1) : t1Min ? std::get<9>(tuple1) : 0; BNodeType point2Type1 = std::get<1>(tuple2); BNodeType point2Type2 = std::get<3>(tuple2); bool t21Min = point2Type1 == BLocalMin; bool t21Max = point2Type1 == BLocalMax; bool t22Min = point2Type2 == BLocalMin; bool t22Max = point2Type2 == BLocalMax; // bool bothEx2 = t21Ex && t22Ex; bool t2Max = t21Max || t22Max; bool t2Min = !t2Max && (t21Min || t22Min); // if (bothEx2) { x2 = t2Max ? std::get<11>(tuple2) : t2Min ? std::get<7>(tuple2) : 0; y2 = t2Max ? std::get<12>(tuple2) : t2Min ? std::get<8>(tuple2) : 0; z2 = t2Max ? std::get<13>(tuple2) : t2Min ? std::get<9>(tuple2) : 0; // } // if (!bothEx1 && !bothEx2) // continue; // Saddle-saddle matching not supported. if (!t1Min && !t2Min && !t1Max && !t2Max) continue; // Check every other tracking trajectory. for (unsigned int m = k + 1; m < trackings.size(); ++m) { trackingTuple &tm = trackings[m]; int startM = std::get<0>(tm); int endM = std::get<1>(tm); std::vector<BIdVertex> &chainM = std::get<2>(tm); if ((endK > 0 && startM > endK) || (endM > 0 && startK > endM)) continue; for (int c = 0; c < (int) chainM.size(); ++c) { bool doMatch1 = startM + c == startK; bool doMatch2 = startM + c == endK; // if (startM + c != startK && startM + c != endK) continue; if (!doMatch1 && !doMatch2) continue; /// Check proximity. auto n3 = (int) chainM[c]; std::vector<diagramTuple> &diagramM = allDiagrams[startM + c]; diagramTuple &tuple3 = diagramM[n3]; double x3, y3, z3; BNodeType point3Type1 = std::get<1>(tuple3); BNodeType point3Type2 = std::get<3>(tuple3); bool t31Min = point3Type1 == BLocalMin; bool t31Max = point3Type1 == BLocalMax; bool t32Min = point3Type2 == BLocalMin; bool t32Max = point3Type2 == BLocalMax; // bool bothEx3 = t31Ex && t32Ex; // if (!bothEx3) // continue; bool t3Max = t31Max || t32Max; bool t3Min = !t3Max && (t31Min || t32Min); x3 = t3Max ? std::get<11>(tuple3) : t3Min ? std::get<7>(tuple3) : 0; y3 = t3Max ? std::get<12>(tuple3) : t3Min ? std::get<8>(tuple3) : 0; z3 = t3Max ? std::get<13>(tuple3) : t3Min ? std::get<9>(tuple3) : 0; double dist = 0; bool hasMatched = false; if (doMatch1 && ((t3Max && t1Max) || (t3Min && t1Min))) { double dist13 = sqrt(std::pow(x1 - x3, 2) + std::pow(y1 - y3, 2) + std::pow(z1 - z3, 2)); dist = dist13; if (dist13 >= postProcThresh) continue; hasMatched = true; } if (doMatch2 && ((t3Max && t2Max) || (t3Min && t2Min))) { double dist23 = sqrt(std::pow(x2 - x3, 2) + std::pow(y2 - y3, 2) + std::pow(z2 - z3, 2)); dist = dist23; if (dist23 >= postProcThresh) continue; hasMatched = true; } if (!hasMatched) continue; /// Merge! std::stringstream msg; msg << "[ttkTrackingFromPersistenceDiagrams] Merged " << m << " with " << k << ": d = " << dist << "." << std::endl; dMsg(std::cout, msg.str(), timeMsg); // Get every other tracking trajectory. std::set<int>& mergedM = trackingTupleToMerged[m]; // std::set<int> mergedK = trackingTupleToMerged[k]; // Push for others to merge. // for (auto& i : mergedM) mergedK.insert(i); // for (auto& i : mergedK) mergedM.insert(i); // mergedK.insert(m); mergedM.insert(k); break; } } } return 0; } #endif // _TRACKINGFROMP_H
matrixstrassen.h
/** * @file matrixstrassen.h matrix strassen operations. * @author TPOC: palisade@njit.edu * * @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT) * 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. * 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. * */ #ifndef LBCRYPTO_MATH_MATRIXSTRASSEN_H #define LBCRYPTO_MATH_MATRIXSTRASSEN_H #include "matrix.h" namespace lbcrypto { template<class Element> class MatrixStrassen : public Serializable { public: typedef vector<vector<unique_ptr<Element>>> data_t; typedef vector<unique_ptr<Element>> lineardata_t; typedef typename vector<unique_ptr<Element>>::iterator it_lineardata_t; typedef std::function<unique_ptr<Element>(void)> alloc_func; /** * Constructor that initializes matrix values using a zero allocator * * @param &allocZero lambda function for zero initialization. * @param &rows number of rows. * @param &rows number of columns. */ MatrixStrassen(alloc_func allocZero, size_t rows, size_t cols) : data(), rows(rows), cols(cols), allocZero(allocZero) { data.resize(rows); for (auto row = data.begin(); row != data.end(); ++row) { for (size_t col = 0; col < cols; ++col) { row->push_back(allocZero()); } } } /** * Constructor that initializes matrix values using a distribution generation allocator * * @param &allocZero lambda function for zero initialization (used for initializing derived matrix objects) * @param &rows number of rows. * @param &rows number of columns. * @param &allocGen lambda function for intialization using a distribution generator. */ MatrixStrassen(alloc_func allocZero, size_t rows, size_t cols, alloc_func allocGen); /** * Constructor of an empty matrix; SetSize must be called on this matrix to use it * Basically this exists to support deserializing * * @param &allocZero lambda function for zero initialization. */ MatrixStrassen(alloc_func allocZero) : data(), rows(0), cols(0), allocZero(allocZero) {} void SetSize(size_t rows, size_t cols) { if( this->rows != 0 || this->cols != 0 ) throw std::logic_error("You cannot SetSize on a non-empty matrix"); this->rows = rows; this->cols = cols; data.resize(rows); for (auto row = data.begin(); row != data.end(); ++row) { for (size_t col = 0; col < cols; ++col) { row->push_back(allocZero()); } } } /** * Copy constructor * * @param &other the matrix object to be copied */ MatrixStrassen(const MatrixStrassen<Element>& other) : data(), rows(other.rows), cols(other.cols), allocZero(other.allocZero) { deepCopyData(other.data); } /** * Assignment operator * * @param &other the matrix object whose values are to be copied * @return the resulting matrix */ inline MatrixStrassen<Element>& operator=(const MatrixStrassen<Element>& other); /** * In-place change of the current matrix to a matrix of all ones * * @return the resulting matrix */ inline MatrixStrassen<Element>& Ones(); /** * Fill matrix using the same element * * @param &val the element the matrix is filled by * * @return the resulting matrix */ inline MatrixStrassen<Element>& Fill(const Element &val); /** * In-place change of the current matrix to Identity matrix * * @return the resulting matrix */ inline MatrixStrassen<Element>& Identity(); /** * Sets the first row to be powers of two * * @return the resulting matrix */ inline MatrixStrassen<Element> GadgetVector() const; /** * Computes the infinity norm * * @return the norm in double format */ inline double Norm() const; /** * Operator for matrix multiplication * * @param &other the multiplier matrix * @return the result of multiplication */ inline MatrixStrassen<Element> operator*(MatrixStrassen<Element> const& other) const { return Mult(other); } /** * Multiplication of matrix by a scalar * * @param &other the multiplier element * @return the result of multiplication */ inline MatrixStrassen<Element> ScalarMult(Element const& other) const { MatrixStrassen<Element> result(*this); #if 0 for (size_t row = 0; row < result.rows; ++row) { for (size_t col = 0; col < result.cols; ++col) { *result.data[row][col] = *result.data[row][col] * other; } } #else #pragma omp parallel for for (int32_t col = 0; col < result.cols; ++col) { for (int32_t row = 0; row < result.rows; ++row) { *result.data[row][col] = *result.data[row][col] * other; } } #endif return result; } /** * Operator for scalar multiplication * * @param &other the multiplier element * @return the result of multiplication */ inline MatrixStrassen<Element> operator*(Element const& other) const { return ScalarMult(other); } /** * Equality check * * @param &other the matrix object to compare to * @return the boolean result */ inline bool Equal(MatrixStrassen<Element> const& other) const { if (rows != other.rows || cols != other.cols) { return false; } for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < cols; ++j) { if (*data[i][j] != *other.data[i][j]) { return false; } } } return true; } /** * Operator for equality check * * @param &other the matrix object to compare to * @return the boolean result */ inline bool operator==(MatrixStrassen<Element> const& other) const { return Equal(other); } /** * Operator for non-equality check * * @param &other the matrix object to compare to * @return the boolean result */ inline bool operator!=(MatrixStrassen<Element> const& other) const { return !Equal(other); } /** * Get property to access the data as a vector of vectors * * @return the data as vector of vectors */ const data_t& GetData() const { return data; } /** * Get property to access the number of rows in the matrix * * @return the number of rows */ size_t GetRows() const { return rows; } /** * Get property to access the number of columns in the matrix * * @return the number of columns */ size_t GetCols() const { return cols; } /** * Get property to access the zero allocator for the matrix * * @return the lambda function corresponding to the element zero allocator */ alloc_func GetAllocator() const { return allocZero; } /** * Sets the evaluation or coefficient representation for all ring elements that support the SetFormat method * * @param &format the enum value corresponding to coefficient or evaluation representation */ void SetFormat(Format format); /** * MatrixStrassen addition * * @param &other the matrix to be added * @return the resulting matrix */ inline MatrixStrassen<Element> Add(MatrixStrassen<Element> const& other) const { if (rows != other.rows || cols != other.cols) { throw invalid_argument("Addition operands have incompatible dimensions"); } MatrixStrassen<Element> result(*this); #if 0 for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < cols; ++j) { *result.data[i][j] += *other.data[i][j]; } } #else #pragma omp parallel for for (int32_t j = 0; j < cols; ++j) { for (int32_t i = 0; i < rows; ++i) { *result.data[i][j] += *other.data[i][j]; } } #endif return result; } /** * Operator for matrix addition * * @param &other the matrix to be added * @return the resulting matrix */ inline MatrixStrassen<Element> operator+(MatrixStrassen<Element> const& other) const { return this->Add(other); } /** * Operator for in-place addition * * @param &other the matrix to be added * @return the resulting matrix (same object) */ inline MatrixStrassen<Element>& operator+=(MatrixStrassen<Element> const& other); /** * MatrixStrassen substraction * * @param &other the matrix to be substracted * @return the resulting matrix */ inline MatrixStrassen<Element> Sub(MatrixStrassen<Element> const& other) const { if (rows != other.rows || cols != other.cols) { throw invalid_argument("Subtraction operands have incompatible dimensions"); } MatrixStrassen<Element> result(allocZero, rows, other.cols); #if 0 for (size_t i = 0; i < rows; ++i) { for (size_t j = 0; j < cols; ++j) { *result.data[i][j] = *data[i][j] - *other.data[i][j]; } } #else #pragma omp parallel for for (int32_t j = 0; j < cols; ++j) { for (int32_t i = 0; i < rows; ++i) { *result.data[i][j] = *data[i][j] - *other.data[i][j]; } } #endif return result; } /** * Operator for matrix substraction * * @param &other the matrix to be substracted * @return the resulting matrix */ inline MatrixStrassen<Element> operator-(MatrixStrassen<Element> const& other) const { return this->Sub(other); } /** * Operator for in-place matrix substraction * * @param &other the matrix to be substracted * @return the resulting matrix (same object) */ inline MatrixStrassen<Element>& operator-=(MatrixStrassen<Element> const& other); /** * MatrixStrassen transposition * * @return the resulting matrix */ inline MatrixStrassen<Element> Transpose() const; // YSP The signature of this method needs to be changed in the future /** * MatrixStrassen determinant - found using Laplace formula with complexity O(d!), where d is the dimension * * @param *result where the result is stored */ inline void Determinant(Element *result) const; //inline Element Determinant() const; /** * Cofactor matrix - the matrix of determinants of the minors A_{ij} multiplied by -1^{i+j} * * @return the cofactor matrix for the given matrix */ inline MatrixStrassen<Element> CofactorMatrixStrassen() const; /** * Add rows to bottom of the matrix * * @param &other the matrix to be added to the bottom of current matrix * @return the resulting matrix */ inline MatrixStrassen<Element>& VStack(MatrixStrassen<Element> const& other); /** * Add columns the right of the matrix * * @param &other the matrix to be added to the right of current matrix * @return the resulting matrix */ inline MatrixStrassen<Element>& HStack(MatrixStrassen<Element> const& other); /** * MatrixStrassen indexing operator - writeable instance of the element * * @param &row row index * @param &col column index * @return the element at the index */ inline Element& operator()(size_t row, size_t col) { return *data[row][col]; } /** * MatrixStrassen indexing operator - read-only instance of the element * * @param &row row index * @param &col column index * @return the element at the index */ inline Element const& operator()(size_t row, size_t col) const { return *data[row][col]; } /** * MatrixStrassen row extractor * * @param &row row index * @return the row at the index */ inline MatrixStrassen<Element> ExtractRow(size_t row) const { MatrixStrassen<Element> result(this->allocZero,1,this->cols); int i = 0; for (auto elem = this->GetData()[row].begin(); elem != this->GetData()[row].end(); ++elem) { result(0,i) = **elem; i++; } return result; //return *this; } /** * Print values of the matrix to the cout stream * */ void PrintValues() const; /** * Call switch format for each (ring) element * */ inline void SwitchFormat(); /** * MatrixStrassen multiplication * * @param &other the multiplier matrix * @return the result of multiplication */ MatrixStrassen<Element> Mult(const MatrixStrassen<Element>& other, int nrec=0, int pad = -1) const; /* * Multiply the matrix by a vector whose elements are all 1's. This causes the elements of each * row of the matrix to be added and placed into the corresponding position in the output vector. */ MatrixStrassen<Element> MultByUnityVector() const; /* * Multiply the matrix by a vector of random 1's and 0's, which is the same as adding select * elements in each row together. * Return a vector that is a rows x 1 matrix. */ MatrixStrassen<Element> MultByRandomVector(std::vector<int> ranvec) const; /** * Serialize the object into a Serialized * @param serObj is used to store the serialized result. It MUST be a rapidjson Object (SetObject()); * @return true if successfully serialized */ bool Serialize(Serialized* serObj) const; /** * Populate the object from the deserialization of the Serialized * @param serObj contains the serialized object * @return true on success */ bool Deserialize(const Serialized& serObj); private: struct MatDescriptor { int lda; int nrec; int nproc; int nprocr; int nprocc; int nproc_summa; int bs; }; const int DESC_SIZE = 7; // number of ints that make up a MatDescriptor const int rank=0, base=0; mutable data_t data; size_t rows; mutable int rowpad = 0; size_t cols; mutable int colpad = 0; alloc_func allocZero; mutable char *pattern = NULL; mutable int numAdd = 0; mutable int numMult = 0; mutable int numSub = 0; mutable MatDescriptor desc; mutable unique_ptr<Element> zeroUniquePtr = allocZero(); mutable int NUM_THREADS = 1; void multiplyInternalCAPS( it_lineardata_t A, it_lineardata_t B, it_lineardata_t C, MatDescriptor desc, it_lineardata_t work ) const; void strassenDFSCAPS( it_lineardata_t A, it_lineardata_t B, it_lineardata_t C, MatDescriptor desc, it_lineardata_t workPassThrough ) const; void block_multiplyCAPS( it_lineardata_t A, it_lineardata_t B, it_lineardata_t C, MatDescriptor d, it_lineardata_t workPassThrough ) const; void LinearizeDataCAPS(lineardata_t *lineardataPtr) const; void UnlinearizeDataCAPS(lineardata_t *lineardataPtr) const; int getRank() const; void verifyDescriptor( MatDescriptor desc ); long long numEntriesPerProc( MatDescriptor desc ) const; //deep copy of data - used for copy constructor void deepCopyData(data_t const& src); void getData(const data_t &Adata, const data_t &Bdata, const data_t &Cdata, int row, int inner, int col) const; void accessUniquePtrCAPS(it_lineardata_t ptr, Element val) const; void smartSubtractionCAPS(it_lineardata_t result, it_lineardata_t A, it_lineardata_t B) const; void smartAdditionCAPS(it_lineardata_t result, it_lineardata_t A, it_lineardata_t B) const; void addMatricesCAPS( int numEntries, it_lineardata_t C, it_lineardata_t A, it_lineardata_t B ) const; void addSubMatricesCAPS(int numEntries, it_lineardata_t T1, it_lineardata_t S11, it_lineardata_t S12, it_lineardata_t T2, it_lineardata_t S21, it_lineardata_t S22 ) const; void subMatricesCAPS( int numEntries, it_lineardata_t C, it_lineardata_t A, it_lineardata_t B ) const; void tripleAddMatricesCAPS(int numEntries, it_lineardata_t T1, it_lineardata_t S11, it_lineardata_t S12, it_lineardata_t T2, it_lineardata_t S21, it_lineardata_t S22, it_lineardata_t T3, it_lineardata_t S31, it_lineardata_t S32) const; void tripleSubMatricesCAPS(int numEntries, it_lineardata_t T1, it_lineardata_t S11, it_lineardata_t S12, it_lineardata_t T2, it_lineardata_t S21, it_lineardata_t S22, it_lineardata_t T3, it_lineardata_t S31, it_lineardata_t S32) const ; void distributeFrom1ProcCAPS( MatDescriptor desc, it_lineardata_t O, it_lineardata_t I ) const; void collectTo1ProcCAPS( MatDescriptor desc, it_lineardata_t O, it_lineardata_t I ) const; void sendBlockCAPS( int rank, int target, it_lineardata_t O, int bs, int source, it_lineardata_t I, int ldi ) const; void receiveBlockCAPS( int rank, int target, it_lineardata_t O, int bs, int source, it_lineardata_t I, int ldo ) const; void distributeFrom1ProcRecCAPS( MatDescriptor desc, it_lineardata_t O, it_lineardata_t I, int ldi ) const; void collectTo1ProcRecCAPS( MatDescriptor desc, it_lineardata_t O, it_lineardata_t I, int ldo ) const; }; /** * Operator for scalar multiplication of matrix * * @param &e element * @param &M matrix * @return the resulting matrix */ template<class Element> inline MatrixStrassen<Element> operator*(Element const& e, MatrixStrassen<Element> const& M) { return M.ScalarMult(e); } /** * Generates a matrix of rotations. See pages 7-8 of https://eprint.iacr.org/2013/297 * * @param &inMat the matrix of power-of-2 cyclotomic ring elements to be rotated * @return the resulting matrix of big binary integers */ inline MatrixStrassen<BigInteger> Rotate(MatrixStrassen<Poly> const& inMat); /** * Each element becomes a square matrix with columns of that element's * rotations in coefficient form. See pages 7-8 of https://eprint.iacr.org/2013/297 * * @param &inMat the matrix of power-of-2 cyclotomic ring elements to be rotated * @return the resulting matrix of big binary integers */ inline MatrixStrassen<BigVector> RotateVecResult(MatrixStrassen<Poly> const& inMat); /** * Stream output operator * * @param &os stream * @param &m matrix to be outputted * @return the chained stream */ template<class Element> inline std::ostream& operator<<(std::ostream& os, const MatrixStrassen<Element>& m); /** * Gives the Choleshky decomposition of the input matrix. * The assumption is that covariance matrix does not have large coefficients because it is formed by * discrete gaussians e and s; this implies int32_t can be used * This algorithm can be further improved - see the Darmstadt paper section 4.4 * http://eprint.iacr.org/2013/297.pdf * * @param &input the matrix for which the Cholesky decomposition is to be computed * @return the resulting matrix of floating-point numbers */ inline MatrixStrassen<double> Cholesky(const MatrixStrassen<int32_t> &input); /** * Convert a matrix of integers from BigInteger to int32_t * Convert from Z_q to [-q/2, q/2] * * @param &input the input matrix * @param &modulus the ring modulus * @return the resulting matrix of int32_t */ inline MatrixStrassen<int32_t> ConvertToInt32(const MatrixStrassen<BigInteger> &input, const BigInteger& modulus); /** * Convert a matrix of BigVector to int32_t * Convert from Z_q to [-q/2, q/2] * * @param &input the input matrix * @param &modulus the ring modulus * @return the resulting matrix of int32_t */ inline MatrixStrassen<int32_t> ConvertToInt32(const MatrixStrassen<BigVector> &input, const BigInteger& modulus); /** * Split a vector of int32_t into a vector of ring elements with ring dimension n * * @param &other the input matrix * @param &n the ring dimension * @param &params Poly element params * @return the resulting matrix of Poly */ inline MatrixStrassen<Poly> SplitInt32IntoPolyElements(MatrixStrassen<int32_t> const& other, size_t n, const shared_ptr<ILParams> params); /** * Another method for splitting a vector of int32_t into a vector of ring elements with ring dimension n * * @param &other the input matrix * @param &n the ring dimension * @param &params Poly element params * @return the resulting matrix of Poly */ inline MatrixStrassen<Poly> SplitInt32AltIntoPolyElements(MatrixStrassen<int32_t> const& other, size_t n, const shared_ptr<ILParams> params); } #endif // LBCRYPTO_MATH_MATRIXSTRASSEN_H
GB_binop__isne_uint16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__isne_uint16) // A.*B function (eWiseMult): GB (_AemultB_08__isne_uint16) // A.*B function (eWiseMult): GB (_AemultB_02__isne_uint16) // A.*B function (eWiseMult): GB (_AemultB_04__isne_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isne_uint16) // A*D function (colscale): GB (_AxD__isne_uint16) // D*A function (rowscale): GB (_DxB__isne_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__isne_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__isne_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isne_uint16) // C=scalar+B GB (_bind1st__isne_uint16) // C=scalar+B' GB (_bind1st_tran__isne_uint16) // C=A+scalar GB (_bind2nd__isne_uint16) // C=A'+scalar GB (_bind2nd_tran__isne_uint16) // C type: uint16_t // A type: uint16_t // B,b type: uint16_t // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_t #define GB_CTYPE \ uint16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint16_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint16_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (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_ISNE || GxB_NO_UINT16 || GxB_NO_ISNE_UINT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__isne_uint16) ( 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__isne_uint16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__isne_uint16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint16_t uint16_t bwork = (*((uint16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isne_uint16) ( 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 uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isne_uint16) ( 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 uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isne_uint16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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__isne_uint16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__isne_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__isne_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__isne_uint16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__isne_uint16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint16_t bij = GBX (Bx, p, false) ; Cx [p] = (x != bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isne_uint16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint16_t aij = GBX (Ax, p, false) ; Cx [p] = (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) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__isne_uint16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__isne_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
morn_tensor.c
/* Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com> Licensed under the Apache License, Version 2.0; 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 "morn_tensor.h" struct HandleTensorCreate { MTensor *tns; MChain *property; int64_t reserve[8]; int writeable; int batch; int size; float **data; MMemory *memory; float **backup_data; MMemory *backup_memory; }; #define HASH_TensorCreate 0x6b6cf658 void endTensorCreate(struct HandleTensorCreate *handle) { mException((handle->tns ==NULL),EXIT,"invalid tensor"); if(handle->property!=NULL) mChainRelease(handle->property); if(handle->data !=NULL) mFree(handle->data); if(handle->memory !=NULL) mMemoryRelease(handle->memory); if(handle->backup_data !=NULL) mFree(handle->backup_data); if(handle->backup_memory!=NULL) mMemoryRelease(handle->backup_memory); memset(handle->tns,0,sizeof(MTensor)); // mFree(((MList **)(handle->tns))-1); } MTensor *TensorCreate(int batch,int channel,int height,int width,float **data,int device) { MTensor *tns = (MTensor *)ObjectAlloc(sizeof(MTensor)); MHandle *hdl=mHandle(tns,TensorCreate); struct HandleTensorCreate *handle = (struct HandleTensorCreate *)(hdl->handle); handle->tns = tns; if(batch <0) {batch = 0; } tns->batch = batch; if(channel<0) {channel= 0; } tns->channel= channel; if(height <0) {height = 0; } tns->height = height; if(width <0) {width = 0; } tns->width = width; if(device <0) {device = MORN_HOST;} tns->device = MORN_HOST; int size = channel*height*width; if((batch==0)||(size == 0)) { mException((!INVALID_POINTER(data)),EXIT,"invalid input"); return tns; } size = size+8; handle->batch = batch; handle->data = (float **)mMalloc(batch*sizeof(float *)); tns->data = handle->data; if(!INVALID_POINTER(data)) { handle->size = 0; memcpy(handle->data,data,batch*sizeof(float *)); return tns; } handle->size= size; handle->memory = mMemoryCreate(batch,size*sizeof(float),device); void ***idx = malloc(batch*sizeof(void **)); for(int i=0;i<batch;i++) idx[i]=(void **)(&(handle->data[i])); mMemoryIndex(handle->memory,1,size*sizeof(float),idx,batch); free(idx); mPropertyFunction(tns,"device",mornMemoryDevice,handle->memory); for(int b=0;b<batch;b++) tns->data[b][channel*height*width]=1.0f; return tns; } void mTensorRelease(MTensor *tns) { ObjectFree(tns); } MMemoryBlock *mTensorMemory(MTensor *tns,int batch) { int size = tns->channel*tns->height*tns->width+8; float *data = tns->data[batch]; struct HandleTensorCreate *handle = (struct HandleTensorCreate *)(ObjHandle(tns,0)->handle); if(handle->memory == NULL) { handle->memory = mMemoryCreate(batch,size*sizeof(float),MORN_HOST); mPropertyFunction(tns,"device",mornMemoryDevice,handle->memory); } MMemoryBlock *mem = handle->memory->data[batch]; if(mem->size<size) { void ***idx = malloc(batch*sizeof(void **)); for(int i=0;i<batch;i++) idx[i]=(void **)(&(handle->data[i])); mMemoryIndex(handle->memory,1,size*sizeof(float),idx,batch); free(idx); } if(mem->data!=data) memcpy(mem->data,data,size*sizeof(float)); return mem; } void TensorRedefine(MTensor *tns,int batch,int channel,int height,int width,float **data,int device) { mException((INVALID_POINTER(tns)),EXIT,"invalid input"); if(batch <= 0) batch = tns->batch; if(channel<= 0) channel= tns->channel; if(height <= 0) height = tns->height; if(width <= 0) width = tns->width; if(INVALID_POINTER(data)) data=tns->data; int size = channel*height*width+8; if((batch!=tns->batch)||(channel!=tns->channel)||(height!=tns->height)||(width!=tns->width)) mHandleReset(tns); int same_size = (batch<=tns->batch)&&(size<tns->channel*tns->height*tns->width)&&(data==tns->data); tns->batch=batch; tns->height=height; tns->width=width; tns->channel=channel; if(same_size&&(data==NULL)) goto tensor_redefine_end; if(same_size&&((device<0)||(device==mMemoryBlock(data[0])->device))) goto tensor_redefine_end; struct HandleTensorCreate *handle = (struct HandleTensorCreate *)(ObjHandle(tns,0)->handle); if(device<0) { if((data!=tns->data)&&(data!=NULL)) device=mMemoryBlock(data[0])->device; } if((data!=tns->data)&&(data!=NULL)) { for(int bc=0;bc<batch;bc++) mException(mMemoryBlock(data[bc])->device!=device,EXIT,"invalid data device"); } if((batch<=handle->batch)&&(size<=handle->size)&&(data==handle->data)) return; // int flag = (tns->batch)&&(tns->channel)&&(tns->height)&&(tns->width); // mException(reuse&&flag&&(handle->size==0),EXIT,"invalid redefine"); if((batch==0)||(size<=8)) { mException((data!=tns->data),EXIT,"invalid input"); tns->data=NULL; goto tensor_redefine_end; } if(batch>handle->batch){if(handle->data != NULL) {free(handle->data);}handle->data=NULL;} if(handle->data==NULL) { handle->data = (float **)malloc(batch*sizeof(float *)); handle->batch = batch; } if(data!=tns->data) { memcpy(handle->data,data,batch*sizeof(float *)); tns->data = handle->data; if(handle->backup_data !=NULL) mFree(handle->backup_data); if(handle->backup_memory!=NULL) mMemoryRelease(handle->backup_memory); goto tensor_redefine_end; } if(handle->memory == NULL) { handle->memory = mMemoryCreate(batch,size*sizeof(float),device); mPropertyFunction(tns,"device",mornMemoryDevice,handle->memory); } else mMemoryRedefine(handle->memory,batch,size*sizeof(float),device); void ***idx = malloc(batch*sizeof(void **)); for(int i=0;i<batch;i++) idx[i]=(void **)(&(handle->data[i])); mMemoryIndex(handle->memory,1,size*sizeof(float),idx,batch); free(idx); tns->data = handle->data; handle->size = size; tensor_redefine_end: for(int b=0;b<batch;b++) tns->data[b][channel*height*width]=1.0f; } float **mTensorBackup(MTensor *tns,int batch,int cn,int height,int width) { if(batch <=0) batch =tns->batch; if(cn <=0) cn =tns->channel; if(height<=0) height=tns->height; if(width <=0) width =tns->width; int size = cn*height*width; struct HandleTensorCreate *handle = (struct HandleTensorCreate *)(ObjHandle(tns,0)->handle); if(handle->backup_data!=NULL) mFree(handle->backup_data); handle->backup_data = (float **)mMalloc(batch*sizeof(float *)); if(handle->backup_memory == NULL) handle->backup_memory = mMemoryCreate(batch,size*sizeof(float),tns->device); else mMemoryRedefine(handle->backup_memory,batch,size*sizeof(float),tns->device); for(int i=0;i<batch;i++) handle->backup_data[i] = (float *)(handle->backup_memory->data[i]); return (handle->backup_data); } void MemCopy(void *dst,int dst_dev,void *src,int src_dev,int size); void mTensorCopy(MTensor *src,MTensor *dst,int device) { mException(INVALID_POINTER(src),EXIT,"invalid input source tensor"); mException(INVALID_POINTER(dst)&&(device<0),EXIT,"invalid input device"); if(device<0) device=dst->device; float **dst_data; int flag = (INVALID_POINTER(dst))||(dst==src); if(flag) {if(device==src->device){return;} dst_data=mTensorBackup(src,DFLT,DFLT,DFLT,DFLT);} else {if(device!=dst->device){mTensorRedefine(dst,DFLT,DFLT,DFLT,DFLT,NULL,device);} dst_data=dst->data;} // int size = src->channel*src->height*src->width; // for(int i=0;i<src->batch;i++) // MemCopy(dst_data[i],device,src->data[i],src->device,size*sizeof(float)); if(flag) mTensorRedefine(src,DFLT,DFLT,DFLT,DFLT,dst_data,device); } /* void mTensorAdd(MTensor *src1,MTensor *src2,MTensor *dst) { int i; mException((INVALID_TENSOR(src1)||INVALID_TENSOR(src2)),EXIT,"invalid input source"); int batch = src1->batch; mException((src2->batch!=batch)&&(src2->batch!=1),EXIT,"invalid input source"); mException((batch>1)&&(src2->batch==1)&&(dst==src2),EXIT,"invalid input"); int channel = src1->channel; int height = src1->height; int width = src1->width; mException((src2->channel!=channel)||(src2->height!=height)||(src2->width!=width),EXIT,"invalid input source"); int size = channel*height*width; if(dst==NULL) dst = src1; if((dst!=src1)&&(dst!=src2)) mTensorRedefine(dst,batch,channel,height,width,dst->data); for(int b=0;b<batch;b++) { float *data1 = src1->data[b]; float *data2 = (src2->batch>1)?src2->data[b]:src2->data[0]; float *data = dst ->data[b]; #pragma omp parallel for for(i=0;i<size;i++) data[i] = data1[i]+data2[i]; } } void mTensorSub(MTensor *src1,MTensor *src2,MTensor *dst) { int i; mException((INVALID_TENSOR(src1)||INVALID_TENSOR(src2)),EXIT,"invalid input source"); int batch = src1->batch; mException((src2->batch!=batch)&&(src2->batch!=1),EXIT,"invalid input source"); mException((batch>1)&&(src2->batch==1)&&(dst==src2),EXIT,"invalid input"); int channel = src1->channel; int height = src1->height; int width = src1->width; mException((src2->channel!=channel)||(src2->height!=height)||(src2->width!=width),EXIT,"invalid input source"); int size = channel*height*width; if(dst==NULL) dst = src1; if((dst!=src1)&&(dst!=src2)) mTensorRedefine(dst,batch,channel,height,width,dst->data); for(int b=0;b<batch;b++) { float *data1 = src1->data[b]; float *data2 = (src2->batch>1)?src2->data[b]:src2->data[0]; float *data = dst ->data[b]; #pragma omp parallel for for(i=0;i<size;i++) data[i] = data1[i]-data2[i]; } } void mTensorScalarMul(MTensor *src1,MTensor *src2,MTensor *dst) { int i; mException((INVALID_TENSOR(src1)||INVALID_TENSOR(src2)),EXIT,"invalid input source"); int batch = src1->batch; mException((src2->batch!=batch)&&(src2->batch!=1),EXIT,"invalid input source"); mException((batch>1)&&(src2->batch==1)&&(dst==src2),EXIT,"invalid input"); int channel = src1->channel; int height = src1->height; int width = src1->width; mException((src2->channel!=channel)||(src2->height!=height)||(src2->width!=width),EXIT,"invalid input source"); int size = channel*height*width; if(dst==NULL) dst = src1; if((dst!=src1)&&(dst!=src2)) mTensorRedefine(dst,batch,channel,height,width,dst->data); for(int b=0;b<batch;b++) { float *data1 = src1->data[b]; float *data2 = (src2->batch>1)?src2->data[b]:src2->data[0]; float *data = dst ->data[b]; #pragma omp parallel for for(i=0;i<size;i++) data[i] = data1[i]*data2[i]; } } void mTensorScalarDiv(MTensor *src1,MTensor *src2,MTensor *dst) { int i; mException((INVALID_TENSOR(src1)||INVALID_TENSOR(src2)),EXIT,"invalid input source"); int batch = src1->batch; mException((src2->batch!=batch)&&(src2->batch!=1),EXIT,"invalid input source"); mException((batch>1)&&(src2->batch==1)&&(dst==src2),EXIT,"invalid input"); int channel = src1->channel; int height = src1->height; int width = src1->width; mException((src2->channel!=channel)||(src2->height!=height)||(src2->width!=width),EXIT,"invalid input source"); int size = channel*height*width; if(dst==NULL) dst = src1; if((dst!=src1)&&(dst!=src2)) mTensorRedefine(dst,batch,channel,height,width,dst->data); for(int b=0;b<batch;b++) { float *data1 = src1->data[b]; float *data2 = (src2->batch>1)?src2->data[b]:src2->data[0]; float *data = dst ->data[b]; #pragma omp parallel for for(i=0;i<size;i++) data[i] = data1[i]/data2[i]; } } */ void mTensorOperate(MTensor *src,MTensor *dst, float (*func)(float)) { int i; mException(INVALID_TENSOR(src),EXIT,"invalid input source"); if(dst==NULL) dst = src; if(dst!=src ) mTensorRedefine(dst,src->batch,src->channel,src->height,src->width,dst->data); int size = src->channel*src->height*src->width; for(int b=0;b<src->batch;b++) { #pragma omp parallel for for(i=0;i<size;i++) dst->data[b][i] = func(src->data[b][i]); } }
DRB012-minusminus-var-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* The -- operation is not protected, causing race condition. Data race pair: numNodes2@75 vs. numNodes2@75 */ #include <stdlib.h> #include <omp.h> int main(int argc,char *argv[]) { int i; int len = 100; if (argc > 1) len = atoi(argv[1]); int numNodes = len; int numNodes2 = 0; int x[len]; #pragma omp parallel for private (i) firstprivate (len) for (i = 0; i <= len - 1; i += 1) { if (i % 2 == 0) x[i] = 5; else x[i] = - 5; } #pragma omp parallel for private (i) reduction (-:numNodes2) for (i = numNodes - 1; i >= 0; i += -1) { if (x[i] <= 0) { numNodes2--; } } printf("numNodes2 = %d\n",numNodes2); return 0; }
exercice2.c
#include <stdio.h> int main(void){ #pragma omp parallel for for (int i = 0; i < 100; ++i){ #pragma omp critical{ printf("Je suis #%d\n", i); } } return 0; }
vector.c
/*BHEADER********************************************************************** * Copyright (c) 2006 The Regents of the University of California. * Produced at the Lawrence Livermore National Laboratory. * Written by the HYPRE team. UCRL-CODE-222953. * All rights reserved. * * This file is part of HYPRE (see http://www.llnl.gov/CASC/hypre/). * Please see the COPYRIGHT_and_LICENSE file for the copyright notice, * disclaimer, contact information and the GNU Lesser General Public License. * * HYPRE is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License (as published by the Free Software * Foundation) version 2.1 dated February 1999. * * HYPRE is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the terms and conditions of the GNU General * Public License for more details. * * You should have received a copy of the GNU Lesser 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 * * $Revision: 2.8 $ ***********************************************************************EHEADER*/ /****************************************************************************** * * Member functions for hypre_Vector class. * *****************************************************************************/ #include "headers.h" #include <assert.h> /*-------------------------------------------------------------------------- * hypre_SeqVectorCreate *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorCreate( int size ) { hypre_Vector *vector; vector = hypre_CTAlloc(hypre_Vector, 1); hypre_VectorData(vector) = NULL; hypre_VectorSize(vector) = size; hypre_VectorNumVectors(vector) = 1; hypre_VectorMultiVecStorageMethod(vector) = 0; /* set defaults */ hypre_VectorOwnsData(vector) = 1; return vector; } /*-------------------------------------------------------------------------- * hypre_SeqMultiVectorCreate *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqMultiVectorCreate( int size, int num_vectors ) { hypre_Vector *vector = hypre_SeqVectorCreate(size); hypre_VectorNumVectors(vector) = num_vectors; return vector; } /*-------------------------------------------------------------------------- * hypre_SeqVectorDestroy *--------------------------------------------------------------------------*/ int hypre_SeqVectorDestroy( hypre_Vector *vector ) { int ierr=0; if (vector) { if ( hypre_VectorOwnsData(vector) ) { hypre_TFree(hypre_VectorData(vector)); } hypre_TFree(vector); } return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorInitialize *--------------------------------------------------------------------------*/ int hypre_SeqVectorInitialize( hypre_Vector *vector ) { int size = hypre_VectorSize(vector); int ierr = 0; int num_vectors = hypre_VectorNumVectors(vector); int multivec_storage_method = hypre_VectorMultiVecStorageMethod(vector); if ( ! hypre_VectorData(vector) ) hypre_VectorData(vector) = hypre_CTAlloc(double, num_vectors*size); if ( multivec_storage_method == 0 ) { hypre_VectorVectorStride(vector) = size; hypre_VectorIndexStride(vector) = 1; } else if ( multivec_storage_method == 1 ) { hypre_VectorVectorStride(vector) = 1; hypre_VectorIndexStride(vector) = num_vectors; } else ++ierr; return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorSetDataOwner *--------------------------------------------------------------------------*/ int hypre_SeqVectorSetDataOwner( hypre_Vector *vector, int owns_data ) { int ierr=0; hypre_VectorOwnsData(vector) = owns_data; return ierr; } /*-------------------------------------------------------------------------- * ReadVector *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorRead( char *file_name ) { hypre_Vector *vector; FILE *fp; double *data; int size; int j; /*---------------------------------------------------------- * Read in the data *----------------------------------------------------------*/ fp = fopen(file_name, "r"); fscanf(fp, "%d", &size); vector = hypre_SeqVectorCreate(size); hypre_SeqVectorInitialize(vector); data = hypre_VectorData(vector); for (j = 0; j < size; j++) { fscanf(fp, "%le", &data[j]); } fclose(fp); /* multivector code not written yet >>> */ hypre_assert( hypre_VectorNumVectors(vector) == 1 ); return vector; } /*-------------------------------------------------------------------------- * hypre_SeqVectorPrint *--------------------------------------------------------------------------*/ int hypre_SeqVectorPrint( hypre_Vector *vector, char *file_name ) { FILE *fp; double *data; int size, num_vectors, vecstride, idxstride; int i, j; int ierr = 0; num_vectors = hypre_VectorNumVectors(vector); vecstride = hypre_VectorVectorStride(vector); idxstride = hypre_VectorIndexStride(vector); /*---------------------------------------------------------- * Print in the data *----------------------------------------------------------*/ data = hypre_VectorData(vector); size = hypre_VectorSize(vector); fp = fopen(file_name, "w"); if ( hypre_VectorNumVectors(vector) == 1 ) { fprintf(fp, "%d\n", size); } else { fprintf(fp, "%d vectors of size %d\n", num_vectors, size ); } if ( num_vectors>1 ) { for ( j=0; j<num_vectors; ++j ) { fprintf(fp, "vector %d\n", j ); for (i = 0; i < size; i++) { fprintf(fp, "%.14e\n", data[ j*vecstride + i*idxstride ] ); } } } else { for (i = 0; i < size; i++) { fprintf(fp, "%.14e\n", data[i]); } } fclose(fp); return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorSetConstantValues *--------------------------------------------------------------------------*/ int hypre_SeqVectorSetConstantValues( hypre_Vector *v, double value ) { double *vector_data = hypre_VectorData(v); int size = hypre_VectorSize(v); int i; int ierr = 0; size *=hypre_VectorNumVectors(v); for (i = 0; i < size; i++) vector_data[i] = value; return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorCopy * copies data from x to y * y should have already been initialized at the same size as x *--------------------------------------------------------------------------*/ int hypre_SeqVectorCopy( hypre_Vector *x, hypre_Vector *y ) { double *x_data = hypre_VectorData(x); double *y_data = hypre_VectorData(y); int size = hypre_VectorSize(x); int i; int ierr = 0; size *=hypre_VectorNumVectors(x); for (i = 0; i < size; i++) y_data[i] = x_data[i]; return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorCloneDeep * Returns a complete copy of x - a deep copy, with its own copy of the data. *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorCloneDeep( hypre_Vector *x ) { int size = hypre_VectorSize(x); int num_vectors = hypre_VectorNumVectors(x); hypre_Vector * y = hypre_SeqMultiVectorCreate( size, num_vectors ); hypre_VectorMultiVecStorageMethod(y) = hypre_VectorMultiVecStorageMethod(x); hypre_VectorVectorStride(y) = hypre_VectorVectorStride(x); hypre_VectorIndexStride(y) = hypre_VectorIndexStride(x); hypre_SeqVectorInitialize(y); hypre_SeqVectorCopy( x, y ); return y; } /*-------------------------------------------------------------------------- * hypre_SeqVectorCloneShallow * Returns a complete copy of x - a shallow copy, pointing the data of x *--------------------------------------------------------------------------*/ hypre_Vector * hypre_SeqVectorCloneShallow( hypre_Vector *x ) { int size = hypre_VectorSize(x); int num_vectors = hypre_VectorNumVectors(x); hypre_Vector * y = hypre_SeqMultiVectorCreate( size, num_vectors ); hypre_VectorMultiVecStorageMethod(y) = hypre_VectorMultiVecStorageMethod(x); hypre_VectorVectorStride(y) = hypre_VectorVectorStride(x); hypre_VectorIndexStride(y) = hypre_VectorIndexStride(x); hypre_VectorData(y) = hypre_VectorData(x); hypre_SeqVectorSetDataOwner( y, 0 ); hypre_SeqVectorInitialize(y); return y; } /*-------------------------------------------------------------------------- * hypre_SeqVectorScale *--------------------------------------------------------------------------*/ int hypre_SeqVectorScale( double alpha, hypre_Vector *y ) { double *y_data = hypre_VectorData(y); int size = hypre_VectorSize(y); int i; int ierr = 0; size *=hypre_VectorNumVectors(y); for (i = 0; i < size; i++) y_data[i] *= alpha; return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorAxpy *--------------------------------------------------------------------------*/ int hypre_SeqVectorAxpy( double alpha, hypre_Vector *x, hypre_Vector *y ) { double *x_data = hypre_VectorData(x); double *y_data = hypre_VectorData(y); int size = hypre_VectorSize(x); int i; int ierr = 0; size *=hypre_VectorNumVectors(x); #pragma omp parallel for schedule(dynamic, size/16) //#pragma omp parallel for schedule(dynamic) for (i = 0; i < size; i++) y_data[i] += alpha * x_data[i]; return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqVectorInnerProd *--------------------------------------------------------------------------*/ double hypre_SeqVectorInnerProd( hypre_Vector *x, hypre_Vector *y ) { double *x_data = hypre_VectorData(x); double *y_data = hypre_VectorData(y); int size = hypre_VectorSize(x); int i; double result = 0.0; size *=hypre_VectorNumVectors(x); for (i = 0; i < size; i++) result += y_data[i] * x_data[i]; return result; } /*-------------------------------------------------------------------------- * hypre_VectorSumElts: * Returns the sum of all vector elements. *--------------------------------------------------------------------------*/ double hypre_VectorSumElts( hypre_Vector *vector ) { double sum = 0; double * data = hypre_VectorData( vector ); int size = hypre_VectorSize( vector ); int i; for ( i=0; i<size; ++i ) sum += data[i]; return sum; }
SceneGraphConverterOCC.h
/* -*-c++-*- IfcQuery www.ifcquery.com * MIT License Copyright (c) 2017 Fabian Gerold Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <boost/unordered/unordered_set.hpp> #include <osg/Material> #include <osg/Geode> #include <osg/CullFace> #include <osg/Point> #include <osg/Switch> #include <osgText/Text> #include <BRepAdaptor_Curve.hxx> #include <BRep_Tool.hxx> #include <BRepMesh_IncrementalMesh.hxx> #include <GCPnts_AbscissaPoint.hxx> #include <GCPnts_UniformAbscissa.hxx> #include <Geom_Line.hxx> #include <Poly.hxx> #include <TopExp.hxx> #include <TopExp_Explorer.hxx> #include <TopoDS.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Shape.hxx> #include <TopoDS_Vertex.hxx> #include <ifcpp/geometry/GeometrySettings.h> #include <ifcpp/geometry/SceneGraphUtils.h> #include <ifcpp/model/BuildingModel.h> #include <ifcpp/model/BasicTypes.h> #include <ifcpp/model/StatusCallback.h> #include <ifcpp/IFC4/include/IfcCurtainWall.h> #include <ifcpp/IFC4/include/IfcFeatureElementSubtraction.h> #include <ifcpp/IFC4/include/IfcProject.h> #include <ifcpp/IFC4/include/IfcPropertySetDefinitionSet.h> #include <ifcpp/IFC4/include/IfcRelAggregates.h> #include <ifcpp/IFC4/include/IfcRelContainedInSpatialStructure.h> #include <ifcpp/IFC4/include/IfcRelDefinesByProperties.h> #include <ifcpp/IFC4/include/IfcSpace.h> #include <ifcpp/IFC4/include/IfcWindow.h> #include "GeometryInputDataOCC.h" class ScenegraphConverterOCC : public StatusCallback { protected: std::map<int, osg::ref_ptr<osg::Switch> > m_map_entity_id_to_switch; // Map: IfcProduct ID -> scenegraph switch std::map<int, osg::ref_ptr<osg::Switch> > m_map_representation_to_switch; // Map: Representation identifier -> scenegraph switch shared_ptr<GeometrySettings> m_geom_settings; double m_recent_progress = 0; osg::ref_ptr<osg::CullFace> m_cull_back_off; osg::ref_ptr<osg::StateSet> m_glass_stateset; //\brief StateSet caching and re-use std::vector<osg::ref_ptr<osg::StateSet> > m_vec_existing_statesets; bool m_enable_stateset_caching = false; #ifdef ENABLE_OPENMP Mutex m_writelock_appearance_cache; #endif public: ScenegraphConverterOCC( shared_ptr<GeometrySettings>& geom_settings ) : m_geom_settings( geom_settings ) { m_cull_back_off = new osg::CullFace( osg::CullFace::BACK ); m_glass_stateset = new osg::StateSet(); m_glass_stateset->setMode( GL_BLEND, osg::StateAttribute::ON ); m_glass_stateset->setRenderingHint( osg::StateSet::TRANSPARENT_BIN ); } virtual ~ScenegraphConverterOCC() {} // after calling convertToOSG, the OSG Switches are in the map returned by this method const std::map<int, osg::ref_ptr<osg::Switch> >& getMapIdSwitch() { return m_map_entity_id_to_switch; } struct RenderOptions { RenderOptions(){} RenderOptions( osg::Vec4f color, double distance_between_points_in_mm = 0.5, bool create_points_along_straight_line = false ) { m_color = color; m_color_set = true; m_distance_between_points_in_mm = distance_between_points_in_mm; m_create_points_along_straight_line = create_points_along_straight_line; } osg::Vec4f m_color; bool m_color_set = false; double m_distance_between_points_in_mm = 0.5; bool m_create_points_along_straight_line = false; }; void clearInputCache() { m_map_entity_id_to_switch.clear(); m_map_representation_to_switch.clear(); m_vec_existing_statesets.clear(); } static void getEdgePoints( const TopoDS_Edge& edge, osg::Vec3Array* vertices, const RenderOptions& render_options ) { Standard_Real first = 0; Standard_Real last = 1; Handle( Geom_Curve ) c = BRep_Tool::Curve( edge, first, last ); bool discretize_points_on_straight_line = render_options.m_create_points_along_straight_line; if( c->DynamicType() == STANDARD_TYPE( Geom_Line ) && !discretize_points_on_straight_line ) { // just straight line const TopoDS_Vertex& v1 = TopExp::FirstVertex( edge ); const TopoDS_Vertex& v2 = TopExp::LastVertex( edge ); gp_Pnt point1 = BRep_Tool::Pnt( v1 ); gp_Pnt point2 = BRep_Tool::Pnt( v2 ); vertices->push_back( osg::Vec3d( point1.X(), point1.Y(), point1.Z() ) ); vertices->push_back( osg::Vec3d( point2.X(), point2.Y(), point2.Z() ) ); } else { double param_range = last - first; BRepAdaptor_Curve curve_adaptor(edge); //curve_adaptor.Initialize( edge ); #ifdef _DEBUG const TopoDS_Vertex& v1 = TopExp::FirstVertex( edge ); const TopoDS_Vertex& v2 = TopExp::LastVertex( edge ); gp_Pnt point1 = BRep_Tool::Pnt( v1 ); gp_Pnt point2 = BRep_Tool::Pnt( v2 ); #endif Standard_Real length_of_edge = GCPnts_AbscissaPoint::Length( curve_adaptor ); double distance = render_options.m_distance_between_points_in_mm; double num_points = 40*param_range/(2.0*M_PI); distance = length_of_edge/num_points; GCPnts_UniformAbscissa uniform_abscissa; uniform_abscissa.Initialize( curve_adaptor, distance ); if( uniform_abscissa.IsDone() ) { int nb_points = uniform_abscissa.NbPoints(); for( int i = 0; i < nb_points; ++i ) { Standard_Real parameter = uniform_abscissa.Parameter( i + 1 ); gp_Pnt pnt = curve_adaptor.Value( parameter ); vertices->push_back( osg::Vec3d( pnt.X(), pnt.Y(), pnt.Z() ) ); if( i > 0 && i < nb_points - 1 ) { vertices->push_back( osg::Vec3d( pnt.X(), pnt.Y(), pnt.Z() ) ); } } if( vertices->size()> 0 ) { if( vertices->size()%2 != 0 ) { vertices->push_back( vertices->back() ); } } } } } static void drawShape( const TopoDS_Shape& shape, osg::Geode* parent_geode, const RenderOptions& render_options ) { if( shape.IsNull() ) { return; } osg::ref_ptr<osg::Vec3Array> vertices_lines = new osg::Vec3Array(); osg::ref_ptr<osg::Vec3Array> vertices_tri_storage = new osg::Vec3Array(); osg::ref_ptr<osg::Vec3Array> vertices_tri = new osg::Vec3Array(); osg::ref_ptr<osg::Vec3Array> normals_tri = new osg::Vec3Array(); osg::ref_ptr<osg::Vec3Array> normals_tri_storage = new osg::Vec3Array(); osg::ref_ptr<osg::Vec3Array> vertices_quad; osg::ref_ptr<osg::Vec3Array> normals_quad; #ifdef _DEBUG osg::ref_ptr<osg::Vec3Array> vertices_triangle_edges = new osg::Vec3Array(); #endif TopAbs_ShapeEnum shape_type = shape.ShapeType(); if( shape_type == TopAbs_WIRE || shape_type == TopAbs_EDGE || shape_type == TopAbs_VERTEX ) { TopExp_Explorer Ex; for( Ex.Init( shape, TopAbs_EDGE ); Ex.More(); Ex.Next() ) { TopoDS_Edge edge = TopoDS::Edge( Ex.Current() ); getEdgePoints( edge, vertices_lines, render_options ); } } else { Standard_Real linear_tolerance = 0.06*0.001; // for [m] Standard_Real angular_tolerance = 0.5; bool is_relative = false; BRepMesh_IncrementalMesh incremental_mesh( shape, linear_tolerance, is_relative, angular_tolerance ); TopExp_Explorer shape_explorer( shape, TopAbs_FACE ); for( ; shape_explorer.More(); shape_explorer.Next() ) { const TopoDS_Face& face = TopoDS::Face( shape_explorer.Current() ); TopLoc_Location L = TopLoc_Location(); const Handle( Poly_Triangulation )& poly_triangulation = BRep_Tool::Triangulation( face, L ); if( poly_triangulation.IsNull() ) { continue; } const gp_Trsf & face_trsf = L.Transformation(); Poly::ComputeNormals( poly_triangulation ); const TColgp_Array1OfPnt& triang_vertices = poly_triangulation->Nodes(); const TShort_Array1OfShortReal& triang_normals = poly_triangulation->Normals(); const Poly_Array1OfTriangle& triangles = poly_triangulation->Triangles(); // Number of nodes in the triangulation int num_vertices = poly_triangulation->Nodes().Length(); if( num_vertices*3 != triang_normals.Length() ) { std::cout << "Different number of normals and vertices\n"; return; } if( !vertices_tri_storage ) { vertices_tri_storage = new osg::Vec3Array(); } size_t offset_vertex_storage = vertices_tri_storage->size(); if( !normals_tri_storage ) { normals_tri_storage = new osg::Vec3Array(); } //size_t offset_normals_storage = normals_tri_storage->size(); // Get each vertex index, checking common vertices between shapes for( int i = 0; i < num_vertices; i++ ) { gp_Pnt triang_point = triang_vertices.Value( i+1 ); gp_Vec normal( triang_normals.Value( i*3 + 1 ), triang_normals.Value( i*3 + 2 ), triang_normals.Value( i*3 + 3 ) ); if( face_trsf.Form() != gp_Identity ) { triang_point.Transform( face_trsf ); normal.Transform( face_trsf ); } double x = std::round( triang_point.X()*10.0 )*0.1; double y = std::round( triang_point.Y()*10.0 )*0.1; double z = std::round( triang_point.Z()*10.0 )*0.1; vertices_tri_storage->push_back( osg::Vec3d( x, y, z ) ); normals_tri_storage->push_back( osg::Vec3d( normal.X(), normal.Y(), normal.Z() ) ); } if( !vertices_tri ) { vertices_tri = new osg::Vec3Array(); } if( !normals_tri ) { normals_tri = new osg::Vec3Array(); } int num_stored_vertices = vertices_tri_storage->size(); for( auto it = triangles.begin(); it != triangles.end(); ++it ) { const Poly_Triangle& triang = *it; int idx_tri1, idx_tri2, idx_tri3; triang.Get( idx_tri1, idx_tri2, idx_tri3 ); int idx1 = offset_vertex_storage + idx_tri1 - 1; int idx2 = offset_vertex_storage + idx_tri2 - 1; int idx3 = offset_vertex_storage + idx_tri3 - 1; if( idx1 >= num_stored_vertices || idx2 >= num_stored_vertices || idx3 >= num_stored_vertices ) { std::cout << "idx > num_stored_vertices" << std::endl; continue; } osg::Vec3 v1 = vertices_tri_storage->at( idx1 ); osg::Vec3 v2 = vertices_tri_storage->at( idx2 ); osg::Vec3 v3 = vertices_tri_storage->at( idx3 ); vertices_tri->push_back( v1 ); vertices_tri->push_back( v2 ); vertices_tri->push_back( v3 ); osg::Vec3 n1 = normals_tri_storage->at( idx1 ); osg::Vec3 n2 = normals_tri_storage->at( idx2 ); osg::Vec3 n3 = normals_tri_storage->at( idx3 ); normals_tri->push_back( n1 ); normals_tri->push_back( n2 ); normals_tri->push_back( n3 ); } } } if( vertices_tri->size() > 0 ) { if( vertices_tri->size() == normals_tri->size() ) { osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry(); geometry->setVertexArray( vertices_tri ); geometry->setNormalArray( normals_tri ); normals_tri->setBinding( osg::Array::BIND_PER_VERTEX ); if( render_options.m_color_set ) { osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(); colors->push_back( render_options.m_color ); colors->setBinding( osg::Array::BIND_OVERALL ); geometry->setColorArray( colors ); } geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::TRIANGLES, 0, vertices_tri->size() ) ); parent_geode->addDrawable( geometry ); #ifdef DEBUG_DRAW_NORMALS osg::ref_ptr<osg::Vec3Array> vertices_normals = new osg::Vec3Array(); for( size_t i = 0; i < vertices_tri->size(); ++i ) { osg::Vec3f& vertex_vec = vertices_tri->at( i );// [i]; osg::Vec3f& normal_vec = normals_tri->at( i ); vertices_normals->push_back( osg::Vec3f( vertex_vec.x(), vertex_vec.y(), vertex_vec.z() ) ); vertices_normals->push_back( osg::Vec3f( vertex_vec.x(), vertex_vec.y(), vertex_vec.z() ) + normal_vec ); } osg::ref_ptr<osg::Vec4Array> colors_normals = new osg::Vec4Array(); colors_normals->resize( vertices_normals->size(), osg::Vec4f( 0.4f, 0.7f, 0.4f, 1.f ) ); osg::ref_ptr<osg::Geometry> geometry_normals = new osg::Geometry(); geometry_normals->setVertexArray( vertices_normals ); geometry_normals->setColorArray( colors_normals ); colors_normals->setBinding( osg::Array::BIND_PER_VERTEX ); geometry_normals->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); geometry_normals->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINES, 0, vertices_normals->size() ) ); parent_geode->addDrawable( geometry_normals ); #endif } } if( vertices_quad ) { if( vertices_quad->size() > 0 ) { osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry(); geometry->setVertexArray( vertices_quad ); if( normals_quad ) { normals_quad->setBinding( osg::Array::BIND_PER_VERTEX ); geometry->setNormalArray( normals_quad ); } if( render_options.m_color_set ) { osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(); colors->push_back( render_options.m_color ); colors->setBinding( osg::Array::BIND_OVERALL ); geometry->setColorArray( colors ); } geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::QUADS, 0, vertices_quad->size() ) ); parent_geode->addDrawable( geometry ); } } if( vertices_lines->size() > 0 ) { osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry(); geometry->setVertexArray( vertices_lines ); if( render_options.m_color_set ) { osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(); colors->push_back( render_options.m_color ); colors->setBinding( osg::Array::BIND_OVERALL ); geometry->setColorArray( colors ); } geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINES, 0, vertices_lines->size() ) ); geometry->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); parent_geode->addDrawable( geometry ); } #ifdef _DEBUG if( vertices_triangle_edges->size() > 0 && false ) { { osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry(); geometry->setVertexArray( vertices_triangle_edges ); osg::ref_ptr<osg::Vec4Array> colors = new osg::Vec4Array(); colors->resize( vertices_triangle_edges->size(), osg::Vec4f( 0.6f, 0.7f, 0.6f, 0.1f ) ); colors->setBinding( osg::Array::BIND_PER_VERTEX ); geometry->setColorArray( colors ); geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::LINES, 0, vertices_triangle_edges->size() ) ); parent_geode->addDrawable( geometry ); geometry->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); } } #endif } void applyAppearancesToGroup( const std::vector<shared_ptr<AppearanceData> >& vec_product_appearances, osg::Group* grp ) { for( size_t ii = 0; ii < vec_product_appearances.size(); ++ii ) { const shared_ptr<AppearanceData>& appearance = vec_product_appearances[ii]; if( !appearance ) { continue; } AppearanceData::GeometryTypeEnum geom_type = appearance->m_apply_to_geometry_type; if( geom_type == AppearanceData::GEOM_TYPE_SURFACE || geom_type == AppearanceData::GEOM_TYPE_ANY ) { osg::StateSet* item_stateset = convertToOSGStateSet( appearance ); if( item_stateset != nullptr ) { osg::StateSet* existing_item_stateset = grp->getStateSet(); if( existing_item_stateset ) { if( existing_item_stateset != item_stateset ) { existing_item_stateset->merge( *item_stateset ); } } else { grp->setStateSet( item_stateset ); } } } else if( geom_type == AppearanceData::GEOM_TYPE_CURVE ) { //osg::Vec4f color_lines( appearance->m_color_ambient.m_r, appearance->m_color_ambient.m_g, appearance->m_color_ambient.m_b, appearance->m_color_ambient.m_a ); //GeomUtils::setColorToLines( grp, color_lines ); } } } //\brief method convertProductShapeToOSG: creates geometry objects from an IfcProduct object // caution: when using OpenMP, this method runs in parallel threads, so every write access to member variables needs a write lock void convertProductShapeToOSG( shared_ptr<ProductShapeDataOCC>& product_shape, std::map<int, osg::ref_ptr<osg::Switch> >& map_representation_switches ) { if( product_shape->m_ifc_object_definition.expired() ) { return; } RenderOptions render_options; shared_ptr<IfcObjectDefinition> ifc_object_def( product_shape->m_ifc_object_definition ); shared_ptr<IfcProduct> ifc_product = dynamic_pointer_cast<IfcProduct>(ifc_object_def); if( !ifc_product ) { return; } const int product_id = ifc_product->m_entity_id; std::stringstream strs_product_switch_name; strs_product_switch_name << "#" << product_id << "=" << ifc_product->className() << " group"; // create OSG objects std::vector<shared_ptr<RepresentationDataOCC> >& vec_product_representations = product_shape->m_vec_representations; for( size_t ii_representation = 0; ii_representation < vec_product_representations.size(); ++ii_representation ) { const shared_ptr<RepresentationDataOCC>& product_representation_data = vec_product_representations[ii_representation]; if( product_representation_data->m_ifc_representation.expired() ) { continue; } shared_ptr<IfcRepresentation> ifc_representation( product_representation_data->m_ifc_representation ); const int representation_id = ifc_representation->m_entity_id; osg::ref_ptr<osg::Switch> representation_switch = new osg::Switch(); #ifdef _DEBUG std::stringstream strs_representation_name; strs_representation_name << strs_product_switch_name.str().c_str() << ", representation " << ii_representation; representation_switch->setName( strs_representation_name.str().c_str() ); #endif const std::vector<shared_ptr<ItemShapeDataOCC> >& product_items = product_representation_data->m_vec_item_data; for( size_t i_item = 0; i_item < product_items.size(); ++i_item ) { const shared_ptr<ItemShapeDataOCC>& item_input_data = product_items[i_item]; osg::ref_ptr<osg::Group> item_group = new osg::Group(); if( !item_group ) { throw OutOfMemoryException( __FUNC__ ); } #ifdef _DEBUG std::stringstream strs_item_name; strs_item_name << strs_representation_name.str().c_str() << ", item " << i_item; item_group->setName( strs_item_name.str().c_str() ); #endif // create shape for open shells for( size_t ii_shapes = 0; ii_shapes < item_input_data->getShapes().size(); ++ii_shapes ) { const TopoDS_Shape& item_shape = item_input_data->getShapes()[ii_shapes]; osg::ref_ptr<osg::Geode> geode = new osg::Geode(); if( !geode ) { throw OutOfMemoryException( __FUNC__ ); } drawShape( item_shape, geode, render_options ); // disable back face culling for open meshes geode->getOrCreateStateSet()->setAttributeAndModes( m_cull_back_off.get(), osg::StateAttribute::OFF ); if( geode->getNumDrawables() > 0 ) { item_group->addChild( geode ); #ifdef _DEBUG std::stringstream strs_item_shape_name; strs_item_shape_name << strs_item_name.str().c_str() << ", open shape " << ii_shapes; geode->setName( strs_item_shape_name.str().c_str() ); #endif } } // create shape for points const std::vector<TopoDS_Vertex>& vertex_points = item_input_data->getVertexPoints(); if( vertex_points.size() > 0 ) { osg::ref_ptr<osg::Geode> geode = new osg::Geode(); if( !geode ) { throw OutOfMemoryException( __FUNC__ ); } osg::ref_ptr<osg::Vec3Array> vertices = new osg::Vec3Array(); for( size_t ii_vertex_point = 0; ii_vertex_point < vertex_points.size(); ++ii_vertex_point ) { const TopoDS_Vertex& vertex_input = vertex_points[ii_vertex_point]; if( !vertex_input.IsNull() ) { gp_Pnt point1 = BRep_Tool::Pnt( vertex_input ); vertices->push_back( osg::Vec3d( point1.X(), point1.Y(), point1.Z() ) ); } } if( vertices->size() > 0 ) { osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry(); geometry->setVertexArray( vertices ); geometry->addPrimitiveSet( new osg::DrawArrays( osg::PrimitiveSet::POINTS, 0, vertices->size() ) ); geode->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); geode->getOrCreateStateSet()->setAttribute( new osg::Point( 3.0f ), osg::StateAttribute::ON ); geode->addDrawable( geometry ); geode->setCullingActive( false ); item_group->addChild( geode ); #ifdef _DEBUG std::stringstream strs_item_shape_name; strs_item_shape_name << strs_item_name.str().c_str() << ", vertex_point "; geode->setName( strs_item_shape_name.str().c_str() ); #endif } else { std::cout << __FUNC__ << ": unexpected vertices->size() == 0" << std::endl; } } // create shape for polylines for( size_t ii_shapes = 0; ii_shapes < item_input_data->getPolylines().size(); ++ii_shapes ) { const TopoDS_Wire& polyline_data = item_input_data->getPolylines()[ii_shapes]; osg::ref_ptr<osg::Geode> geode = new osg::Geode(); if( !geode ) { throw OutOfMemoryException( __FUNC__ ); } geode->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); RenderOptions render_options_polyline; if( item_input_data->getAppearances().size() > 0 ) { for( size_t ii_appearances = 0; ii_appearances < item_input_data->getAppearances().size(); ++ii_appearances ) { const shared_ptr<AppearanceData>& appearance = item_input_data->getAppearances()[ii_appearances]; if( !appearance ) { continue; } if( appearance->m_apply_to_geometry_type == AppearanceData::GEOM_TYPE_CURVE || appearance->m_apply_to_geometry_type == AppearanceData::GEOM_TYPE_ANY ) { osg::Vec4f color_lines( appearance->m_color_ambient.m_r, appearance->m_color_ambient.m_g, appearance->m_color_ambient.m_b, appearance->m_color_ambient.m_a ); render_options_polyline.m_color = color_lines; render_options_polyline.m_color_set = true; break; } } } drawShape( polyline_data, geode, render_options_polyline ); if( geode->getNumDrawables() > 0 ) { item_group->addChild( geode ); #ifdef _DEBUG std::stringstream strs_item_shape_name; strs_item_shape_name << strs_item_name.str().c_str() << ", polylines " << ii_shapes; geode->setName( strs_item_shape_name.str().c_str() ); #endif } } if( m_geom_settings->isShowTextLiterals() ) { for( size_t ii = 0; ii < item_input_data->getTextItems().size(); ++ii ) { const shared_ptr<TextItemDataOCC>& text_data = item_input_data->getTextItems()[ii]; if( !text_data ) { continue; } gp_Trsf& text_pos = text_data->m_text_position; // TODO: handle rotation std::string text_str; text_str.assign( text_data->m_text.begin(), text_data->m_text.end() ); gp_XYZ pos_translation = text_pos.TranslationPart(); osg::Vec3 pos2( pos_translation.X(), pos_translation.Y(), pos_translation.Z() );// text_pos._41, text_pos._42, text_pos._43 ); osg::ref_ptr<osgText::Text> txt = new osgText::Text(); if( !txt ) { throw OutOfMemoryException( __FUNC__ ); } txt->setFont( "fonts/arial.ttf" ); txt->setColor( osg::Vec4f( 0, 0, 0, 1 ) ); txt->setCharacterSize( 0.1f ); txt->setAutoRotateToScreen( true ); txt->setPosition( pos2 ); txt->setText( text_str.c_str() ); txt->getOrCreateStateSet()->setMode( GL_LIGHTING, osg::StateAttribute::OFF ); osg::ref_ptr<osg::Geode> geode = new osg::Geode(); if( !geode ) { throw OutOfMemoryException( __FUNC__ ); } geode->addDrawable( txt ); item_group->addChild( geode ); } } // apply statesets if there are any if( item_input_data->getAppearances().size() > 0 ) { applyAppearancesToGroup( item_input_data->getAppearances(), item_group ); } // If anything has been created, add it to the representation group if( item_group->getNumChildren() > 0 ) { #ifdef _DEBUG if( item_group->getNumParents() > 0 ) { std::cout << __FUNC__ << ": item_group->getNumParents() > 0" << std::endl; } #endif representation_switch->addChild( item_group ); } } // apply statesets if there are any if( product_representation_data->m_vec_representation_appearances.size() > 0 ) { applyAppearancesToGroup( product_representation_data->m_vec_representation_appearances, representation_switch ); } // If anything has been created, add it to the product group if( representation_switch->getNumChildren() > 0 ) { #ifdef _DEBUG if( representation_switch->getNumParents() > 0 ) { std::cout << __FUNC__ << ": product_representation_switch->getNumParents() > 0" << std::endl; } #endif // enable transparency for certain objects if( dynamic_pointer_cast<IfcSpace>(ifc_product) ) { representation_switch->setStateSet( m_glass_stateset ); } else if( dynamic_pointer_cast<IfcCurtainWall>(ifc_product) || dynamic_pointer_cast<IfcWindow>(ifc_product) ) { representation_switch->setStateSet( m_glass_stateset ); SceneGraphUtils::setMaterialAlpha( representation_switch, 0.6f ); } } map_representation_switches.insert( std::make_pair( representation_id, representation_switch ) ); } // TODO: if no color or material is given, set color 231/219/169 for walls, 140/140/140 for slabs } /*\brief method convertToOSG: Creates geometry for OpenSceneGraph from given ProductShapeData. \param[out] parent_group Group to append the geometry. **/ void convertToOSG( std::map<int, shared_ptr<ProductShapeDataOCC> >& map_shape_data, osg::ref_ptr<osg::Switch> parent_group ) { progressTextCallback( L"Converting geometry to OpenGL format ..." ); progressValueCallback( 0, "scenegraph" ); m_map_entity_id_to_switch.clear(); m_map_representation_to_switch.clear(); shared_ptr<ProductShapeDataOCC> ifc_project_data; std::vector<shared_ptr<ProductShapeDataOCC> > vec_products; for( auto it = map_shape_data.begin(); it != map_shape_data.end(); ++it ) { shared_ptr<ProductShapeDataOCC> shape_data = it->second; if( shape_data ) { vec_products.push_back( shape_data ); } } // create geometry for for each IfcProduct independently, spatial structure will be resolved later std::map<int, osg::ref_ptr<osg::Switch> >* map_entity_id = &m_map_entity_id_to_switch; std::map<int, osg::ref_ptr<osg::Switch> >* map_representations = &m_map_representation_to_switch; const int num_products = (int)vec_products.size(); #ifdef ENABLE_OPENMP Mutex writelock_map; Mutex writelock_ifc_project; #pragma omp parallel firstprivate(num_products) shared(map_entity_id, map_representations) { // time for one product may vary significantly, so schedule not so many #pragma omp for schedule(dynamic,10) #endif for( int i = 0; i < num_products; ++i ) { shared_ptr<ProductShapeDataOCC>& shape_data = vec_products[i]; weak_ptr<IfcObjectDefinition>& ifc_object_def_weak = shape_data->m_ifc_object_definition; if( ifc_object_def_weak.expired() ) { continue; } shared_ptr<IfcObjectDefinition> ifc_object_def( ifc_object_def_weak ); std::stringstream thread_err; if( dynamic_pointer_cast<IfcFeatureElementSubtraction>(ifc_object_def) ) { // geometry will be created in method subtractOpenings continue; } else if( dynamic_pointer_cast<IfcProject>(ifc_object_def) ) { #ifdef ENABLE_OPENMP ScopedLock scoped_lock( writelock_ifc_project ); #endif ifc_project_data = shape_data; } shared_ptr<IfcProduct> ifc_product = dynamic_pointer_cast<IfcProduct>(ifc_object_def); if( !ifc_product ) { continue; } if( !ifc_product->m_Representation ) { continue; } const int product_id = ifc_product->m_entity_id; std::map<int, osg::ref_ptr<osg::Switch> > map_representation_switches; try { convertProductShapeToOSG( shape_data, map_representation_switches ); } catch( OutOfMemoryException& e ) { throw e; } catch( BuildingException& e ) { thread_err << e.what(); } catch( Standard_Failure& sf ) { thread_err << sf.GetMessageString(); } catch( std::exception& e ) { thread_err << e.what(); } catch( ... ) { thread_err << "undefined error, product id " << product_id; } if( map_representation_switches.size() > 0 ) { osg::ref_ptr<osg::Switch> product_switch = new osg::Switch(); std::stringstream strs_product_switch_name; strs_product_switch_name << "#" << product_id << "=" << ifc_product->className() << " group"; product_switch->setName( strs_product_switch_name.str().c_str() ); for( auto it_map = map_representation_switches.begin(); it_map != map_representation_switches.end(); ++it_map ) { osg::ref_ptr<osg::Switch>& repres_switch = it_map->second; product_switch->addChild( repres_switch ); } // apply statesets if there are any const std::vector<shared_ptr<AppearanceData> >& vec_product_appearances = shape_data->getAppearances(); if( vec_product_appearances.size() > 0 ) { applyAppearancesToGroup( vec_product_appearances, product_switch ); } #ifdef ENABLE_OPENMP ScopedLock scoped_lock( writelock_map ); #endif map_entity_id->insert( std::make_pair( product_id, product_switch ) ); map_representations->insert( map_representation_switches.begin(), map_representation_switches.end() ); } if( thread_err.tellp() > 0 ) { messageCallback( thread_err.str().c_str(), StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ ); } // progress callback double progress = (double)i / (double)num_products; if( progress - m_recent_progress > 0.02 ) { #ifdef ENABLE_OPENMP if( omp_get_thread_num() == 0 ) #endif { // leave 10% of progress to openscenegraph internals progressValueCallback( progress*0.9, "scenegraph" ); m_recent_progress = progress; } } } #ifdef ENABLE_OPENMP } // implicit barrier #endif try { // now resolve spatial structure if( ifc_project_data ) { resolveProjectStructure( ifc_project_data, parent_group ); } } catch( OutOfMemoryException& e ) { throw e; } catch( BuildingException& e ) { messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" ); } catch( std::exception& e ) { messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" ); } catch( ... ) { messageCallback( "undefined error", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ ); } } void addNodes( const std::map<int, shared_ptr<BuildingObject> >& map_shape_data, osg::ref_ptr<osg::Switch>& target_group ) { // check if there are entities that are not in spatial structure if( !target_group ) { target_group = new osg::Switch(); } for( auto it_product_shapes = map_shape_data.begin(); it_product_shapes != map_shape_data.end(); ++it_product_shapes ) { int product_id = it_product_shapes->first; auto it_find = m_map_entity_id_to_switch.find( product_id ); if( it_find != m_map_entity_id_to_switch.end() ) { osg::ref_ptr<osg::Switch>& sw = it_find->second; if( sw ) { target_group->addChild( sw ); } } } } bool inParentList( const int entity_id, osg::Group* group ) { if( !group ) { return false; } const osg::Group::ParentList& vec_parents = group->getParents(); for( size_t ii = 0; ii < vec_parents.size(); ++ii ) { osg::Group* parent = vec_parents[ii]; if( parent ) { const std::string parent_name = parent->getName(); if( parent_name.length() > 0 ) { if( parent_name.at( 0 ) == '#' ) { // extract entity id std::string parent_name_id = parent_name.substr( 1 ); size_t last_index = parent_name_id.find_first_not_of( "0123456789" ); std::string id_str = parent_name_id.substr( 0, last_index ); const int id = std::stoi( id_str.c_str() ); if( id == entity_id ) { return true; } bool in_parent_list = inParentList( entity_id, parent ); if( in_parent_list ) { return true; } } } } } return false; } void resolveProjectStructure( const shared_ptr<ProductShapeDataOCC>& product_data, osg::ref_ptr<osg::Switch> group ) { if( !product_data ) { return; } if( product_data->m_ifc_object_definition.expired() ) { return; } shared_ptr<IfcObjectDefinition> object_def( product_data->m_ifc_object_definition ); const int entity_id = object_def->m_entity_id; if( SceneGraphUtils::inParentList( entity_id, group ) ) { messageCallback( "Cycle in project structure detected", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__, object_def.get() ); return; } const std::vector<shared_ptr<ProductShapeDataOCC> >& vec_children = product_data->getChildren(); for( size_t ii = 0; ii < vec_children.size(); ++ii ) { const shared_ptr<ProductShapeDataOCC>& child_product_data = vec_children[ii]; if( !child_product_data ) { continue; } osg::ref_ptr<osg::Switch> group_subparts = new osg::Switch(); resolveProjectStructure( child_product_data, group_subparts ); if( group_subparts->getNumChildren() > 0 ) { if( !child_product_data->m_ifc_object_definition.expired() ) { shared_ptr<IfcObjectDefinition> child_obj_def( child_product_data->m_ifc_object_definition ); std::stringstream group_subparts_name; group_subparts_name << "#" << child_obj_def->m_entity_id << "="; group_subparts_name << child_obj_def->className(); group_subparts->setName( group_subparts_name.str().c_str() ); } group->addChild( group_subparts ); } } auto it_product_map = m_map_entity_id_to_switch.find( entity_id ); if( it_product_map != m_map_entity_id_to_switch.end() ) { const osg::ref_ptr<osg::Switch>& product_switch = it_product_map->second; if( product_switch ) { group->addChild( product_switch ); } } else { if( group->getNumChildren() == 0 ) { osg::ref_ptr<osg::Switch> product_switch = new osg::Switch(); group->addChild( product_switch ); std::stringstream switch_name; switch_name << "#" << entity_id << "=" << object_def->className(); product_switch->setName( switch_name.str().c_str() ); } } } void clearAppearanceCache() { #ifdef ENABLE_OPENMP ScopedLock lock( m_writelock_appearance_cache ); #endif m_vec_existing_statesets.clear(); } osg::StateSet* convertToOSGStateSet( const shared_ptr<AppearanceData>& appearence ) { if( !appearence ) { return nullptr; } const float shininess = appearence->m_shininess; const float transparency = appearence->m_transparency; const bool set_transparent = appearence->m_set_transparent; const float color_ambient_r = appearence->m_color_ambient.r(); const float color_ambient_g = appearence->m_color_ambient.g(); const float color_ambient_b = appearence->m_color_ambient.b(); const float color_ambient_a = appearence->m_color_ambient.a(); const float color_diffuse_r = appearence->m_color_diffuse.r(); const float color_diffuse_g = appearence->m_color_diffuse.g(); const float color_diffuse_b = appearence->m_color_diffuse.b(); const float color_diffuse_a = appearence->m_color_diffuse.a(); const float color_specular_r = appearence->m_color_specular.r(); const float color_specular_g = appearence->m_color_specular.g(); const float color_specular_b = appearence->m_color_specular.b(); const float color_specular_a = appearence->m_color_specular.a(); if( m_enable_stateset_caching ) { #ifdef ENABLE_OPENMP ScopedLock lock( m_writelock_appearance_cache ); #endif for( size_t i = 0; i<m_vec_existing_statesets.size(); ++i ) { const osg::ref_ptr<osg::StateSet> stateset_existing = m_vec_existing_statesets[i]; if( !stateset_existing.valid() ) { continue; } osg::ref_ptr<osg::Material> mat_existing = (osg::Material*)stateset_existing->getAttribute( osg::StateAttribute::MATERIAL ); if( !mat_existing ) { continue; } // compare osg::Vec4f color_ambient_existing = mat_existing->getAmbient( osg::Material::FRONT_AND_BACK ); if( abs( color_ambient_existing.r() - color_ambient_r ) > 0.03 ) break; if( abs( color_ambient_existing.g() - color_ambient_g ) > 0.03 ) break; if( abs( color_ambient_existing.b() - color_ambient_b ) > 0.03 ) break; if( abs( color_ambient_existing.a() - color_ambient_a ) > 0.03 ) break; osg::Vec4f color_diffuse_existing = mat_existing->getDiffuse( osg::Material::FRONT_AND_BACK ); if( abs( color_diffuse_existing.r() - color_diffuse_r ) > 0.03 ) break; if( abs( color_diffuse_existing.g() - color_diffuse_g ) > 0.03 ) break; if( abs( color_diffuse_existing.b() - color_diffuse_b ) > 0.03 ) break; if( abs( color_diffuse_existing.a() - color_diffuse_a ) > 0.03 ) break; osg::Vec4f color_specular_existing = mat_existing->getSpecular( osg::Material::FRONT_AND_BACK ); if( abs( color_specular_existing.r() - color_specular_r ) > 0.03 ) break; if( abs( color_specular_existing.g() - color_specular_g ) > 0.03 ) break; if( abs( color_specular_existing.b() - color_specular_b ) > 0.03 ) break; if( abs( color_specular_existing.a() - color_specular_a ) > 0.03 ) break; float shininess_existing = mat_existing->getShininess( osg::Material::FRONT_AND_BACK ); if( abs( shininess_existing - shininess ) > 0.03 ) break; bool blend_on_existing = stateset_existing->getMode( GL_BLEND ) == osg::StateAttribute::ON; if( blend_on_existing != set_transparent ) break; bool transparent_bin = stateset_existing->getRenderingHint() == osg::StateSet::TRANSPARENT_BIN; if( transparent_bin != set_transparent ) break; // if we get here, appearance is same as existing state set // TODO: block this re-used stateset for merging, or prevent merged statesets from being re-used return stateset_existing; } } osg::Vec4f ambientColor( color_ambient_r, color_ambient_g, color_ambient_b, transparency ); osg::Vec4f diffuseColor( color_diffuse_r, color_diffuse_g, color_diffuse_b, transparency ); osg::Vec4f specularColor( color_specular_r, color_specular_g, color_specular_b, transparency ); // TODO: material caching and re-use osg::ref_ptr<osg::Material> mat = new osg::Material(); if( !mat ) { throw OutOfMemoryException(); } mat->setAmbient( osg::Material::FRONT_AND_BACK, ambientColor ); mat->setDiffuse( osg::Material::FRONT_AND_BACK, diffuseColor ); mat->setSpecular( osg::Material::FRONT_AND_BACK, specularColor ); mat->setShininess( osg::Material::FRONT_AND_BACK, shininess ); mat->setColorMode( osg::Material::SPECULAR ); osg::StateSet* stateset = new osg::StateSet(); if( !stateset ) { throw OutOfMemoryException(); } stateset->setAttribute( mat, osg::StateAttribute::ON ); if( appearence->m_set_transparent ) { mat->setTransparency( osg::Material::FRONT_AND_BACK, transparency ); stateset->setMode( GL_BLEND, osg::StateAttribute::ON ); stateset->setRenderingHint( osg::StateSet::TRANSPARENT_BIN ); } if( appearence->m_specular_exponent != 0.f ) { //osg::ref_ptr<osgFX::SpecularHighlights> spec_highlights = new osgFX::SpecularHighlights(); //spec_highlights->setSpecularExponent( spec->m_value ); // todo: add to scenegraph } if( m_enable_stateset_caching ) { m_vec_existing_statesets.push_back( stateset ); } return stateset; } };
rawMD5flat_fmt_plug.c
/* * Raw-MD5 "flat intrinsics" experimental format * * This software is Copyright (c) 2011-2015 magnum, * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. * */ #include "arch.h" #if USE_EXPERIMENTAL #if FMT_EXTERNS_H extern struct fmt_main fmt_rawMD5f; #elif FMT_REGISTERS_H john_register_one(&fmt_rawMD5f); #else #include <string.h> #include "md5.h" #include "common.h" #include "formats.h" #if !FAST_FORMATS_OMP #undef _OPENMP #endif #ifdef _OPENMP #ifdef SIMD_COEF_32 #ifndef OMP_SCALE #define OMP_SCALE 1024 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 2048 #endif #endif #include <omp.h> #endif #include "simd-intrinsics.h" #include "memdbg.h" #ifdef SIMD_COEF_32 #define NBKEYS (SIMD_COEF_32 * SIMD_PARA_MD5) #define PLAINTEXT_LENGTH 55 #define MIN_KEYS_PER_CRYPT NBKEYS #define MAX_KEYS_PER_CRYPT NBKEYS #else #define PLAINTEXT_LENGTH 125 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #define FORMAT_LABEL "Raw-MD5-flat" #define FORMAT_NAME "" #define ALGORITHM_NAME "MD5 " MD5_ALGORITHM_NAME " (experimental)" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define CIPHERTEXT_LENGTH 32 #define DIGEST_SIZE 16 #define BINARY_SIZE 16 // source() #define BINARY_ALIGN 4 #define SALT_SIZE 0 #define SALT_ALIGN 1 #define FORMAT_TAG "$dynamic_0$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) static struct fmt_tests tests[] = { {"5a105e8b9d40e1329780d62ea2265d8a", "test1"}, {FORMAT_TAG "5a105e8b9d40e1329780d62ea2265d8a", "test1"}, {"098f6bcd4621d373cade4e832627b4f6", "test"}, {"098F6BCD4621D373CADE4E832627B4F6", "test"}, {FORMAT_TAG "378e2c4a07968da2eca692320136433d", "thatsworking"}, {FORMAT_TAG "8ad8757baa8564dc136c1e07507f4a98", "test3"}, {"d41d8cd98f00b204e9800998ecf8427e", ""}, #ifdef DEBUG #if PLAINTEXT_LENGTH >= 55 {FORMAT_TAG "c9ccf168914a1bcfc3229f1948e67da0","1234567890123456789012345678901234567890123456789012345"}, #if PLAINTEXT_LENGTH >= 80 {FORMAT_TAG "57edf4a22be3c955ac49da2e2107b67a","12345678901234567890123456789012345678901234567890123456789012345678901234567890"}, #endif // 80 #endif // 55 #endif // DEBUG {NULL} }; #ifdef SIMD_COEF_32 static uint32_t (*crypt_key)[DIGEST_SIZE/4*NBKEYS]; static uint32_t (*saved_key)[64/4]; static int sz; #else static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_key)[DIGEST_SIZE/4]; #endif static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif sz = self->params.max_keys_per_crypt * 64; #ifndef SIMD_COEF_32 saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_key)); #else saved_key = mem_calloc_align(self->params.max_keys_per_crypt, sizeof(*saved_key), MEM_ALIGN_SIMD); crypt_key = mem_calloc_align(self->params.max_keys_per_crypt/NBKEYS, sizeof(*crypt_key), MEM_ALIGN_SIMD); #endif } static void done(void) { MEM_FREE(crypt_key); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *q; p = ciphertext; if (!strncmp(p, FORMAT_TAG, TAG_LENGTH)) p += TAG_LENGTH; q = p; while (atoi16[ARCH_INDEX(*q)] != 0x7F) { q++; } return !*q && q - p == CIPHERTEXT_LENGTH; } static char *split(char *ciphertext, int index, struct fmt_main *self) { static char out[TAG_LENGTH + CIPHERTEXT_LENGTH + 1]; if (ciphertext[0] == '$' && !strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) ciphertext += TAG_LENGTH; memcpy(out, FORMAT_TAG, TAG_LENGTH); memcpylwr(out + TAG_LENGTH, ciphertext, CIPHERTEXT_LENGTH + 1); return out; } static void *get_binary(char *ciphertext) { static unsigned char *out; char *p; int i; if (!out) out = mem_alloc_tiny(DIGEST_SIZE, MEM_ALIGN_WORD); p = ciphertext + TAG_LENGTH; for (i = 0; i < DIGEST_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } #ifdef SIMD_COEF_32 #define HASH_OFFSET (index&(SIMD_COEF_32-1))+(((unsigned int)index%NBKEYS)/SIMD_COEF_32)*SIMD_COEF_32*4 static int get_hash_0(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_6; } #else static int get_hash_0(int index) { return crypt_key[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_key[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_key[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_key[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_key[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_key[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_key[index][0] & PH_MASK_6; } #endif static void set_key(char *key, int index) { #ifdef SIMD_COEF_32 int len = strlen(key); strncpy((char*)saved_key[index], key, sizeof(saved_key[0])); ((unsigned char*)saved_key[index])[len] = 0x80; saved_key[index][14] = len << 3; #else strcpy(saved_key[index], key); #endif } static char *get_key(int index) { #ifdef SIMD_COEF_32 int len = saved_key[index][14] >> 3; ((char*)saved_key[index])[len] = 0; #endif return (char*)saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #ifdef SIMD_COEF_32 const int inc = SIMD_COEF_32; #else const int inc = 1; #endif const int loops = (count + MAX_KEYS_PER_CRYPT - 1) / MAX_KEYS_PER_CRYPT; #pragma omp parallel for for (index = 0; index < loops; index += inc) #endif { #if SIMD_COEF_32 SIMDmd5body(saved_key[index], crypt_key[index/NBKEYS], NULL, SSEi_FLAT_IN); #else MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, saved_key[index], strlen(saved_key[index])); MD5_Final((unsigned char *)crypt_key[index], &ctx); #endif } return count; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) #ifdef SIMD_COEF_32 if (((uint32_t *) binary)[0] == ((uint32_t*)crypt_key)[(index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*4*SIMD_COEF_32]) #else if ( ((uint32_t*)binary)[0] == crypt_key[index][0] ) #endif return 1; return 0; } static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_32 int i; for (i = 0; i < BINARY_SIZE/sizeof(uint32_t); i++) if (((uint32_t *) binary)[i] != ((uint32_t*)crypt_key)[(index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*4*SIMD_COEF_32+i*SIMD_COEF_32]) return 0; return 1; #else return !memcmp(binary, crypt_key[index], BINARY_SIZE); #endif } static int cmp_exact(char *source, int index) { return 1; } static char *source(char *source, void *binary) { static char Buf[CIPHERTEXT_LENGTH + TAG_LENGTH + 1]; unsigned char *cpi; char *cpo; int i; strcpy(Buf, FORMAT_TAG); cpo = &Buf[TAG_LENGTH]; cpi = (unsigned char*)(binary); for (i = 0; i < BINARY_SIZE; ++i) { *cpo++ = itoa16[(*cpi)>>4]; *cpo++ = itoa16[*cpi&0xF]; ++cpi; } *cpo = 0; return Buf; } struct fmt_main fmt_rawMD5f = { { 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, #ifdef _OPENMP FMT_OMP | FMT_OMP_BAD | #endif FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE, { FORMAT_TAG }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, split, get_binary, fmt_default_salt, { NULL }, source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, fmt_default_set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* USE_EXPERIMENTAL */
4770.c
// this source is derived from CHILL AST originally from file '/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/heat-3d/kernel.c' as parsed by frontend compiler rose void kernel_heat_3d(int tsteps, int n, double A[120 + 0][120 + 0][120 + 0], double B[120 + 0][120 + 0][120 + 0]) { int t12; int t10; int t8; int t6; int t4; int t2; for (t2 = 1; t2 <= 500; t2 += 1) { #pragma omp parallel for private(t4,t8,t10,t12,t14) for (t4 = 1; t4 <= n - 2; t4 += 32) for (t6 = t4; t6 <= (t4 + 31 < n - 2 ? t4 + 31 : n - 2); t6 += 1) for (t8 = 1; t8 <= n - 2; t8 += 16) for (t10 = t8; t10 <= (t8 + 15 < n - 2 ? t8 + 15 : n - 2); t10 += 1) for (t12 = 1; t12 <= n - 2; t12 += 1) B[t6][t10][t12] = 0.125 * (A[t6 + 1][t10][t12] - 2 * A[t6][t10][t12] + A[t6 - 1][t10][t12]) + 0.125 * (A[t6][t10 + 1][t12] - 2 * A[t6][t10][t12] + A[t6][t10 - 1][t12]) + 0.125 * (A[t6][t10][t12 + 1] - 2 * A[t6][t10][t12] + A[t6][t10][t12 - 1]) + A[t6][t10][t12]; #pragma omp parallel for private(t4,t8,t10,t12,t14) for (t4 = 1; t4 <= n - 2; t4 += 32) for (t6 = t4; t6 <= (t4 + 31 < n - 2 ? t4 + 31 : n - 2); t6 += 1) for (t8 = 1; t8 <= n - 2; t8 += 16) for (t10 = t8; t10 <= (t8 + 15 < n - 2 ? t8 + 15 : n - 2); t10 += 1) for (t12 = 1; t12 <= n - 2; t12 += 1) A[t6][t10][t12] = 0.125 * (B[t6 + 1][t10][t12] - 2 * B[t6][t10][t12] + B[t6 - 1][t10][t12]) + 0.125 * (B[t6][t10 + 1][t12] - 2 * B[t6][t10][t12] + B[t6][t10 - 1][t12]) + 0.125 * (B[t6][t10][t12 + 1] - 2 * B[t6][t10][t12] + B[t6][t10][t12 - 1]) + B[t6][t10][t12]; } }
GB_unop__minv_fp64_fp64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__minv_fp64_fp64 // op(A') function: GB_unop_tran__minv_fp64_fp64 // C type: double // A type: double // cast: double cij = aij // unaryop: cij = 1./aij #define GB_ATYPE \ double #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = 1./x ; // casting #define GB_CAST(z, aij) \ double z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ double aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = aij ; \ Cx [pC] = 1./z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__minv_fp64_fp64 ( double *Cx, // Cx and Ax may be aliased const double *Ax, const int8_t *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 (double), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; double z = aij ; Cx [p] = 1./z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; double aij = Ax [p] ; double z = aij ; Cx [p] = 1./z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__minv_fp64_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *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
increase.c
// RUN: %libomp-compile && env OMP_DISPLAY_AFFINITY=true %libomp-run | %python %S/check.py -c 'CHECK' %s #include <stdio.h> #include <stdlib.h> #include <omp.h> int main(int argc, char** argv) { omp_set_affinity_format("TESTER: tl:%L tn:%n nt:%N"); // should print all for first parallel omp_set_num_threads(4); #pragma omp parallel { } // should print all because of new threads omp_set_num_threads(8); #pragma omp parallel { } // should not print anything here omp_set_num_threads(6); #pragma omp parallel { } // should print all because of new thread omp_set_num_threads(9); #pragma omp parallel { } // should not print anything here omp_set_num_threads(2); #pragma omp parallel { } return 0; } // CHECK: num_threads=4 TESTER: tl:1 tn:[0-3] nt:4 // CHECK: num_threads=8 TESTER: tl:1 tn:[0-7] nt:8 // CHECK: num_threads=6 TESTER: tl:1 tn:[0-5] nt:6 // CHECK: num_threads=9 TESTER: tl:1 tn:[0-8] nt:9 // CHECK: num_threads=2 TESTER: tl:1 tn:[01] nt:2
parallel_resize_vector.h
// ----------------------------------------------------------------------------- // // Copyright (C) The BioDynaMo Project. // 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. // // See the LICENSE file distributed with this work for details. // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. // // ----------------------------------------------------------------------------- #ifndef CORE_CONTAINER_PARALLEL_RESIZE_VECTOR_H_ #define CORE_CONTAINER_PARALLEL_RESIZE_VECTOR_H_ #include <cstdlib> #include <vector> #include "core/util/root.h" namespace bdm { /// \brief std::vector with parallel resize template <typename T> class ParallelResizeVector { public: using iterator = T*; using const_iterator = const T*; using value_type = T; explicit ParallelResizeVector(TRootIOCtor* io_ctor) {} // Constructor for ROOT I/O ParallelResizeVector() {} ParallelResizeVector(std::initializer_list<T> init) { reserve(init.size()); for (auto& el : init) { push_back(el); } } ParallelResizeVector(const ParallelResizeVector& other) { if (other.data_ != nullptr && other.capacity_ != 0) { reserve(other.capacity_); // initialize using copy ctor #pragma omp parallel for for (std::size_t i = 0; i < other.size_; i++) { new (&(data_[i])) T(other.data_[i]); } } size_ = other.size_; capacity_ = other.capacity_; } virtual ~ParallelResizeVector() { if (data_ != nullptr) { #pragma omp parallel for for (std::size_t i = 0; i < size_; i++) { data_[i].~T(); } capacity_ = 0; free(data_); data_ = nullptr; } } std::size_t size() const { return size_; } // NOLINT T* data() noexcept { return data_; } // NOLINT const T* data() const noexcept { return data_; } // NOLINT void swap(ParallelResizeVector& other) { // NOLINT // size_ size_ ^= other.size_; other.size_ ^= size_; size_ ^= other.size_; // capacity_ capacity_ ^= other.capacity_; other.capacity_ ^= capacity_; capacity_ ^= other.capacity_; // data_ auto* tmp = data_; data_ = other.data_; other.data_ = tmp; } UInt_t capacity() const { return capacity_; } // NOLINT void push_back(const T& element) { // NOLINT if (capacity_ == size_) { reserve(capacity_ * kGrowFactor); } new (&(data_[size_++])) T(element); } void reserve(UInt_t new_capacity) { // NOLINT if (new_capacity > capacity_) { T* new_data = static_cast<T*>(malloc(new_capacity * sizeof(T))); if (data_ != nullptr) { // initialize using copy ctor #pragma omp parallel for for (std::size_t i = 0; i < size_; i++) { new (&(new_data[i])) T(data_[i]); } // destruct old elements #pragma omp parallel for for (std::size_t i = 0; i < size_; i++) { data_[i].~T(); } free(data_); } data_ = new_data; capacity_ = new_capacity; } } void resize(std::size_t new_size, const T& t = T()) { // NOLINT if (capacity_ < new_size) { reserve(new_size); } // grow #pragma omp parallel for for (std::size_t i = size_; i < new_size; i++) { new (&(data_[i])) T(t); } // shrink #pragma omp parallel for for (std::size_t i = new_size; i < size_; i++) { data_[i].~T(); } size_ = new_size; } void clear() { // NOLINT for (std::size_t i = 0; i < size_; i++) { data_[i].~T(); } size_ = 0; } ParallelResizeVector& operator=(const ParallelResizeVector& other) { free(data_); data_ = nullptr; reserve(other.capacity_); size_ = other.size_; capacity_ = other.capacity_; #pragma omp parallel for for (std::size_t i = 0; i < size_; i++) { data_[i] = other.data_[i]; } return *this; } T& operator[](std::size_t index) { return data_[index]; } const T& operator[](std::size_t index) const { return data_[index]; } iterator begin() { return &(data_[0]); } // NOLINT iterator end() { return &(data_[size_]); } // NOLINT const_iterator cbegin() { return &(data_[0]); } // NOLINT const_iterator cend() { return &(data_[size_]); } // NOLINT private: static constexpr float kGrowFactor = 1.5; std::size_t size_ = 0; UInt_t capacity_ = 0; T* data_ = nullptr; //[capacity_] // NOLINT BDM_CLASS_DEF(ParallelResizeVector, 1); // NOLINT }; } // namespace bdm #endif // CORE_CONTAINER_PARALLEL_RESIZE_VECTOR_H_
JeeIOrbitalSoA.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: Ye Luo, yeluo@anl.gov, Argonne National Laboratory // // File created by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory ////////////////////////////////////////////////////////////////////////////////////// #ifndef QMCPLUSPLUS_EEIJASTROW_OPTIMIZED_SOA_H #define QMCPLUSPLUS_EEIJASTROW_OPTIMIZED_SOA_H #include "Configuration.h" #if !defined(QMC_BUILD_SANDBOX_ONLY) #include "QMCWaveFunctions/WaveFunctionComponent.h" #endif #include "Particle/DistanceTableData.h" #include <simd/allocator.hpp> #include <simd/algorithm.hpp> #include <map> #include <numeric> namespace qmcplusplus { /** @ingroup WaveFunctionComponent * @brief Specialization for three-body Jastrow function using multiple functors * *Each pair-type can have distinct function \f$u(r_{ij})\f$. *For electrons, distinct pair correlation functions are used *for spins up-up/down-down and up-down/down-up. */ template<class FT> class JeeIOrbitalSoA : public WaveFunctionComponent { ///type of each component U, dU, d2U; using valT = typename FT::real_type; ///element position type using posT = TinyVector<valT, OHMMS_DIM>; ///use the same container using RowContainer = DistanceTableData::RowContainer; ///table index for el-el const int ee_Table_ID_; ///table index for i-el const int ei_Table_ID_; //nuber of particles int Nelec, Nion; ///number of particles + padded size_t Nelec_padded; //number of groups of the target particleset int eGroups, iGroups; ///reference to the sources (ions) const ParticleSet& Ions; ///diff value RealType DiffVal; ///\f$Uat[i] = sum_(j) u_{i,j}\f$ Vector<valT> Uat, oldUk, newUk; ///\f$dUat[i] = sum_(j) du_{i,j}\f$ using gContainer_type = VectorSoaContainer<valT, OHMMS_DIM>; gContainer_type dUat, olddUk, newdUk; ///\f$d2Uat[i] = sum_(j) d2u_{i,j}\f$ Vector<valT> d2Uat, oldd2Uk, newd2Uk; /// current values during PbyP valT cur_Uat, cur_d2Uat; posT cur_dUat, dUat_temp; ///container for the Jastrow functions Array<FT*, 3> F; std::map<std::string, FT*> J3Unique; //YYYY std::map<FT*, int> J3UniqueIndex; /// the cutoff for e-I pairs std::vector<valT> Ion_cutoff; /// the electrons around ions within the cutoff radius, grouped by species Array<std::vector<int>, 2> elecs_inside; Array<std::vector<valT>, 2> elecs_inside_dist; Array<std::vector<posT>, 2> elecs_inside_displ; /// the ids of ions within the cutoff radius of an electron on which a move is proposed std::vector<int> ions_nearby_old, ions_nearby_new; /// work buffer size size_t Nbuffer; /// compressed distances aligned_vector<valT> Distjk_Compressed, DistkI_Compressed, DistjI_Compressed; std::vector<int> DistIndice_k; /// compressed displacements gContainer_type Disp_jk_Compressed, Disp_jI_Compressed, Disp_kI_Compressed; /// work result buffer VectorSoaContainer<valT, 9> mVGL; // Used for evaluating derivatives with respect to the parameters int NumVars; Array<std::pair<int, int>, 3> VarOffset; Vector<RealType> dLogPsi; Array<PosType, 2> gradLogPsi; Array<RealType, 2> lapLogPsi; // Temporary store for parameter derivatives of functor // The first index is the functor index in J3Unique. The second is the parameter index w.r.t. to that // functor std::vector<std::vector<RealType>> du_dalpha; std::vector<std::vector<PosType>> dgrad_dalpha; std::vector<std::vector<Tensor<RealType, 3>>> dhess_dalpha; public: ///alias FuncType using FuncType = FT; JeeIOrbitalSoA(const ParticleSet& ions, ParticleSet& elecs, bool is_master = false) : Ions(ions), NumVars(0), ee_Table_ID_(elecs.addTable(elecs, DT_SOA)), ei_Table_ID_(elecs.addTable(ions, DT_SOA, true)) { ClassName = "JeeIOrbitalSoA"; init(elecs); } ~JeeIOrbitalSoA() {} WaveFunctionComponentPtr makeClone(ParticleSet& elecs) const { JeeIOrbitalSoA<FT>* eeIcopy = new JeeIOrbitalSoA<FT>(Ions, elecs, false); std::map<const FT*, FT*> fcmap; for (int iG = 0; iG < iGroups; iG++) for (int eG1 = 0; eG1 < eGroups; eG1++) for (int eG2 = 0; eG2 < eGroups; eG2++) { if (F(iG, eG1, eG2) == 0) continue; typename std::map<const FT*, FT*>::iterator fit = fcmap.find(F(iG, eG1, eG2)); if (fit == fcmap.end()) { FT* fc = new FT(*F(iG, eG1, eG2)); eeIcopy->addFunc(iG, eG1, eG2, fc); fcmap[F(iG, eG1, eG2)] = fc; } } // Ye: I don't like the following memory allocated by default. eeIcopy->myVars.clear(); eeIcopy->myVars.insertFrom(myVars); eeIcopy->NumVars = NumVars; eeIcopy->dLogPsi.resize(NumVars); eeIcopy->gradLogPsi.resize(NumVars, Nelec); eeIcopy->lapLogPsi.resize(NumVars, Nelec); eeIcopy->VarOffset = VarOffset; eeIcopy->Optimizable = Optimizable; return eeIcopy; } void init(ParticleSet& p) { Nelec = p.getTotalNum(); Nelec_padded = getAlignedSize<valT>(Nelec); Nion = Ions.getTotalNum(); iGroups = Ions.getSpeciesSet().getTotalNum(); eGroups = p.groups(); Uat.resize(Nelec); dUat.resize(Nelec); d2Uat.resize(Nelec); oldUk.resize(Nelec); olddUk.resize(Nelec); oldd2Uk.resize(Nelec); newUk.resize(Nelec); newdUk.resize(Nelec); newd2Uk.resize(Nelec); F.resize(iGroups, eGroups, eGroups); F = nullptr; elecs_inside.resize(eGroups, Nion); elecs_inside_dist.resize(eGroups, Nion); elecs_inside_displ.resize(eGroups, Nion); ions_nearby_old.resize(Nion); ions_nearby_new.resize(Nion); Ion_cutoff.resize(Nion, 0.0); //initialize buffers Nbuffer = Nelec; mVGL.resize(Nbuffer); Distjk_Compressed.resize(Nbuffer); DistjI_Compressed.resize(Nbuffer); DistkI_Compressed.resize(Nbuffer); Disp_jk_Compressed.resize(Nbuffer); Disp_jI_Compressed.resize(Nbuffer); Disp_kI_Compressed.resize(Nbuffer); DistIndice_k.resize(Nbuffer); } void initUnique() { typename std::map<std::string, FT*>::iterator it(J3Unique.begin()), it_end(J3Unique.end()); du_dalpha.resize(J3Unique.size()); dgrad_dalpha.resize(J3Unique.size()); dhess_dalpha.resize(J3Unique.size()); int ifunc = 0; while (it != it_end) { J3UniqueIndex[it->second] = ifunc; FT& functor = *(it->second); int numParams = functor.getNumParameters(); du_dalpha[ifunc].resize(numParams); dgrad_dalpha[ifunc].resize(numParams); dhess_dalpha[ifunc].resize(numParams); ++it; ifunc++; } } void addFunc(int iSpecies, int eSpecies1, int eSpecies2, FT* j) { if (eSpecies1 == eSpecies2) { //if only up-up is specified, assume spin-unpolarized correlations if (eSpecies1 == 0) for (int eG1 = 0; eG1 < eGroups; eG1++) for (int eG2 = 0; eG2 < eGroups; eG2++) { if (F(iSpecies, eG1, eG2) == 0) F(iSpecies, eG1, eG2) = j; } } else { F(iSpecies, eSpecies1, eSpecies2) = j; F(iSpecies, eSpecies2, eSpecies1) = j; } if (j) { RealType rcut = 0.5 * j->cutoff_radius; for (int i = 0; i < Nion; i++) if (Ions.GroupID[i] == iSpecies) Ion_cutoff[i] = rcut; } else { APP_ABORT("JeeIOrbitalSoA::addFunc Jastrow function pointer is NULL"); } std::stringstream aname; aname << iSpecies << "_" << eSpecies1 << "_" << eSpecies2; J3Unique[aname.str()] = j; initUnique(); } /** check that correlation information is complete */ void check_complete() { //check that correlation pointers are either all 0 or all assigned bool complete = true; for (int i = 0; i < iGroups; ++i) { int nfilled = 0; bool partial; for (int e1 = 0; e1 < eGroups; ++e1) for (int e2 = 0; e2 < eGroups; ++e2) if (F(i, e1, e2) != 0) nfilled++; partial = nfilled > 0 && nfilled < eGroups * eGroups; if (partial) app_log() << "J3 eeI is missing correlation for ion " << i << std::endl; complete = complete && !partial; } if (!complete) { APP_ABORT("JeeIOrbitalSoA::check_complete J3 eeI is missing correlation components\n see preceding messages " "for details"); } //first set radii for (int i = 0; i < Nion; ++i) { FT* f = F(Ions.GroupID[i], 0, 0); if (f != 0) Ion_cutoff[i] = .5 * f->cutoff_radius; } //then check radii bool all_radii_match = true; for (int i = 0; i < iGroups; ++i) { if (F(i, 0, 0) != 0) { bool radii_match = true; RealType rcut = F(i, 0, 0)->cutoff_radius; for (int e1 = 0; e1 < eGroups; ++e1) for (int e2 = 0; e2 < eGroups; ++e2) radii_match = radii_match && F(i, e1, e2)->cutoff_radius == rcut; if (!radii_match) app_log() << "eeI functors for ion species " << i << " have different radii" << std::endl; all_radii_match = all_radii_match && radii_match; } } if (!all_radii_match) { APP_ABORT("JeeIOrbitalSoA::check_radii J3 eeI are inconsistent for some ion species\n see preceding messages " "for details"); } } //evaluate the distance table with els void resetTargetParticleSet(ParticleSet& P) {} /** check in an optimizable parameter * @param o a super set of optimizable variables */ void checkInVariables(opt_variables_type& active) { myVars.clear(); typename std::map<std::string, FT*>::iterator it(J3Unique.begin()), it_end(J3Unique.end()); while (it != it_end) { (*it).second->checkInVariables(active); (*it).second->checkInVariables(myVars); ++it; } } /** check out optimizable variables */ void checkOutVariables(const opt_variables_type& active) { myVars.clear(); typename std::map<std::string, FT*>::iterator it(J3Unique.begin()), it_end(J3Unique.end()); while (it != it_end) { (*it).second->myVars.getIndex(active); myVars.insertFrom((*it).second->myVars); ++it; } myVars.getIndex(active); NumVars = myVars.size(); if (NumVars) { dLogPsi.resize(NumVars); gradLogPsi.resize(NumVars, Nelec); lapLogPsi.resize(NumVars, Nelec); VarOffset.resize(iGroups, eGroups, eGroups); int varoffset = myVars.Index[0]; for (int ig = 0; ig < iGroups; ig++) for (int jg = 0; jg < eGroups; jg++) for (int kg = 0; kg < eGroups; kg++) { FT* func_ijk = F(ig, jg, kg); if (func_ijk == nullptr) continue; VarOffset(ig, jg, kg).first = func_ijk->myVars.Index.front() - varoffset; VarOffset(ig, jg, kg).second = func_ijk->myVars.Index.size() + VarOffset(ig, jg, kg).first; } } } ///reset the value of all the unique Two-Body Jastrow functions void resetParameters(const opt_variables_type& active) { if (!Optimizable) return; typename std::map<std::string, FT*>::iterator it(J3Unique.begin()), it_end(J3Unique.end()); while (it != it_end) { (*it++).second->resetParameters(active); } for (int i = 0; i < myVars.size(); ++i) { int ii = myVars.Index[i]; if (ii >= 0) myVars[i] = active[ii]; } } /** print the state, e.g., optimizables */ void reportStatus(std::ostream& os) { typename std::map<std::string, FT*>::iterator it(J3Unique.begin()), it_end(J3Unique.end()); while (it != it_end) { (*it).second->myVars.print(os); ++it; } } void build_compact_list(ParticleSet& P) { const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_); for (int iat = 0; iat < Nion; ++iat) for (int jg = 0; jg < eGroups; ++jg) { elecs_inside(jg, iat).clear(); elecs_inside_dist(jg, iat).clear(); elecs_inside_displ(jg, iat).clear(); } for (int jg = 0; jg < eGroups; ++jg) for (int jel = P.first(jg); jel < P.last(jg); jel++) for (int iat = 0; iat < Nion; ++iat) if (eI_table.Distances[jel][iat] < Ion_cutoff[iat]) { elecs_inside(jg, iat).push_back(jel); elecs_inside_dist(jg, iat).push_back(eI_table.Distances[jel][iat]); elecs_inside_displ(jg, iat).push_back(eI_table.Displacements[jel][iat]); } } RealType evaluateLog(ParticleSet& P, ParticleSet::ParticleGradient_t& G, ParticleSet::ParticleLaplacian_t& L) { evaluateGL(P, G, L, true); return LogValue; } ValueType ratio(ParticleSet& P, int iat) { UpdateMode = ORB_PBYP_RATIO; const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_); const DistanceTableData& ee_table = P.getDistTable(ee_Table_ID_); cur_Uat = computeU(P, iat, P.GroupID[iat], eI_table.Temp_r.data(), ee_table.Temp_r.data(), ions_nearby_new); DiffVal = Uat[iat] - cur_Uat; return std::exp(DiffVal); } void evaluateRatios(VirtualParticleSet& VP, std::vector<ValueType>& ratios) { for (int k = 0; k < ratios.size(); ++k) ratios[k] = std::exp(Uat[VP.refPtcl] - computeU(VP.refPS, VP.refPtcl, VP.refPS.GroupID[VP.refPtcl], VP.getDistTable(ei_Table_ID_).Distances[k], VP.getDistTable(ee_Table_ID_).Distances[k], ions_nearby_old)); } void evaluateRatiosAlltoOne(ParticleSet& P, std::vector<ValueType>& ratios) { const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_); const DistanceTableData& ee_table = P.getDistTable(ee_Table_ID_); for (int jg = 0; jg < eGroups; ++jg) { const valT sumU = computeU(P, -1, jg, eI_table.Temp_r.data(), ee_table.Temp_r.data(), ions_nearby_new); for (int j = P.first(jg); j < P.last(jg); ++j) { // remove self-interaction valT Uself(0); for (int iat = 0; iat < Nion; ++iat) { const valT& r_Ij = eI_table.Temp_r[iat]; const valT& r_Ik = eI_table.Distances[j][iat]; if (r_Ij < Ion_cutoff[iat] && r_Ik < Ion_cutoff[iat]) { const int ig = Ions.GroupID[iat]; Uself += F(ig, jg, jg)->evaluate(ee_table.Temp_r[j], r_Ij, r_Ik); } } ratios[j] = std::exp(Uat[j] + Uself - sumU); } } } GradType evalGrad(ParticleSet& P, int iat) { return GradType(dUat[iat]); } ValueType ratioGrad(ParticleSet& P, int iat, GradType& grad_iat) { UpdateMode = ORB_PBYP_PARTIAL; const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_); const DistanceTableData& ee_table = P.getDistTable(ee_Table_ID_); computeU3(P, iat, eI_table.Temp_r.data(), eI_table.Temp_dr, ee_table.Temp_r.data(), ee_table.Temp_dr, cur_Uat, cur_dUat, cur_d2Uat, newUk, newdUk, newd2Uk, ions_nearby_new); DiffVal = Uat[iat] - cur_Uat; grad_iat += cur_dUat; return std::exp(DiffVal); } inline void restore(int iat) {} void acceptMove(ParticleSet& P, int iat) { const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_); const DistanceTableData& ee_table = P.getDistTable(ee_Table_ID_); // get the old value, grad, lapl computeU3(P, iat, eI_table.Distances[iat], eI_table.Displacements[iat], ee_table.Distances[iat], ee_table.Displacements[iat], Uat[iat], dUat_temp, d2Uat[iat], oldUk, olddUk, oldd2Uk, ions_nearby_old); if (UpdateMode == ORB_PBYP_RATIO) { //ratio-only during the move; need to compute derivatives computeU3(P, iat, eI_table.Temp_r.data(), eI_table.Temp_dr, ee_table.Temp_r.data(), ee_table.Temp_dr, cur_Uat, cur_dUat, cur_d2Uat, newUk, newdUk, newd2Uk, ions_nearby_new); } #pragma omp simd for (int jel = 0; jel < Nelec; jel++) { Uat[jel] += newUk[jel] - oldUk[jel]; d2Uat[jel] += newd2Uk[jel] - oldd2Uk[jel]; } for (int idim = 0; idim < OHMMS_DIM; ++idim) { valT* restrict save_g = dUat.data(idim); const valT* restrict new_g = newdUk.data(idim); const valT* restrict old_g = olddUk.data(idim); #pragma omp simd aligned(save_g, new_g, old_g) for (int jel = 0; jel < Nelec; jel++) save_g[jel] += new_g[jel] - old_g[jel]; } LogValue += Uat[iat] - cur_Uat; Uat[iat] = cur_Uat; dUat(iat) = cur_dUat; d2Uat[iat] = cur_d2Uat; const int ig = P.GroupID[iat]; // update compact list elecs_inside // if the old position exists in elecs_inside for (int iind = 0; iind < ions_nearby_old.size(); iind++) { int jat = ions_nearby_old[iind]; auto iter = std::find(elecs_inside(ig, jat).begin(), elecs_inside(ig, jat).end(), iat); auto iter_dist = elecs_inside_dist(ig, jat).begin() + std::distance(elecs_inside(ig, jat).begin(), iter); auto iter_displ = elecs_inside_displ(ig, jat).begin() + std::distance(elecs_inside(ig, jat).begin(), iter); if (eI_table.Temp_r[jat] < Ion_cutoff[jat]) // the new position is still inside { *iter_dist = eI_table.Temp_r[jat]; *iter_displ = eI_table.Temp_dr[jat]; *std::find(ions_nearby_new.begin(), ions_nearby_new.end(), jat) = -1; } else { *iter = elecs_inside(ig, jat).back(); elecs_inside(ig, jat).pop_back(); *iter_dist = elecs_inside_dist(ig, jat).back(); elecs_inside_dist(ig, jat).pop_back(); *iter_displ = elecs_inside_displ(ig, jat).back(); elecs_inside_displ(ig, jat).pop_back(); } } // if the old position doesn't exist in elecs_inside but the new position do for (int iind = 0; iind < ions_nearby_new.size(); iind++) { int jat = ions_nearby_new[iind]; if (jat >= 0) { elecs_inside(ig, jat).push_back(iat); elecs_inside_dist(ig, jat).push_back(eI_table.Temp_r[jat]); elecs_inside_displ(ig, jat).push_back(eI_table.Temp_dr[jat]); } } } inline void recompute(ParticleSet& P) { const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_); const DistanceTableData& ee_table = P.getDistTable(ee_Table_ID_); build_compact_list(P); for (int jel = 0; jel < Nelec; ++jel) { computeU3(P, jel, eI_table.Distances[jel], eI_table.Displacements[jel], ee_table.Distances[jel], ee_table.Displacements[jel], Uat[jel], dUat_temp, d2Uat[jel], newUk, newdUk, newd2Uk, ions_nearby_new, true); dUat(jel) = dUat_temp; // add the contribution from the upper triangle #pragma omp simd for (int kel = 0; kel < jel; kel++) { Uat[kel] += newUk[kel]; d2Uat[kel] += newd2Uk[kel]; } for (int idim = 0; idim < OHMMS_DIM; ++idim) { valT* restrict save_g = dUat.data(idim); const valT* restrict new_g = newdUk.data(idim); #pragma omp simd aligned(save_g, new_g) for (int kel = 0; kel < jel; kel++) save_g[kel] += new_g[kel]; } } } inline valT computeU(const ParticleSet& P, int jel, int jg, const RealType* distjI, const RealType* distjk, std::vector<int>& ions_nearby) { const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_); ions_nearby.clear(); for (int iat = 0; iat < Nion; ++iat) if (distjI[iat] < Ion_cutoff[iat]) ions_nearby.push_back(iat); valT Uj = valT(0); for (int kg = 0; kg < eGroups; ++kg) { int kel_counter = 0; for (int iind = 0; iind < ions_nearby.size(); ++iind) { const int iat = ions_nearby[iind]; const int ig = Ions.GroupID[iat]; const valT r_jI = distjI[iat]; for (int kind = 0; kind < elecs_inside(kg, iat).size(); kind++) { const int kel = elecs_inside(kg, iat)[kind]; if (kel != jel) { DistkI_Compressed[kel_counter] = elecs_inside_dist(kg, iat)[kind]; Distjk_Compressed[kel_counter] = distjk[kel]; DistjI_Compressed[kel_counter] = r_jI; kel_counter++; if (kel_counter == Nbuffer) { const FT& feeI(*F(ig, jg, kg)); Uj += feeI.evaluateV(kel_counter, Distjk_Compressed.data(), DistjI_Compressed.data(), DistkI_Compressed.data()); kel_counter = 0; } } } if ((iind + 1 == ions_nearby.size() || ig != Ions.GroupID[ions_nearby[iind + 1]]) && kel_counter > 0) { const FT& feeI(*F(ig, jg, kg)); Uj += feeI.evaluateV(kel_counter, Distjk_Compressed.data(), DistjI_Compressed.data(), DistkI_Compressed.data()); kel_counter = 0; } } } return Uj; } inline void computeU3_engine(const ParticleSet& P, const FT& feeI, int kel_counter, valT& Uj, posT& dUj, valT& d2Uj, Vector<valT>& Uk, gContainer_type& dUk, Vector<valT>& d2Uk) { const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_); constexpr valT czero(0); constexpr valT cone(1); constexpr valT ctwo(2); constexpr valT lapfac = OHMMS_DIM - cone; valT* restrict val = mVGL.data(0); valT* restrict gradF0 = mVGL.data(1); valT* restrict gradF1 = mVGL.data(2); valT* restrict gradF2 = mVGL.data(3); valT* restrict hessF00 = mVGL.data(4); valT* restrict hessF11 = mVGL.data(5); valT* restrict hessF22 = mVGL.data(6); valT* restrict hessF01 = mVGL.data(7); valT* restrict hessF02 = mVGL.data(8); feeI.evaluateVGL(kel_counter, Distjk_Compressed.data(), DistjI_Compressed.data(), DistkI_Compressed.data(), val, gradF0, gradF1, gradF2, hessF00, hessF11, hessF22, hessF01, hessF02); // compute the contribution to jel, kel Uj = simd::accumulate_n(val, kel_counter, Uj); valT gradF0_sum = simd::accumulate_n(gradF0, kel_counter, czero); valT gradF1_sum = simd::accumulate_n(gradF1, kel_counter, czero); valT hessF00_sum = simd::accumulate_n(hessF00, kel_counter, czero); valT hessF11_sum = simd::accumulate_n(hessF11, kel_counter, czero); d2Uj -= hessF00_sum + hessF11_sum + lapfac * (gradF0_sum + gradF1_sum); std::fill_n(hessF11, kel_counter, czero); for (int idim = 0; idim < OHMMS_DIM; ++idim) { valT* restrict jk = Disp_jk_Compressed.data(idim); valT* restrict jI = Disp_jI_Compressed.data(idim); valT* restrict kI = Disp_kI_Compressed.data(idim); valT dUj_x(0); #pragma omp simd aligned(gradF0, gradF1, gradF2, hessF11, jk, jI, kI) reduction(+ : dUj_x) for (int kel_index = 0; kel_index < kel_counter; kel_index++) { // recycle hessF11 hessF11[kel_index] += kI[kel_index] * jk[kel_index]; dUj_x += gradF1[kel_index] * jI[kel_index]; // destroy jk, kI const valT temp = jk[kel_index] * gradF0[kel_index]; dUj_x += temp; jk[kel_index] *= jI[kel_index]; kI[kel_index] = kI[kel_index] * gradF2[kel_index] - temp; } dUj[idim] += dUj_x; valT* restrict jk0 = Disp_jk_Compressed.data(0); if (idim > 0) { #pragma omp simd aligned(jk, jk0) for (int kel_index = 0; kel_index < kel_counter; kel_index++) jk0[kel_index] += jk[kel_index]; } valT* restrict dUk_x = dUk.data(idim); for (int kel_index = 0; kel_index < kel_counter; kel_index++) dUk_x[DistIndice_k[kel_index]] += kI[kel_index]; } valT sum(0); valT* restrict jk0 = Disp_jk_Compressed.data(0); #pragma omp simd aligned(jk0, hessF01) reduction(+ : sum) for (int kel_index = 0; kel_index < kel_counter; kel_index++) sum += hessF01[kel_index] * jk0[kel_index]; d2Uj -= ctwo * sum; #pragma omp simd aligned(hessF00, hessF22, gradF0, gradF2, hessF02, hessF11) for (int kel_index = 0; kel_index < kel_counter; kel_index++) hessF00[kel_index] = hessF00[kel_index] + hessF22[kel_index] + lapfac * (gradF0[kel_index] + gradF2[kel_index]) - ctwo * hessF02[kel_index] * hessF11[kel_index]; for (int kel_index = 0; kel_index < kel_counter; kel_index++) { const int kel = DistIndice_k[kel_index]; Uk[kel] += val[kel_index]; d2Uk[kel] -= hessF00[kel_index]; } } inline void computeU3(const ParticleSet& P, int jel, const RealType* distjI, const RowContainer& displjI, const RealType* distjk, const RowContainer& displjk, valT& Uj, posT& dUj, valT& d2Uj, Vector<valT>& Uk, gContainer_type& dUk, Vector<valT>& d2Uk, std::vector<int>& ions_nearby, bool triangle = false) { constexpr valT czero(0); Uj = czero; dUj = posT(); d2Uj = czero; const int jg = P.GroupID[jel]; const int kelmax = triangle ? jel : Nelec; std::fill_n(Uk.data(), kelmax, czero); std::fill_n(d2Uk.data(), kelmax, czero); for (int idim = 0; idim < OHMMS_DIM; ++idim) std::fill_n(dUk.data(idim), kelmax, czero); ions_nearby.clear(); for (int iat = 0; iat < Nion; ++iat) if (distjI[iat] < Ion_cutoff[iat]) ions_nearby.push_back(iat); for (int kg = 0; kg < eGroups; ++kg) { int kel_counter = 0; for (int iind = 0; iind < ions_nearby.size(); ++iind) { const int iat = ions_nearby[iind]; const int ig = Ions.GroupID[iat]; const valT r_jI = distjI[iat]; const posT disp_Ij = displjI[iat]; for (int kind = 0; kind < elecs_inside(kg, iat).size(); kind++) { const int kel = elecs_inside(kg, iat)[kind]; if (kel < kelmax && kel != jel) { DistkI_Compressed[kel_counter] = elecs_inside_dist(kg, iat)[kind]; DistjI_Compressed[kel_counter] = r_jI; Distjk_Compressed[kel_counter] = distjk[kel]; Disp_kI_Compressed(kel_counter) = elecs_inside_displ(kg, iat)[kind]; Disp_jI_Compressed(kel_counter) = disp_Ij; Disp_jk_Compressed(kel_counter) = displjk[kel]; DistIndice_k[kel_counter] = kel; kel_counter++; if (kel_counter == Nbuffer) { const FT& feeI(*F(ig, jg, kg)); computeU3_engine(P, feeI, kel_counter, Uj, dUj, d2Uj, Uk, dUk, d2Uk); kel_counter = 0; } } } if ((iind + 1 == ions_nearby.size() || ig != Ions.GroupID[ions_nearby[iind + 1]]) && kel_counter > 0) { const FT& feeI(*F(ig, jg, kg)); computeU3_engine(P, feeI, kel_counter, Uj, dUj, d2Uj, Uk, dUk, d2Uk); kel_counter = 0; } } } } inline void registerData(ParticleSet& P, WFBufferType& buf) { if (Bytes_in_WFBuffer == 0) { Bytes_in_WFBuffer = buf.current(); buf.add(Uat.begin(), Uat.end()); buf.add(dUat.data(), dUat.end()); buf.add(d2Uat.begin(), d2Uat.end()); Bytes_in_WFBuffer = buf.current() - Bytes_in_WFBuffer; // free local space Uat.free(); dUat.free(); d2Uat.free(); } else { buf.forward(Bytes_in_WFBuffer); } } inline RealType updateBuffer(ParticleSet& P, WFBufferType& buf, bool fromscratch = false) { evaluateGL(P, P.G, P.L, false); buf.forward(Bytes_in_WFBuffer); return LogValue; } inline void copyFromBuffer(ParticleSet& P, WFBufferType& buf) { Uat.attachReference(buf.lendReference<valT>(Nelec), Nelec); dUat.attachReference(Nelec, Nelec_padded, buf.lendReference<valT>(Nelec_padded * OHMMS_DIM)); d2Uat.attachReference(buf.lendReference<valT>(Nelec), Nelec); build_compact_list(P); } void evaluateGL(ParticleSet& P, ParticleSet::ParticleGradient_t& G, ParticleSet::ParticleLaplacian_t& L, bool fromscratch = false) { if (fromscratch) recompute(P); LogValue = valT(0); for (int iat = 0; iat < Nelec; ++iat) { LogValue += Uat[iat]; G[iat] += dUat[iat]; L[iat] += d2Uat[iat]; } constexpr valT mhalf(-0.5); LogValue = mhalf * LogValue; } void evaluateDerivatives(ParticleSet& P, const opt_variables_type& optvars, std::vector<ValueType>& dlogpsi, std::vector<ValueType>& dhpsioverpsi) { bool recalculate(false); std::vector<bool> rcsingles(myVars.size(), false); for (int k = 0; k < myVars.size(); ++k) { int kk = myVars.where(k); if (kk < 0) continue; if (optvars.recompute(kk)) recalculate = true; rcsingles[k] = true; } if (recalculate) { constexpr valT czero(0); constexpr valT cone(1); constexpr valT cminus(-1); constexpr valT ctwo(2); constexpr valT lapfac = OHMMS_DIM - cone; const DistanceTableData& ee_table = P.getDistTable(ee_Table_ID_); const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_); build_compact_list(P); dLogPsi = czero; gradLogPsi = PosType(); lapLogPsi = czero; for (int iat = 0; iat < Nion; ++iat) { const int ig = Ions.GroupID[iat]; for (int jg = 0; jg < eGroups; ++jg) for (int jind = 0; jind < elecs_inside(jg, iat).size(); jind++) { const int jel = elecs_inside(jg, iat)[jind]; const valT r_Ij = elecs_inside_dist(jg, iat)[jind]; const posT disp_Ij = cminus * elecs_inside_displ(jg, iat)[jind]; const valT r_Ij_inv = cone / r_Ij; for (int kg = 0; kg < eGroups; ++kg) for (int kind = 0; kind < elecs_inside(kg, iat).size(); kind++) { const int kel = elecs_inside(kg, iat)[kind]; if (kel < jel) { const FT& feeI(*F(ig, jg, kg)); const valT r_Ik = elecs_inside_dist(kg, iat)[kind]; const posT disp_Ik = cminus * elecs_inside_displ(kg, iat)[kind]; const valT r_Ik_inv = cone / r_Ik; const valT r_jk = ee_table.Distances[jel][kel]; const posT disp_jk = ee_table.Displacements[jel][kel]; const valT r_jk_inv = cone / r_jk; FT& func = *F(ig, jg, kg); int idx = J3UniqueIndex[F(ig, jg, kg)]; func.evaluateDerivatives(r_jk, r_Ij, r_Ik, du_dalpha[idx], dgrad_dalpha[idx], dhess_dalpha[idx]); int first = VarOffset(ig, jg, kg).first; int last = VarOffset(ig, jg, kg).second; std::vector<RealType>& dlog = du_dalpha[idx]; std::vector<PosType>& dgrad = dgrad_dalpha[idx]; std::vector<Tensor<RealType, 3>>& dhess = dhess_dalpha[idx]; for (int p = first, ip = 0; p < last; p++, ip++) { RealType& dval = dlog[ip]; PosType& dg = dgrad[ip]; Tensor<RealType, 3>& dh = dhess[ip]; dg[0] *= r_jk_inv; dg[1] *= r_Ij_inv; dg[2] *= r_Ik_inv; PosType gr_ee = dg[0] * disp_jk; gradLogPsi(p, jel) -= dg[1] * disp_Ij - gr_ee; lapLogPsi(p, jel) -= (dh(0, 0) + lapfac * dg[0] - ctwo * dh(0, 1) * dot(disp_jk, disp_Ij) * r_jk_inv * r_Ij_inv + dh(1, 1) + lapfac * dg[1]); gradLogPsi(p, kel) -= dg[2] * disp_Ik + gr_ee; lapLogPsi(p, kel) -= (dh(0, 0) + lapfac * dg[0] + ctwo * dh(0, 2) * dot(disp_jk, disp_Ik) * r_jk_inv * r_Ik_inv + dh(2, 2) + lapfac * dg[2]); dLogPsi[p] -= dval; } } } } } for (int k = 0; k < myVars.size(); ++k) { int kk = myVars.where(k); if (kk < 0) continue; dlogpsi[kk] = (ValueType)dLogPsi[k]; RealType sum = 0.0; for (int i = 0; i < Nelec; i++) { #if defined(QMC_COMPLEX) sum -= 0.5 * lapLogPsi(k, i); for (int jdim = 0; jdim < OHMMS_DIM; ++jdim) sum -= P.G[i][jdim].real() * gradLogPsi(k, i)[jdim]; #else sum -= 0.5 * lapLogPsi(k, i) + dot(P.G[i], gradLogPsi(k, i)); #endif } dhpsioverpsi[kk] = (ValueType)sum; } } } }; } // namespace qmcplusplus #endif
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/ASTConcept.h" #include "clang/AST/ASTFwd.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/ExprConcepts.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExprOpenMP.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/StmtOpenMP.h" #include "clang/AST/TypeLoc.h" #include "clang/APINotes/APINotesManager.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/DarwinSDKInfo.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenCLOptions.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/SemaConcept.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/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include <deque> #include <functional> #include <memory> #include <string> #include <tuple> #include <vector> namespace llvm { class APSInt; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; enum class OverloadCandidateParamOrder : char; enum OverloadCandidateRewriteKind : unsigned; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; /// Tracks expected type during expression parsing, for use in code completion. /// 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 avoids updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Handles e.g. BaseType{ .D = Tok... void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, const Designation &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. /// /// The callback should also emit signature help as a side-effect, but only /// if the completion point has been reached. 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); /// Get the expected type associated with this location, if any. /// /// If the location is a function argument, determining the expected type /// involves considering all function overloads and the arguments so far. /// In this case, signature help for these function overloads will be reported /// as a side-effect (only if the completion point has been reached). QualType get(SourceLocation Tok) const { if (!Enabled || Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: bool Enabled; /// 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 final { 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: /// The maximum alignment, same as in llvm::Value. We duplicate them here /// because that allows us not to duplicate the constants in clang code, /// which we must to since we can't directly use the llvm constants. /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp /// /// This is the greatest alignment value supported by load, store, and alloca /// instructions, and global values. static const unsigned MaxAlignmentExponent = 32; static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent; typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions CurFPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; api_notes::APINotesManager APINotes; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by /// `TransformTypos` in order to keep track of any TypoExprs that are created /// recursively during typo correction and wipe them away if the correction /// fails. llvm::SmallVector<TypoExpr *, 2> TypoExprs; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4, PCSK_Relro = 5 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangRelroSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; // #pragma pack and align. class AlignPackInfo { public: // `Native` represents default align mode, which may vary based on the // platform. enum Mode : unsigned char { Native, Natural, Packed, Mac68k }; // #pragma pack info constructor AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL) : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) { assert(Num == PackNumber && "The pack number has been truncated."); } // #pragma align info constructor AlignPackInfo(AlignPackInfo::Mode M, bool IsXL) : PackAttr(false), AlignMode(M), PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {} explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {} AlignPackInfo() : AlignPackInfo(Native, false) {} // When a AlignPackInfo itself cannot be used, this returns an 32-bit // integer encoding for it. This should only be passed to // AlignPackInfo::getFromRawEncoding, it should not be inspected directly. static uint32_t getRawEncoding(const AlignPackInfo &Info) { std::uint32_t Encoding{}; if (Info.IsXLStack()) Encoding |= IsXLMask; Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1; if (Info.IsPackAttr()) Encoding |= PackAttrMask; Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4; return Encoding; } static AlignPackInfo getFromRawEncoding(unsigned Encoding) { bool IsXL = static_cast<bool>(Encoding & IsXLMask); AlignPackInfo::Mode M = static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1); int PackNumber = (Encoding & PackNumMask) >> 4; if (Encoding & PackAttrMask) return AlignPackInfo(M, PackNumber, IsXL); return AlignPackInfo(M, IsXL); } bool IsPackAttr() const { return PackAttr; } bool IsAlignAttr() const { return !PackAttr; } Mode getAlignMode() const { return AlignMode; } unsigned getPackNumber() const { return PackNumber; } bool IsPackSet() const { // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack // attriute on a decl. return PackNumber != UninitPackVal && PackNumber != 0; } bool IsXLStack() const { return XLStack; } bool operator==(const AlignPackInfo &Info) const { return std::tie(AlignMode, PackNumber, PackAttr, XLStack) == std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr, Info.XLStack); } bool operator!=(const AlignPackInfo &Info) const { return !(*this == Info); } private: /// \brief True if this is a pragma pack attribute, /// not a pragma align attribute. bool PackAttr; /// \brief The alignment mode that is in effect. Mode AlignMode; /// \brief The pack number of the stack. unsigned char PackNumber; /// \brief True if it is a XL #pragma align/pack stack. bool XLStack; /// \brief Uninitialized pack value. static constexpr unsigned char UninitPackVal = -1; // Masks to encode and decode an AlignPackInfo. static constexpr uint32_t IsXLMask{0x0000'0001}; static constexpr uint32_t AlignModeMask{0x0000'0006}; static constexpr uint32_t PackAttrMask{0x00000'0008}; static constexpr uint32_t PackNumMask{0x0000'01F0}; }; 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) { if (Action == PSK_Reset) { CurrentValue = DefaultValue; CurrentPragmaLocation = PragmaLocation; return; } if (Action & PSK_Push) Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, PragmaLocation); else if (Action & PSK_Pop) { if (!StackSlotLabel.empty()) { // If we've got a label, try to find it and jump there. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { return x.StackSlotLabel == StackSlotLabel; }); // If we found the label so pop from there. if (I != Stack.rend()) { CurrentValue = I->Value; CurrentPragmaLocation = I->PragmaLocation; Stack.erase(std::prev(I.base()), Stack.end()); } } else if (!Stack.empty()) { // We do not have a label, just pop the last entry. CurrentValue = Stack.back().Value; CurrentPragmaLocation = Stack.back().PragmaLocation; Stack.pop_back(); } } if (Action & PSK_Set) { CurrentValue = Value; CurrentPragmaLocation = PragmaLocation; } } // 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<MSVtorDispMode> VtorDispStack; PragmaStack<AlignPackInfo> AlignPackStack; // The current #pragma align/pack values and locations at each #include. struct AlignPackIncludeState { AlignPackInfo CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // This stack tracks the current state of Sema.CurFPFeatures. PragmaStack<FPOptionsOverride> FpPragmaStack; FPOptionsOverride CurFPFeatureOverrides() { FPOptionsOverride result; if (!FpPragmaStack.hasValue()) { result = FPOptionsOverride(); } else { result = FpPragmaStack.CurrentValue; } return result; } // 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. SmallVector<ExprWithCleanups::CleanupObject, 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::SetVector<Expr *, SmallVector<Expr *, 4>, llvm::SmallPtrSet<Expr *, 4>>; 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; /// The index of the first FunctionScope that corresponds to the current /// context. unsigned FunctionScopesStart = 0; ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, FunctionScopes.end()); } /// Stack containing information needed when in C++2a an 'auto' is encountered /// in a function declaration parameter type specifier in order to invent a /// corresponding template parameter in the enclosing abbreviated function /// template. This information is also present in LambdaScopeInfo, stored in /// the FunctionScopes stack. SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; /// The index of the first InventedParameterInfo that refers to the current /// context. unsigned InventedParameterInfosStart = 0; ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { return llvm::makeArrayRef(InventedParameterInfos.begin() + InventedParameterInfosStart, InventedParameterInfos.end()); } 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; /// All the external declarations encoutered and used in the TU. SmallVector<VarDecl *, 4> ExternalDeclarations; 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; } /// \brief Callback to the parser to parse a type expressed as a string. std::function<TypeResult(StringRef, StringRef, SourceLocation)> ParseTypeFromStringCallback; 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; unsigned SavedFunctionScopesStart; unsigned SavedInventedParameterInfosStart; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride), SavedFunctionScopesStart(S.FunctionScopesStart), SavedInventedParameterInfosStart(S.InventedParameterInfosStart) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); // Any saved FunctionScopes do not refer to this context. S.FunctionScopesStart = S.FunctionScopes.size(); S.InventedParameterInfosStart = S.InventedParameterInfos.size(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; S.FunctionScopesStart = SavedFunctionScopesStart; S.InventedParameterInfosStart = SavedInventedParameterInfosStart; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Whether the AST is currently being rebuilt to correct immediate /// invocations. Immediate invocation candidates and references to consteval /// functions aren't tracked when this is set. bool RebuildingImmediateInvocation = false; /// 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 namespace where coroutine components are defined. In standard, /// they are defined in std namespace. And in the previous implementation, /// they are defined in std::experimental namespace. NamespaceDecl *CoroTraitsNamespaceCache; /// 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; /// 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, /// In addition of being constant evaluated, the current expression /// occurs in an immediate function context - either a consteval function /// or a consteval if function. ImmediateFunctionContext, /// 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 }; using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; /// 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; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; MaybeODRUseExprSet SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// Expressions appearing as the LHS of a volatile assignment in this /// context. We produce a warning for these when popping the context if /// they are not discarded-value expressions nor unevaluated operands. SmallVector<Expr*, 2> VolatileAssignmentLHSs; /// Set of candidates for starting an immediate invocation. llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; /// Set of DeclRefExprs referencing a consteval function when used in a /// context not already known to be immediately invoked. llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; // A context can be nested in both a discarded statement context and // an immediate function context, so they need to be tracked independently. bool InDiscardedStatement; bool InImmediateFunctionContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext), InDiscardedStatement(false), InImmediateFunctionContext(false) {} bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated || Context == ExpressionEvaluationContext::ImmediateFunctionContext; } bool isImmediateFunctionContext() const { return Context == ExpressionEvaluationContext::ImmediateFunctionContext || (Context == ExpressionEvaluationContext::DiscardedStatement && InImmediateFunctionContext); } bool isDiscardedStatementContext() const { return Context == ExpressionEvaluationContext::DiscardedStatement || (Context == ExpressionEvaluationContext::ImmediateFunctionContext && InDiscardedStatement); } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. Also return the extra mangling decl if any. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. std::tuple<MangleNumberingContext *, Decl *> getCurrentMangleNumberContext(const DeclContext *DC); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl *, 2> Pair; public: SpecialMemberOverloadResult() {} 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. const 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; class GlobalMethodPool { public: using Lists = std::pair<ObjCMethodList, ObjCMethodList>; using iterator = llvm::DenseMap<Selector, Lists>::iterator; iterator begin() { return Methods.begin(); } iterator end() { return Methods.end(); } iterator find(Selector Sel) { return Methods.find(Sel); } std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) { return Methods.insert(Val); } int count(Selector Sel) const { return Methods.count(Sel); } bool empty() const { return Methods.empty(); } private: llvm::DenseMap<Selector, Lists> Methods; }; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// Kinds of defaulted comparison operator functions. enum class DefaultedComparisonKind : unsigned char { /// This is not a defaultable comparison operator. None, /// This is an operator== that should be implemented as a series of /// subobject comparisons. Equal, /// This is an operator<=> that should be implemented as a series of /// subobject comparisons. ThreeWay, /// This is an operator!= that should be implemented as a rewrite in terms /// of a == comparison. NotEqual, /// This is an <, <=, >, or >= that should be implemented as a rewrite in /// terms of a <=> comparison. Relational, }; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the CurFPFeatures state on entry/exit of compound /// statements. class FPFeaturesStateRAII { public: FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { OldOverrides = S.FpPragmaStack.CurrentValue; } ~FPFeaturesStateRAII() { S.CurFPFeatures = OldFPFeaturesState; S.FpPragmaStack.CurrentValue = OldOverrides; } FPOptionsOverride getOverrides() { return OldOverrides; } private: Sema& S; FPOptions OldFPFeaturesState; FPOptionsOverride OldOverrides; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; /// Increment when we find a reference; decrement when we find an ignored /// assignment. Ultimately the value is 0 if every reference is an ignored /// assignment. llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments; Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo; 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(); /// This virtual key function only exists to limit the emission of debug info /// describing the Sema class. GCC and Clang only emit debug info for a class /// with a vtable when the vtable is emitted. Sema is final and not /// polymorphic, but the debug info size savings are so significant that it is /// worth adding a vtable just to take advantage of this optimization. virtual void anchor(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getCurFPFeatures() { return CurFPFeatures; } 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; } DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc, StringRef Platform); ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Warn that the stack is nearly exhausted. void warnStackExhausted(SourceLocation Loc); /// Run some code with "sufficient" stack space. (Currently, at least 256K is /// guaranteed). Produces a warning if we're low on stack space and allocates /// more in that case. Use this in code that may recurse deeply (for example, /// in template instantiation) to avoid stack overflow. void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref<void()> Fn); /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. ImmediateDiagBuilder 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 ImmediateDiagBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} ImmediateDiagBuilder(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 ~ImmediateDiagBuilder is a safe no-op // in that case anwyay. ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default; ~ImmediateDiagBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First 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. 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 ImmediateDiagBuilder & operator<<(const ImmediateDiagBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const ImmediateDiagBuilder &operator<<(T &&V) const { const DiagnosticBuilder &BaseDiag = *this; BaseDiag << std::move(V); return *this; } }; /// A generic diagnostic builder for 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 SemaDiagnosticBuilder { 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 }; SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S); SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D); SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default; ~SemaDiagnosticBuilder(); bool isImmediate() const { return ImmediateDiag.hasValue(); } /// 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 (SemaDiagnosticBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a SemaDiagnosticBuilder yourself. operator bool() const { return isImmediate(); } template <typename T> friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &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; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const SemaDiagnosticBuilder &operator<<(T &&V) const { if (ImmediateDiag.hasValue()) *ImmediateDiag << std::move(V); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V); return *this; } friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) { if (Diag.ImmediateDiag.hasValue()) PD.Emit(*Diag.ImmediateDiag); else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD; return Diag; } void AddFixItHint(const FixItHint &Hint) const { if (ImmediateDiag.hasValue()) ImmediateDiag->AddFixItHint(Hint); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint); } friend ExprResult ExprError(const SemaDiagnosticBuilder &) { return ExprError(); } friend StmtResult StmtError(const SemaDiagnosticBuilder &) { return StmtError(); } operator ExprResult() const { return ExprError(); } operator StmtResult() const { return StmtError(); } operator TypeResult() const { return TypeError(); } operator DeclResult() const { return DeclResult(true); } operator MemInitResult() const { return MemInitResult(true); } 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<ImmediateDiagBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Is the last error level diagnostic immediate. This is used to determined /// whether the next info diagnostic should be immediate. bool IsLastErrorImmediate = true; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint = false); /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint = false); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h /// Whether deferrable diagnostics should be deferred. bool DeferDiags = false; /// RAII class to control scope of DeferDiags. class DeferDiagsRAII { Sema &S; bool SavedDeferDiags = false; public: DeferDiagsRAII(Sema &S, bool DeferDiags) : S(S), SavedDeferDiags(S.DeferDiags) { S.DeferDiags = DeferDiags; } ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; } }; /// Whether uncompilable error has occurred. This includes error happens /// in deferred diagnostics. bool hasUncompilableErrorOccurred() const; 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; /// Invent a new identifier for parameters of abbreviated templates. IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, unsigned Index); void emitAndClearUnusedLocalTypedefWarnings(); private: /// Function or variable declarations to be checked for whether the deferred /// diagnostics should be emitted. llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags; public: // Emit all deferred diagnostics. void emitDeferredDiags(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void setFunctionHasMustTail(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// Retrieve the current function, if any, that should be analyzed for /// potential availability violations. sema::FunctionScopeInfo *getCurFunctionAvailabilityContext(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } /// Called before parsing a function declarator belonging to a function /// declaration. void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth); /// Called after parsing a function declarator belonging to a function /// declaration. void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); 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 BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, 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 Stmt *E); /// Determine whether the callee of a particular function call can throw. /// E, D and Loc are all optional. static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, SourceLocation Loc = SourceLocation()); 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 { protected: unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, std::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, std::index_sequence_for<Ts...>()); DB << T; } }; /// Do a check to make sure \p Name looks like a legal argument for the /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name /// is invalid for the given declaration. /// /// \p AL is used to provide caret diagnostics in case of a malformed name. /// /// \returns true if the name is a valid swift name for \p D, false otherwise. bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, const ParsedAttr &AL, bool IsAsync); /// A derivative of BoundTypeDiagnoser for which the diagnostic's type /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. /// For example, a diagnostic with no other parameters would generally have /// the form "...%select{incomplete|sizeless}0 type %1...". template <typename... Ts> class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { public: SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); this->emit(DB, std::index_sequence_for<Ts...>()); DB << T->isSizelessType() << T; } }; enum class CompleteTypeKind { /// Apply the normal rules for complete types. In particular, /// treat all sizeless types as incomplete. Normal, /// Relax the normal rules for complete types so that they include /// sizeless built-in types. AcceptSizeless, // FIXME: Eventually we should flip the default to Normal and opt in // to AcceptSizeless rather than opt out of it. Default = AcceptSizeless }; 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, CompleteTypeKind Kind, 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; } /// Helper function to judge if we are in module purview. /// Return false if we are not in a module. bool isCurrentModulePurview() const { return getCurrentModule() ? getCurrentModule()->isModulePurview() : false; } /// Enter the scope of the global module. Module *PushGlobalModuleFragment(SourceLocation BeginLoc, bool IsImplicit); /// Leave the scope of the global module. void PopGlobalModuleFragment(); VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(const 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); // When loading a non-modular PCH files, this is used to restore module // visibility. void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { VisibleModules.setVisible(Mod, ImportLoc); } /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return D->isUnconditionallyVisible() || 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, CompleteTypeKind Kind = CompleteTypeKind::Default) { return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, unsigned DiagID); bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); } bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, 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); } template <typename... Ts> bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); } /// Get the type of expression E, triggering instantiation to complete the /// type if necessary -- that is, if the expression refers to a templated /// static data member of incomplete array type. /// /// May still return an incomplete type if instantiation was not possible or /// if the type is incomplete for a different reason. Use /// RequireCompleteExprType instead if a diagnostic is expected for an /// incomplete expression type. QualType getCompletedType(Expr *E); void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, 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, CompleteTypeKind::Default, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Normal, 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); // Returns the underlying type of a decltype with the given expression. QualType getDecltypeForExpr(Expr *E); QualType BuildTypeofExprType(Expr *E); /// 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, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { /// This name is not a type or template in this context, but might be /// something else. NC_Unknown, /// Classification failed; an error has been produced. NC_Error, /// The name has been typo-corrected to a keyword. NC_Keyword, /// The name was classified as a type. NC_Type, /// The name was classified as a specific non-type, non-template /// declaration. ActOnNameClassifiedAsNonType should be called to /// convert the declaration to an expression. NC_NonType, /// The name was classified as an ADL-only function name. /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the /// result to an expression. NC_UndeclaredNonType, /// The name denotes a member of a dependent type that could not be /// resolved. ActOnNameClassifiedAsDependentNonType should be called to /// convert the result to an expression. NC_DependentNonType, /// The name was classified as an overload set, and an expression /// representing that overload set has been formed. /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable /// expression referencing the overload set. NC_OverloadSet, /// The name was classified as a template whose specializations are types. NC_TypeTemplate, /// The name was classified as a variable template name. NC_VarTemplate, /// The name was classified as a function template name. NC_FunctionTemplate, /// The name was classified as an ADL-only function template name. NC_UndeclaredTemplate, /// The name was classified as a concept name. NC_Concept, }; class NameClassification { NameClassificationKind Kind; union { ExprResult Expr; NamedDecl *NonTypeDecl; TemplateName Template; ParsedType Type; }; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification OverloadSet(ExprResult E) { NameClassification Result(NC_OverloadSet); Result.Expr = E; return Result; } static NameClassification NonType(NamedDecl *D) { NameClassification Result(NC_NonType); Result.NonTypeDecl = D; return Result; } static NameClassification UndeclaredNonType() { return NameClassification(NC_UndeclaredNonType); } static NameClassification DependentNonType() { return NameClassification(NC_DependentNonType); } static NameClassification TypeTemplate(TemplateName Name) { NameClassification Result(NC_TypeTemplate); Result.Template = Name; return Result; } static NameClassification VarTemplate(TemplateName Name) { NameClassification Result(NC_VarTemplate); Result.Template = Name; return Result; } static NameClassification FunctionTemplate(TemplateName Name) { NameClassification Result(NC_FunctionTemplate); Result.Template = Name; return Result; } static NameClassification Concept(TemplateName Name) { NameClassification Result(NC_Concept); Result.Template = Name; return Result; } static NameClassification UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ExprResult getExpression() const { assert(Kind == NC_OverloadSet); return Expr; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } NamedDecl *getNonTypeDecl() const { assert(Kind == NC_NonType); return NonTypeDecl; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || 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_Concept: return TNK_Concept_template; case NC_UndeclaredTemplate: return TNK_Undeclared_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC = nullptr); /// Act on the result of classifying a name as an undeclared (ADL-only) /// non-type declaration. ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc); /// Act on the result of classifying a name as an undeclared member of a /// dependent base class. ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand); /// Act on the result of classifying a name as a specific non-type /// declaration. ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken); /// Act on the result of classifying a name as an overload set. ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); /// 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); void warnOnReservedIdentifier(const NamedDecl *D); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID); 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()); void diagnosePointerAuthDisabled(SourceLocation loc, SourceRange range); bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key); 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); NamedDecl *getShadowedDeclaration(const BindingDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); QualType adjustParameterTypeForObjCAutoRefCount(QualType T, SourceLocation NameLoc, TypeSourceInfo *TSInfo); 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); ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); void 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 ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); ExprResult ActOnRequiresClause(ExprResult ConstraintExpr); 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); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); /// For a defaulted function, the kind of defaulted function that it is. class DefaultedFunctionKind { CXXSpecialMember SpecialMember : 8; DefaultedComparisonKind Comparison : 8; public: DefaultedFunctionKind() : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { } DefaultedFunctionKind(CXXSpecialMember CSM) : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp) : SpecialMember(CXXInvalid), Comparison(Comp) {} bool isSpecialMember() const { return SpecialMember != CXXInvalid; } bool isComparison() const { return Comparison != DefaultedComparisonKind::None; } explicit operator bool() const { return isSpecialMember() || isComparison(); } CXXSpecialMember asSpecialMember() const { return SpecialMember; } DefaultedComparisonKind asComparison() const { return Comparison; } /// Get the index of this function kind for use in diagnostics. unsigned getDiagnosticIndex() const { static_assert(CXXInvalid > CXXDestructor, "invalid should have highest index"); static_assert((unsigned)DefaultedComparisonKind::None == 0, "none should be equal to zero"); return SpecialMember + (unsigned)Comparison; } }; DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { return getDefaultedFunctionKind(MD).asSpecialMember(); } DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, 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); /// 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); /// Enter a template parameter scope, after it's been associated with a particular /// DeclContext. Causes lookup within the scope to chain through enclosing contexts /// in the correct order. void EnterTemplatedContext(Scope *S, DeclContext *DC); /// 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, /// Merge availability attributes for an implementation of /// an optional protocol requirement. AMK_OptionalProtocolImplementation }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority); TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis); VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis); UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl); DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model); ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic); FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg); SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident); MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); WebAssemblyImportNameAttr *mergeImportNameAttr( Decl *D, const WebAssemblyImportNameAttr &AL); WebAssemblyImportModuleAttr *mergeImportModuleAttr( Decl *D, const WebAssemblyImportModuleAttr &AL); EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL); EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL); BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &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, bool ConsiderRequiresClauses = true); enum class AllowedExplicit { /// Allow no explicit functions to be used. None, /// Allow explicit conversion functions but not explicit constructors. Conversions, /// Allow both explicit conversion functions and explicit constructors. All }; ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit 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(QualType Param, QualType Arg); bool CanPerformAggregateInitializationForOverloadResolution( const InitializedEntity &Entity, InitListExpr *From); bool IsStringInit(Expr *Init, const ArrayType *AT); 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_ArrayBound, ///< Array bound in array declarator or new-expression. CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier. CCEK_Noexcept ///< Condition in a noexcept(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE, NamedDecl *Dest = nullptr); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false, OverloadCandidateParamOrder PO = {}); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, OverloadCandidateParamOrder PO = {}); bool CheckNonDependentConversions( FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}, OverloadCandidateParamOrder PO = {}); void AddConversionCandidate( CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddNonMemberOperatorCandidates( const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO = {}); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate( NamedDecl *Found, FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, 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 * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfSingleOverloadCandidate( 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); void AddOverloadedCallCandidates( LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet); // 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 CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL = true); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true, bool AllowRewrittenCandidates = true, FunctionDecl *DefaultedFn = nullptr); ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false, bool AllowRecovery = false); 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 a name following ~ in a destructor name. This is an ordinary /// lookup, but prefers tags to typedefs. LookupDestructorName, /// 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_StringTemplatePack, }; 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, SourceLocation TypoLoc); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupBuiltin(LookupResult &R); void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID); 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, 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, bool IsUDSuffix); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit = nullptr); bool isKnownName(StringRef name); /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. enum class FunctionEmissionStatus { Emitted, CUDADiscarded, // Discarded due to CUDA/HIP hostness OMPDiscarded, // Discarded due to OpenMP hostness TemplateDiscarded, // Discarded due to uninstantiated templates Unknown, }; FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, bool Final = false); // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param RecoverUncorrectedTypos If true, when typo correction fails, it /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. /// /// \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, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr( ExprResult ER, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), InitDecl, RecoverUncorrectedTypos, 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); //@} /// Attempts to produce a RecoveryExpr after some AST node cannot be created. ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef<Expr *> SubExprs, QualType T = QualType()); ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( FunctionDecl *FD); 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); /// Handles semantic checking for features that are common to all attributes, /// such as checking whether a parameter was properly specified, or the /// correct number of arguments were passed, etc. Returns true if the /// attribute has been diagnosed. bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A); bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A); /// Map any API notes provided for this declaration to attributes on the /// declaration. /// /// Triggered by declaration-attribute processing. void ProcessAPINotes(Decl *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); llvm::Error isValidSectionSpecifier(StringRef Str); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal, bool &HasDefault, bool &HasCommas, SmallVectorImpl<StringRef> &Strings); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel 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; /// Check whether a nullability type specifier can be added to the given /// type through some means not written in source (e.g. API notes). /// /// \param type The type to which the nullability specifier will be /// added. On success, this type will be updated appropriately. /// /// \param nullability The nullability specifier to add. /// /// \param diagLoc The location to use for diagnostics. /// /// \param allowArrayTypes Whether to accept nullability specifiers on an /// array type (e.g., because it will decay to a pointer). /// /// \param overrideExisting Whether to override an existing, locally-specified /// nullability specifier rather than complaining about the conflict. /// /// \returns true if nullability cannot be applied, false otherwise. bool checkImplicitNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability, SourceLocation diagLoc, bool allowArrayTypes, bool overrideExisting); /// Process the attributes before creating an attributed statement. Returns /// the semantic attributes that have been processed. void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesWithRange &InAttrs, SmallVectorImpl<const Attr *> &OutAttrs); 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); /// Returns default addr space for method qualifiers. LangAS getDefaultCXXMethodAddrSpace() const; 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 ActOnAfterCompoundStatementLeadingPragmas(); 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 BuildAttributedStmt(SourceLocation AttrsLoc, ArrayRef<const Attr *> Attrs, Stmt *SubStmt); StmtResult ActOnAttributedStmt(const ParsedAttributesWithRange &AttrList, Stmt *SubStmt); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, ConditionResult Cond, SourceLocation RParenLoc, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); struct NamedReturnInfo { const VarDecl *Candidate; enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable }; Status S; bool isMoveEligible() const { return S != None; }; bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; } }; enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn }; NamedReturnInfo getNamedReturnInfo( Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal); NamedReturnInfo getNamedReturnInfo(const VarDecl *VD); const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves = false); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery = false); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, NamedReturnInfo &NRInfo, bool SupressSimplerImplicitMoves); 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, unsigned DiagID); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// If VD is set but not otherwise used, diagnose, for a parameter or a /// variable. void DiagnoseUnusedButSetDecl(const VarDecl *VD); /// 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() { ParsingClassDepth++; return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { ParsingClassDepth--; 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); void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult CheckUnevaluatedOperand(Expr *E); void CheckUnusedVolatileAssignment(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false, ArrayRef<const Expr *> StopAt = None); /// 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); /// Try to convert an expression \p E to type \p Ty. Returns the result of the /// conversion. ExprResult tryConvertExprToType(Expr *E, QualType Ty); /// Conditionally issue a diagnostic based on the statements's reachability /// analysis. /// /// \param Stmts If Stmts is non-empty, 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 DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, const PartialDiagnostic &PD); /// 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 DiagnoseDependentMemberLookup(LookupResult &R); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II); ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); /// If \p D cannot be odr-used in the current expression evaluation context, /// return a reason explaining why. Otherwise, return NOUR_None. NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr( const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, UnresolvedLookupExpr *AsULE = nullptr); 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 BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, TypeSourceInfo *TSI); ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, ParsedType ParsedTy); 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 CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc); ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, SourceLocation RParenLoc, ArrayRef<Expr *> Dims, ArrayRef<SourceRange> Brackets); /// Data structure for iterator expression. struct OMPIteratorData { IdentifierInfo *DeclIdent = nullptr; SourceLocation DeclIdentLoc; ParsedType Type; OMPIteratorExpr::IteratorRange Range; SourceLocation AssignLoc; SourceLocation ColonLoc; SourceLocation SecColonLoc; }; ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc, ArrayRef<OMPIteratorData> Data); // 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, bool AllowRecovery = false); Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs); enum class AtomicArgumentOrder { API, AST }; ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init); private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); public: ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions); 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(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth); // 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); ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, 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(); NamespaceDecl *getCachedCoroNamespace() { return CoroTraitsNamespaceCache; } 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: enum class ComparisonCategoryUsage { /// The '<=>' operator was used in an expression and a builtin operator /// was selected. OperatorInExpression, /// A defaulted 'operator<=>' needed the comparison category. This /// typically only applies to 'std::strong_ordering', due to the implicit /// fallback return value. DefaultedOperator, }; /// 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, ComparisonCategoryUsage Usage); /// 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 FilterUsingLookup(Scope *S, LookupResult &lookup); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 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, const LookupResult *R = nullptr, const UsingDecl *UD = nullptr); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists); NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, EnumDecl *ED); 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 *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, const DeclSpec &); 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) { CalledStmt(E); } /// Integrate an invoked statement into the collected data. void CalledStmt(Stmt *S); /// 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; } }; /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(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); /// Produce notes explaining why a defaulted function was defined as deleted. void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); /// 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); /// Wrap the expression in a ConstantExpr if it is a potential immediate /// invocation. ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, 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); // Checks that the vector type should be initialized from a scalar // by splatting the value rather than populating a single element. // This is the case for AltiVecVector types as well as with // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified. bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy); // Checks if the -faltivec-src-compat=gcc option is specified. // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are // treated the same way as they are when trying to initialize // these vectors on gcc (an error is emitted). bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy); /// ActOnCXXNamedCast - Parse /// {dynamic,static,reinterpret,const,addrspace}_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(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, 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); // Complete an enum decl, maybe without a scope spec. bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS = nullptr); 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, Expr *TrailingRequiresClause); /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, Optional<std::tuple<bool, unsigned, 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, ExprResult RequiresClause); /// 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, CallingConv CC); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); /// Check whether the given expression is a valid constraint expression. /// A diagnostic is emitted if it is not, false is returned, and /// PossibleNonPrimary will be set to true if the failure might be due to a /// non-primary expression being used as an atomic constraint. bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), bool *PossibleNonPrimary = nullptr, bool IsTrailingRequiresClause = false); private: /// Caches pairs of template-like decls whose associated constraints were /// checked for subsumption and whether or not the first's constraints did in /// fact subsume the second's. llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; /// Caches the normalized associated constraints of declarations (concepts or /// constrained declarations). If an error occurred while normalizing the /// associated constraints of the template or concept, nullptr will be cached /// here. llvm::DenseMap<NamedDecl *, NormalizedConstraint *> NormalizationCache; llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> SatisfactionCache; public: const NormalizedConstraint * getNormalizedAssociatedConstraints( NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); /// \brief Check whether the given declaration's associated constraints are /// at least as constrained than another declaration's according to the /// partial ordering of constraints. /// /// \param Result If no error occurred, receives the result of true if D1 is /// at least constrained than D2, and false otherwise. /// /// \returns true if an error occurred, false otherwise. bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2, bool &Result); /// If D1 was not at least as constrained as D2, but would've been if a pair /// of atomic constraints involved had been declared in a concept and not /// repeated in two separate places in code. /// \returns true if such a diagnostic was emitted, false otherwise. bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); /// \brief Check whether the given list of constraint expressions are /// satisfied (as if in a 'conjunction') given template arguments. /// \param Template the template-like entity that triggered the constraints /// check (either a concept or a constrained entity). /// \param ConstraintExprs a list of constraint expressions, treated as if /// they were 'AND'ed together. /// \param TemplateArgs the list of template arguments to substitute into the /// constraint expression. /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// \param Satisfaction if true is returned, will contain details of the /// satisfaction, with enough information to diagnose an unsatisfied /// expression. /// \returns true if an error occurred and satisfaction could not be checked, /// false otherwise. bool CheckConstraintSatisfaction( const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); /// \brief Check whether the given non-dependent constraint expression is /// satisfied. Returns false and updates Satisfaction with the satisfaction /// verdict if successful, emits a diagnostic and returns true if an error /// occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, ConstraintSatisfaction &Satisfaction); /// Check whether the given function decl's trailing requires clause is /// satisfied, if any. Returns false and updates Satisfaction with the /// satisfaction verdict if successful, emits a diagnostic and returns true if /// an error occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc = SourceLocation()); /// \brief Ensure that the given template arguments satisfy the constraints /// associated with the given template, emitting a diagnostic if they do not. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateArgs The converted, canonicalized template arguments. /// /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// /// \returns true if the constrains are not satisfied or could not be checked /// for satisfaction, false if the constraints are satisfied. bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. /// \param First whether this is the first time an unsatisfied constraint is /// diagnosed for this error. void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First = true); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. void DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, bool First = true); // 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); /// Mark destructors of virtual bases of this class referenced. In the Itanium /// C++ ABI, this is done when emitting a destructor for any non-abstract /// class. In the Microsoft C++ ABI, this is done any time a class's /// destructor is referenced. void MarkVirtualBaseDestructorsReferenced( SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); /// Do semantic checks to allow the complete destructor variant to be emitted /// when the destructor is defined in another translation unit. In the Itanium /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they /// can be emitted in separate TUs. To emit the complete variant, run a subset /// of the checks performed when emitting a regular destructor. void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly = false); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); /// Add gsl::Pointer attribute to std::container::iterator /// \param ND The declaration that introduces the name /// std::container::iterator. \param UnderlyingRecord The record named by ND. void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); /// Add [[gsl::Pointer]] attributes for std:: types. void inferGslPointerAttribute(TypedefNameDecl *TD); void CheckCompletedCXXClass(Scope *S, 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(); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref<Scope *()> EnterScope); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM); void CheckDelayedMemberExceptionSpecs(); bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK); void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship); void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK); //===--------------------------------------------------------------------===// // C++ Derived Classes // /// ActOnBaseSpecifier - Parsed a base specifier CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc); BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc); bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbiguousBaseConvID, 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, bool Inconsistent); /// 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 isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType) { return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, SourceLocation(), PDiag()); } 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. static NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; /// Whether and why a template name is required in this lookup. class RequiredTemplateKind { public: /// Template name is required if TemplateKWLoc is valid. RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) : TemplateKW(TemplateKWLoc) {} /// Template name is unconditionally required. RequiredTemplateKind(TemplateNameIsRequiredTag) {} SourceLocation getTemplateKeywordLoc() const { return TemplateKW.getValueOr(SourceLocation()); } bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } bool isRequired() const { return TemplateKW != SourceLocation(); } explicit operator bool() const { return isRequired(); } private: llvm::Optional<SourceLocation> TemplateKW; }; 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, RequiredTemplateKind RequiredTemplate = SourceLocation(), AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation = false); /// 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, bool HasTypeConstraint); bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack); bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool RequireStructuralType(QualType T, SourceLocation Loc); 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, bool SuppressDiagnostic = false); 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); /// Get a template argument mapping the given template parameter to itself, /// e.g. for X in \c template<int X>, this would return an expression template /// argument referencing X. TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location); 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); /// Get the specialization of the given variable template corresponding to /// the specified argument list, or a null-but-valid result if the arguments /// are dependent. DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); /// Form a reference to the specialization of the given variable template /// corresponding to the specified argument list, or a null-but-valid result /// if the arguments are dependent. ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnTemplateName( 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, CXXScopeSpec &SS, 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. /// /// \param ConstraintsNotSatisfied If provided, and an error occured, will /// receive true if the cause for the error is the associated constraints of /// the template not being satisfied by the template arguments. /// /// \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 *ConstraintsNotSatisfied = nullptr); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, 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 **TSI, bool DeducedTSTContext); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, bool DeducedTSTContext = true); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); //===--------------------------------------------------------------------===// // C++ Concepts //===--------------------------------------------------------------------===// Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef<ParmVarDecl *> LocalParameters, Scope *BodyScope); void ActOnFinishRequiresExpr(); concepts::Requirement *ActOnSimpleRequirement(Expr *E); concepts::Requirement *ActOnTypeRequirement( SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); concepts::Requirement *ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc); concepts::Requirement * ActOnCompoundRequirement( Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, unsigned Depth); concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); concepts::ExprRequirement * BuildExprRequirement( Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::ExprRequirement * BuildExprRequirement( concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); concepts::TypeRequirement * BuildTypeRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); concepts::NestedRequirement *BuildNestedRequirement(Expr *E); concepts::NestedRequirement * BuildNestedRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> LocalParameters, ArrayRef<concepts::Requirement *> Requirements, SourceLocation ClosingBraceLoc); //===--------------------------------------------------------------------===// // 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, /// A type constraint. UPPC_TypeConstraint, // A requirement in a requires-expression. UPPC_Requirement, // A requires-clause. UPPC_RequiresClause, }; /// 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 requirees-expression contains an unexpanded reference to one /// of its own parameter packs, diagnose the error. /// /// \param RE The requiress-expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); /// 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, /// The deduced arguments did not satisfy the constraints associated /// with the template. TDK_ConstraintsNotSatisfied, /// 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); // Substitute auto in TypeWithAuto for a Dependent auto type QualType SubstAutoTypeDependent(QualType TypeWithAuto); // Substitute auto in TypeWithAuto for a Dependent auto type TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto); /// 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); TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *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, bool IgnoreConstraints = false); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); 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, bool Reversed = false); 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 *PParam, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); 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 instantiating a requirement of a requires expression. RequirementInstantiation, /// We are checking the satisfaction of a nested requirement of a requires /// expression. NestedRequirementConstraintsCheck, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are declaring an implicit 'operator==' for a defaulted /// 'operator<=>'. DeclaringImplicitEqualityComparison, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, // We are checking the constraints associated with a constrained entity or // the constraint expression of a concept. This includes the checks that // atomic constraints have the type 'bool' and that they can be constant // evaluated. ConstraintsCheck, // We are substituting template arguments into a constraint expression. ConstraintSubstitution, // We are normalizing a constraint expression. ConstraintNormalization, // We are substituting into the parameter mapping of an atomic constraint // during normalization. ParameterMappingSubstitution, /// We are rewriting a comparison operator in terms of an operator<=>. RewritingOperatorAsSpaceship, /// We are initializing a structured binding. InitializingStructuredBinding, /// We are marking a class as __dllexport. MarkingClassDllexported, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintsCheck {}; /// \brief Note that we are checking the constraints associated with some /// constrained entity (a concept declaration or a template with associated /// constraints). InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintsCheck, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintSubstitution {}; /// \brief Note that we are checking a constraint expression associated /// with a template declaration or as part of the satisfaction check of a /// concept. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, NamedDecl *Template, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange); struct ConstraintNormalization {}; /// \brief Note that we are normalizing a constraint expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintNormalization, NamedDecl *Template, SourceRange InstantiationRange); struct ParameterMappingSubstitution {}; /// \brief Note that we are subtituting into the parameter mapping of an /// atomic constraint during constraint normalization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParameterMappingSubstitution, NamedDecl *Template, SourceRange InstantiationRange); /// \brief Note that we are substituting template arguments into a part of /// a requirement of a requires expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// \brief Note that we are checking the satisfaction of the constraint /// expression inside of a nested requirement. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::NestedRequirement *Req, ConstraintsCheck, SourceRange InstantiationRange = SourceRange()); /// 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(); } bool isImmediateFunctionContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isImmediateFunctionContext(); } /// 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. if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } else { // Template instantiations in the PCH may be delayed until the TU. S.PendingInstantiations.swap(SavedPendingInstantiations); S.PendingInstantiations.insert(S.PendingInstantiations.end(), SavedPendingInstantiations.begin(), SavedPendingInstantiations.end()); } } 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); bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the name and return type of a defaulted 'operator<=>' to form /// an implicit 'operator=='. FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship); 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); void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor); 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 SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); bool CheckInstantiatedFunctionTemplateConstraints( SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef<TemplateArgument> TemplateArgs, ConstraintSatisfaction &Satisfaction); 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, 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); void deduceOpenCLAddressSpace(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 CheckConversionToObjCLiteral(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 }; /// Check whether the declared result type of the given Objective-C /// method declaration is compatible with the method's class. ResultTypeCompatibilityKind checkRelatedResultTypeCompatibility(const ObjCMethodDecl *Method, const ObjCInterfaceDecl *CurrentClass); void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, ObjCMethodDecl *overridden); 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 PragmaAlignPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaAlignPack(); /// 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, MSVtorDispMode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *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); /// Are precise floating point semantics currently enabled? bool isPreciseFPEnabled() { return !CurFPFeatures.getAllowFPReassociate() && !CurFPFeatures.getNoSignedZero() && !CurFPFeatures.getAllowReciprocal() && !CurFPFeatures.getAllowApproxFunc(); } /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, PragmaFloatControlKind 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(SourceLocation Loc, LangOptions::FPModeKind FPC); /// Called on well formed /// \#pragma clang fp reassociate void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); /// Called on well formed '\#pragma clang fp' that has option 'exceptions'. void ActOnPragmaFPExceptions(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// Called to set constant rounding mode for floating point operations. void setRoundingMode(SourceLocation Loc, llvm::RoundingMode); /// Called to set exception behavior for floating point operations. void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// 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); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion); void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D. void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef<Expr *> Args); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation = false); void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); /// Lookup 'coroutine_traits' in std namespace and std::experimental /// namespace. The namespace found is recorded in Namespace. ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc, NamespaceDecl *&Namespace); /// Check that the expression co_await promise.final_suspend() shall not be /// potentially-throwing. bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; struct DeclareTargetContextInfo { struct MapInfo { OMPDeclareTargetDeclAttr::MapTypeTy MT; SourceLocation Loc; }; /// Explicitly listed variables and functions in a 'to' or 'link' clause. llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped; /// The 'device_type' as parsed from the clause. OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any; /// The directive kind, `begin declare target` or `declare target`. OpenMPDirectiveKind Kind; /// The directive with indirect clause. Optional<Expr *> Indirect; /// The directive location. SourceLocation Loc; DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc) : Kind(Kind), Loc(Loc) {} }; /// Number of nested '#pragma omp declare target' directives. SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true, bool SuppressExprDiags = false); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Returns the number of scopes associated with the construct on the given /// OpenMP level. int getNumberOfConstructScopes(unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Analyzes and checks a loop nest for use by a loop transformation. /// /// \param Kind The loop transformation directive kind. /// \param NumLoops How many nested loops the directive is expecting. /// \param AStmt Associated statement of the transformation directive. /// \param LoopHelpers [out] The loop analysis result. /// \param Body [out] The body code nested in \p NumLoops loop. /// \param OriginalInits [out] Collection of statements and declarations that /// must have been executed/declared before entering the /// loop. /// /// \return Whether there was any error. bool checkTransformableLoopNest( OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops, SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers, Stmt *&Body, SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>> &OriginalInits); /// Helper to keep information about the current `omp begin/end declare /// variant` nesting. struct OMPDeclareVariantScope { /// The associated OpenMP context selector. OMPTraitInfo *TI; /// The associated OpenMP context selector mangling. std::string NameSuffix; OMPDeclareVariantScope(OMPTraitInfo &TI); }; /// Return the OMPTraitInfo for the surrounding scope, if any. OMPTraitInfo *getOMPTraitInfoForSurroundingScope() { return OMPDeclareVariantScopes.empty() ? nullptr : OMPDeclareVariantScopes.back().TI; } /// The current `omp begin/end declare variant` scopes. SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; /// The current `omp begin/end assumes` scopes. SmallVector<AssumptionAttr *, 4> OMPAssumeScoped; /// All `omp assumes` we encountered so far. SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal; public: /// The declarator \p D defines a function in the scope \p S which is nested /// in an `omp begin/end declare variant` scope. In this method we create a /// declaration for \p D and rename \p D according to the OpenMP context /// selector of the surrounding scope. Return all base functions in \p Bases. void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl<FunctionDecl *> &Bases); /// Register \p D as specialization of all base functions in \p Bases in the /// current `omp begin/end declare variant` scope. void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( Decl *D, SmallVectorImpl<FunctionDecl *> &Bases); /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`. void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D); /// Can we exit an OpenMP declare variant scope at the moment. bool isInOpenMPDeclareVariantScope() const { return !OMPDeclareVariantScopes.empty(); } /// Given the potential call expression \p Call, determine if there is a /// specialization via the OpenMP declare variant mechanism available. If /// there is, return the specialized call expression, otherwise return the /// original \p Call. ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig); /// Handle a `omp begin declare variant`. void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); /// Handle a `omp end declare variant`. void ActOnOpenMPEndDeclareVariant(); /// Checks if the variant/multiversion functions are compatible. bool areMultiversionVariantFunctionsCompatible( const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer); /// Function tries to capture lambda's captured variables in the OpenMP region /// before the original lambda is captured. void tryCaptureOpenMPLambdas(ValueDecl *V); /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, unsigned StopAt = 0); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// If the current region is a range loop-based region, mark the start of the /// loop construct. void startOpenMPCXXRangeFor(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) 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, unsigned CaptureLevel) const; /// Check if the specified global variable must be captured by outer capture /// regions. /// \param Level Relative level of nested OpenMP construct for that /// the check is performed. bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) 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); /// Called on well-formed '\#pragma omp metadirective' after parsing /// of the associated statement. StmtResult ActOnOpenMPMetaDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); // 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 [begin] assume[s]'. void ActOnOpenMPAssumesDirective(SourceLocation Loc, OpenMPDirectiveKind DKind, ArrayRef<std::string> Assumptions, bool SkippedClauses); /// Check if there is an active global `omp begin assumes` directive. bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); } /// Check if there is an active global `omp assumes` directive. bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); } /// Called on well-formed '#pragma omp end assumes'. void ActOnOpenMPEndAssumesDirective(); /// 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'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const; const ValueDecl *getOpenMPDeclareMapperVarName() const; /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); /// Called at the end of target region i.e. '#pragma omp end declare target'. const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective(); /// Called once a target context is completed, that can be when a /// '#pragma omp end declare target' was encountered or when a /// '#pragma omp declare target' without declaration-definition-seq was /// encountered. void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, DeclareTargetContextInfo &DTCI); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return !DeclareTargetNesting.empty(); } /// 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); /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to /// an OpenMP loop directive. StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt); /// Process a canonical OpenMP loop nest that can either be a canonical /// literal loop (ForStmt or CXXForRangeStmt), or the generated loop of an /// OpenMP loop transformation construct. StmtResult ActOnOpenMPLoopnest(Stmt *AStmt); /// 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 tile' after parsing of its clauses and /// the associated statement. StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '#pragma omp unroll' after parsing of its clauses /// and the associated statement. StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// 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 master' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// 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(ArrayRef<OMPClause *> Clauses, 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 depobj'. StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp scan'. StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( 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); /// Called on well-formed '\#pragma omp interop'. StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp dispatch' after parsing of the // /associated statement. StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp masked' after parsing of the // /associated statement. StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp loop' after parsing of the /// associated statement. StmtResult ActOnOpenMPGenericLoopDirective( 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, bool IsDeclareSimd = false); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); /// Checks '\#pragma omp declare variant' variant function and original /// functions after parsing of the associated method/function. /// \param DG Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The trait info object representing the match clause. /// \param NumAppendArgs The number of omp_interop_t arguments to account for /// in checking. /// \returns None, if the function/variant function are not compatible with /// the pragma, pair of original function/variant ref expression otherwise. Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, unsigned NumAppendArgs, SourceRange SR); /// Called on well-formed '\#pragma omp declare variant' after parsing of /// the associated method/function. /// \param FD Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The context traits associated with the function variant. /// \param AdjustArgsNothing The list of 'nothing' arguments. /// \param AdjustArgsNeedDevicePtr The list of 'need_device_ptr' arguments. /// \param AppendArgs The list of 'append_args' arguments. /// \param AdjustArgsLoc The Location of an 'adjust_args' clause. /// \param AppendArgsLoc The Location of an 'append_args' clause. /// \param SR The SourceRange of the 'declare variant' directive. void ActOnOpenMPDeclareVariantDirective( FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, ArrayRef<Expr *> AdjustArgsNothing, ArrayRef<Expr *> AdjustArgsNeedDevicePtr, ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs, SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, 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 'align' clause. OMPClause *ActOnOpenMPAlignClause(Expr *Alignment, 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-form 'sizes' clause. OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-form 'full' clauses. OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-form 'partial' clauses. OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, 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); /// Called on well-formed 'detach' clause. OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'when' clause. OMPClause *ActOnOpenMPWhenClause(OMPTraitInfo &TI, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'order' clause. OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind 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 'compare' clause. OMPClause *ActOnOpenMPCompareClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acq_rel' clause. OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acquire' clause. OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'release' clause. OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'relaxed' clause. OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'init' clause. OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs, bool IsTarget, bool IsTargetSync, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'use' clause. OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'destroy' clause. OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'novariants' clause. OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'nocontext' clause. OMPClause *ActOnOpenMPNocontextClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'filter' clause. OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc, SourceLocation LParenLoc, 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 *DepModOrTailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, SourceLocation ExtraModifierLoc, ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc); /// Called on well-formed 'inclusive' clause. OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'exclusive' clause. OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// 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, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, 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, OpenMPReductionClauseModifier Modifier, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, 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 'depobj' pseudo clause. OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, 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, bool NoDiagnose = false, 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<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause * ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 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 'use_device_addr' clause. OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'nontemporal' clause. OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Data for list of allocators. struct UsesAllocatorsData { /// Allocator. Expr *Allocator = nullptr; /// Allocator traits. Expr *AllocatorTraits = nullptr; /// Locations of '(' and ')' symbols. SourceLocation LParenLoc, RParenLoc; }; /// Called on well-formed 'uses_allocators' clause. OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<UsesAllocatorsData> Data); /// Called on well-formed 'affinity' clause. OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators); /// Called on a well-formed 'bind' clause. OMPClause *ActOnOpenMPBindClause(OpenMPBindClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// 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_PRValue, 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 function is a no-op if the operand has a function type // or an 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 whether the given statement can have musttail applied to it, /// issuing a diagnostic and returning false if not. In the success case, /// the statement is rewritten to remove implicit nodes from the return /// value. bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA); private: /// Check whether the given statement can have musttail applied to it, /// issuing a diagnostic and returning false if not. bool checkMustTailAttr(const Stmt *St, const Attr &MTA); public: /// 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); /// Context in which we're performing a usual arithmetic conversion. enum ArithConvKind { /// An arithmetic operation. ACK_Arithmetic, /// A bitwise operation. ACK_BitwiseOp, /// A comparison. ACK_Comparison, /// A conditional (?:) operator. ACK_Conditional, /// A compound assignment expression. ACK_CompAssign, }; // 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, SourceLocation Loc, ArithConvKind ACK); /// 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, /// IncompatibleFunctionPointer - The assignment is between two function /// pointers types that are not compatible, but we accept them as an /// extension. IncompatibleFunctionPointer, /// 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, 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_PRValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 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); /// Type checking for matrix binary operators. QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); bool isValidSveBitcast(QualType srcType, QualType destType); bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy); bool areVectorTypesSameSize(QualType srcType, QualType destType); 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 }; // Fake up a scoped enumeration that still contextually converts to bool. struct ReferenceConversionsScope { /// The conversions that would be performed on an lvalue of type T2 when /// binding a reference of type T1 to it, as determined when evaluating /// whether T1 is reference-compatible with T2. enum ReferenceConversions { Qualification = 0x1, NestedQualification = 0x2, Function = 0x4, DerivedToBase = 0x8, ObjC = 0x10, ObjCLifetime = 0x20, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) }; }; using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv = nullptr); 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); // CheckMatrixCast - Check type constraints for matrix casts. // We allow casting between matrixes of the same dimensions i.e. when they // have the same number of rows and column. Returns true if the cast is // invalid. bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind); // 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. }; QualType PreferredConditionType(ConditionKind K) const { return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy; } ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK = false); 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 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) = 0; virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); virtual ~VerifyICEDiagnoser() {} }; enum AllowFoldKind { NoFold, AllowFold, }; /// 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, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, AllowFoldKind CanFold = NoFold) { return VerifyIntegerConstantExpression(E, nullptr, CanFold); } /// 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; /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics /// unless \p EmitOnBothSides is true. /// - 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. SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder 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. SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the host, emits the diagnostics immediately. /// - If CurContext is a non-host function, just ignore it. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD = nullptr); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, const PartialDiagnostic &PD, FunctionDecl *FD = nullptr) { return targetDiag(Loc, PD.getDiagID(), FD) << PD; } /// Check if the type is allowed to be used for the current target. void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D = nullptr); 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); enum CUDAVariableTarget { CVT_Device, /// Emitted on device side with a shadow variable on host side CVT_Host, /// Emitted on host side only CVT_Both, /// Emitted on both sides with different addresses CVT_Unified, /// Emitted as a unified address, e.g. managed variables }; /// Determines whether the given variable is emitted on host or device side. CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); // 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); /// May add implicit CUDAConstantAttr attribute to VD, depending on VD /// and current compilation settings. void MaybeAddCUDAConstantAttr(VarDecl *VD); 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); void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas by default is host device function unless it has explicit /// host or device attribute. 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); enum class AttributeCompletion { Attribute, Scope, None, }; void CodeCompleteAttribute( AttributeCommonInfo::Syntax Syntax, AttributeCompletion Completion = AttributeCompletion::Attribute, const IdentifierInfo *Scope = nullptr); /// Determines the preferred type of the current function argument, by /// examining the signatures of all possible overloads. /// Returns null if unknown or ambiguous, or if code completion is off. /// /// If the code completion point has been reached, also reports the function /// signatures that were considered. /// /// FIXME: rename to GuessCallArgumentType to reduce confusion. QualType ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc, bool Braced); QualType ProduceCtorInitMemberSignatureHelp( Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc, bool Braced); QualType ProduceTemplateArgumentSignatureHelp( TemplateTy, ArrayRef<ParsedTemplateArgument>, SourceLocation LAngleLoc); void CodeCompleteInitializer(Scope *S, Decl *D); /// Trigger code completion for a record of \p BaseType. \p InitExprs are /// expressions in the initializer list seen so far and \p D is the current /// Designation being parsed. void CodeCompleteDesignator(const QualType BaseType, llvm::ArrayRef<Expr *> InitExprs, const Designation &D); void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, bool IsUsingDeclaration, QualType BaseType, QualType PreferredType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteAfterFunctionEquals(Declarator &D); 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, QualType ThisType, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, StringRef ParamName, QualType ArgTy, QualType ParamTy); 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); bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, bool WantCDE); bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum); bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinComplex(CallExpr *TheCall); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum); 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 SemaBuiltinArithmeticFence(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, const char *TypeDesc); bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc); bool SemaBuiltinElementwiseMath(CallExpr *TheCall); bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall); bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall); // Matrix builtin handling. ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, ExprResult CallResult); 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 CheckFreeArguments(const CallExpr *E); 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(const 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 CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee); 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__Nullable_result = 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; bool isCFError(RecordDecl *D); /// 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; } /// Determine the number of levels of enclosing template parameters. This is /// only usable while parsing. Note that this does not include dependent /// contexts in which no template parameters have yet been declared, such as /// in a terse function template or generic lambda before the first 'auto' is /// encountered. unsigned getTemplateDepth(Scope *S) const; /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; private: int ParsingClassDepth = 0; 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"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); } }; /// 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() {} 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 }; /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurLexicalContext is a kernel function or it is known that the /// function will be emitted for the device, emits the diagnostics /// immediately. /// - If CurLexicalContext is a function and we are compiling /// for the device, but we don't know that this function will be codegen'ed /// for devive yet, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// Diagnose __float128 type usage only from SYCL device code if the current /// target doesn't support it /// if (!S.Context.getTargetInfo().hasFloat128Type() && /// S.getLangOpts().SYCLIsDevice) /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed, creates a deferred diagnostic to be emitted if /// and when the caller is codegen'ed, and returns true. /// /// - Otherwise, returns true without emitting any diagnostics. /// /// Adds Callee to DeviceCallGraph if we don't know if its caller will be /// codegen'ed yet. bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); void deepTypeCheckForSYCLDevice(SourceLocation UsedAt, llvm::DenseSet<QualType> Visited, ValueDecl *DeclToCheck); }; /// 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; }; template <> void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, AlignPackInfo Value); } // 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.getHashValue()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
DRB061-matrixvector1-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. */ /* Matrix-vector multiplication: outer-level loop parallelization */ #define N 100 #include <omp.h> double a[100][100]; double v[100]; double v_out[100]; int init() { int i; int j; int k; #pragma omp parallel for private (i,j) for (i = 0; i <= 99; i += 1) { #pragma omp parallel for private (j) for (j = 0; j <= 99; j += 1) { a[i][j] = (i * j) + 0.01; } v_out[i] = (i * j) + 0.01; v[i] = (i * j) + 0.01; } return 0; } int mv() { int i; int j; #pragma omp parallel for private (i,j) for (i = 0; i <= 99; i += 1) { double sum = 0.0; #pragma omp parallel for private (j) reduction (+:sum) for (j = 0; j <= 99; j += 1) { sum += a[i][j] * v[j]; } v_out[i] = sum; } return 0; } int print() { int i; int j; int k; for (i = 0; i <= 99; i += 1) { for (j = 0; j <= 99; j += 1) { printf("%lf\n",a[i][j]); } printf("%lf\n",v_out[i]); printf("%lf\n",v[i]); } return 0; } int main() { init(); mv(); print(); return 0; }
threads.c
#include <stdio.h> #include <omp.h> #include <string.h> #include <stdlib.h> int main() { //Determine which GPU type (NVIDIA or AMD) char* nvidia= "sm"; char* aomp_gpu= getenv("AOMP_GPU"); int isAMDGPU = 1; int masterWarpThread = -1; if(aomp_gpu && strstr(aomp_gpu, nvidia) != NULL) isAMDGPU = 0; int thread_id[1024] ; for (int i=0; i < 1024; i++) thread_id[i] = -1; //#pragma omp target map (tofrom: thread_id) #pragma omp target parallel for num_threads(1024) for (int i=0; i< 1024; i++) { if (i >950) printf ("Thread: %d\n", omp_get_thread_num()); thread_id[i] = omp_get_thread_num(); } // SPMD: if (thread_id[1023] == 1023 ) { int maxThrd = -1; for (int i=0; i < 1024; i++) { if (thread_id[i] > maxThrd) maxThrd = thread_id[i]; } printf("Max thread id %d\n", maxThrd); //Determine execution Mode if (maxThrd == 1023) printf("Running in SPMD Mode\n"); else printf("Running in Generic Mode\n"); //Verify Results int passed = 0; //Check SPMD results if (maxThrd == 1023) passed = 1; else{ //Check generic results if(isAMDGPU) maxThrd += 64; else maxThrd += 32; if (maxThrd == 1023) passed = 1; } if (passed){ printf("Passed!\n"); return 0; } else{ printf("Failed\n"); return 1; } }
mark_for_refinement.h
/* ============================================================================== KratosIncompressibleFluidApplication A library based on: Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi pooyan@cimne.upc.edu rrossi@cimne.upc.edu - CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain 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 condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS. 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. ============================================================================== */ // // Project Name: Kratos // Last Modified by: $Author: rrossi $ // Date: $Date: 2008-10-13 06:58:23 $ // Revision: $Revision: 1.4 $ // // #if !defined(KRATOS_MARK_FOR_REFINEMENT ) #define KRATOS_MARK_FOR_REFINEMENT // System includes #include <string> #include <iostream> #include <algorithm> // External includes // Project includes #include "includes/define.h" #include "includes/model_part.h" #include "includes/node.h" #include "utilities/geometry_utilities.h" #include "utilities/openmp_utils.h" #include "incompressible_fluid_application.h" namespace Kratos { ///@addtogroup IncompressibleFluidApplication ///@{ ///@name Kratos Classes ///@{ /// A class for dynamic mesh refinement. /** Provides several utility functions to refine the mesh during the solution procedure. The main function is MarkForRefinement, which chooses which elements to refine based on the value of an elemental variable and a user-defined tolerance */ class RefinementUtilities { public: ///@name Life Cycle ///@{ /// Default constructor RefinementUtilities() {} /// Destructor ~RefinementUtilities() {} ///@} ///@name Operations ///@{ /// Identify the elements that need to be refined. /** This class mark elements for refinement based on the elemental value of the variable given as input. If the value exceeds the given tolerance, the element will be marked for refinement. If an element is refined several times, this procedure may choose to refine its neighbours too, to avoid creating elements with poor shapes. @param rVariable The variable used to check which elements must be refined. It is assumed that another function will write, to allow for different refinement criteria @param ThisModelPart The model part containig the elements we want to refine @param DomainSize Number of spatial dimensions of the problem (2 or 3) @param admissible_ratio The refinement tolerance. All elements with a greater value of rVariable will be refined @param admissible_area Minimum area (or volume) for the new elements. Elements won't be refined if this results in elements smaller than this size. @param max_levels Maximum number of successive refinements on the same element */ void MarkForRefinement(Variable<double>& rVariable, ModelPart& ThisModelPart, unsigned int DomainSize, double admissible_ratio, double admissible_area, int max_levels) { KRATOS_TRY; //reset the nodal values for(ModelPart::NodesContainerType::iterator it=ThisModelPart.NodesBegin(); it!=ThisModelPart.NodesEnd(); it++) { it->GetValue(REFINEMENT_LEVEL) = 0; } //mark elements for splitting depending on the desired error ratio unsigned int large_error_elems = 0; for(ModelPart::ElementsContainerType::iterator it=ThisModelPart.ElementsBegin(); it!=ThisModelPart.ElementsEnd(); it++) { double ratio = it->GetValue(rVariable); if(ratio > admissible_ratio && it->GetValue(REFINEMENT_LEVEL) <= max_levels ) { //mark for splitting it->GetValue(SPLIT_ELEMENT) = true; int& current_level = it->GetValue(REFINEMENT_LEVEL); current_level += 1; large_error_elems++; //mark all of the nodes with the refinement level Geometry< Node<3> >& geom = it->GetGeometry(); for(unsigned int i=0; i<geom.size(); i++) { if(geom[i].GetValue(REFINEMENT_LEVEL) < current_level) { geom[i].GetValue(REFINEMENT_LEVEL) = current_level; } } } } bool is_ok = false; int nit = 0; while(is_ok==false && nit<2*max_levels) { is_ok = true; ModelPart::ElementsContainerType aux_elem_list; //fill a list with all of the elements that have to be refined to obtain a correct gradient for(ModelPart::ElementsContainerType::iterator it=ThisModelPart.ElementsBegin(); it!=ThisModelPart.ElementsEnd(); it++) { //mark all of the nodes with the refinement level Geometry< Node<3> >& geom = it->GetGeometry(); //determine for each element the maximum level of refinement (basically if the neighbours have been refined) int level = geom[0].GetValue(REFINEMENT_LEVEL); // int min_level = level; int max_level = level; for(unsigned int i=1; i<geom.size(); i++) { level = geom[i].GetValue(REFINEMENT_LEVEL); // if(level < min_level) min_level = level; if(level > max_level) max_level = level; } const int& current_level = it->GetValue(REFINEMENT_LEVEL); //if there is a difference of level of refinement greater than 1, then refine to have a smoother grading of elements if(max_level > current_level + 1 && current_level < max_levels) { //more iterations of the overall algorithm are needed is_ok = false; aux_elem_list.push_back( *(it.base()) ); } } //now signal such elements for spltting and color their nodes correctly for(ModelPart::ElementsContainerType::iterator it=aux_elem_list.begin(); it!=aux_elem_list.end(); it++) { int& current_level = it->GetValue(REFINEMENT_LEVEL); //mark for splitting it->GetValue(SPLIT_ELEMENT) = true; current_level += 1; //here we increase the level large_error_elems++; //mark all of the nodes with the refinement level Geometry< Node<3> >& geom = it->GetGeometry(); for(unsigned int i=0; i<geom.size(); i++) { if(geom[i].GetValue(REFINEMENT_LEVEL) < current_level) { geom[i].GetValue(REFINEMENT_LEVEL) = current_level; } } } //increase iterations of the grading algorithm nit += 1; } double MinSize,ElemSize; if (DomainSize == 2) { MinSize = admissible_area * 4.0; for( ModelPart::ElementIterator itElem = ThisModelPart.ElementsBegin(); itElem != ThisModelPart.ElementsEnd(); ++itElem) { ElemSize = GeometryUtils::CalculateVolume2D(itElem->GetGeometry()); if (ElemSize < MinSize) { itElem->SetValue(SPLIT_ELEMENT,false); } } } else // (DomainSize == 3) { MinSize = admissible_area * 8.0; for( ModelPart::ElementIterator itElem = ThisModelPart.ElementsBegin(); itElem != ThisModelPart.ElementsEnd(); ++itElem) { ElemSize = GeometryUtils::CalculateVolume3D(itElem->GetGeometry()); if (ElemSize < MinSize) { itElem->SetValue(SPLIT_ELEMENT,false); } } } unsigned int split_elems = 0; for ( ModelPart::ElementIterator itElem = ThisModelPart.ElementsBegin(); itElem != ThisModelPart.ElementsEnd(); ++itElem) { if(itElem->GetValue(SPLIT_ELEMENT) == true) split_elems++; } std::cout << "Refinement utility found " << large_error_elems << " with an error ratio over tolerance." << std::endl; std::cout << "Final number of refined elements: " << split_elems << std::endl; KRATOS_CATCH("") } void UpdateErrorRatio(ModelPart& rModelPart) { // Partitioning const int NumThreads = OpenMPUtils::GetNumThreads(); OpenMPUtils::PartitionVector ElementPartition; OpenMPUtils::DivideInPartitions(rModelPart.Elements().size(),NumThreads,ElementPartition); #pragma omp parallel { int k = OpenMPUtils::ThisThread(); // Initialize the iterator boundaries for this thread ModelPart::ElementsContainerType::iterator ElemBegin = rModelPart.ElementsBegin() + ElementPartition[k]; ModelPart::ElementsContainerType::iterator ElemEnd = rModelPart.ElementsBegin() + ElementPartition[k+1]; ProcessInfo& rProcessInfo = rModelPart.GetProcessInfo(); double Error; // Ask each element to calculate its Error ratio for( ModelPart::ElementsContainerType::iterator itElem = ElemBegin; itElem != ElemEnd; ++itElem) { itElem->Calculate(ERROR_RATIO,Error,rProcessInfo); } } } /// Calculate the subscale velocity on the model's mesh and use it to mark elements for refinement. /** This function is intended to work with VMS elements (and derived classes). It will call the element's Calculate method to estimate the error based on the relative magnitude of the subscale. The result will be stored in the variable ERROR_RATIO for each element. This refinement criteria is based on G. Hauke, M. Doweidar, M. Miana, The multiscale approach to error estimation and adaptivity, Computer Methods in Applied Mechanics and Engineering, Volume 195, Issues 13-16, 2006 @param rModelPart The model part containing the elements @see VMS for the calculation of the error ratio at the elemental level */ void SubscaleErrorEstimate(ModelPart& rModelPart) { // Partitioning const int NumThreads = OpenMPUtils::GetNumThreads(); OpenMPUtils::PartitionVector ElementPartition; OpenMPUtils::DivideInPartitions(rModelPart.Elements().size(),NumThreads,ElementPartition); // Initialize error values for( ModelPart::ElementIterator itElem = rModelPart.ElementsBegin(); itElem != rModelPart.ElementsEnd(); ++itElem) itElem->SetValue(ERROR_RATIO,0.0); //Compute average kinetic energy double Atot = 0.0; double avg_vel = 0.0; array_1d<double,3> vgauss; const double NodeFactor = 1.0 / static_cast<double>(rModelPart.ElementsBegin()->GetGeometry().size()); const int ElementsEnd = static_cast<unsigned int>(rModelPart.Elements().size()); #pragma omp parallel for reduction(+:Atot,avg_vel) for(int k=0; k< ElementsEnd; k++) { ModelPart::ElementsContainerType::iterator itElem = rModelPart.ElementsBegin()+k; Geometry<Node<3> >& geom = itElem->GetGeometry(); double Area = geom.Area(); noalias(vgauss) = geom[0].FastGetSolutionStepValue(VELOCITY); for(unsigned int i=1; i<geom.size(); i++) noalias(vgauss) += geom[i].FastGetSolutionStepValue(VELOCITY); double norm_v = norm_2(vgauss) * NodeFactor; avg_vel += Area*norm_v; Atot += Area; } avg_vel/=Atot; if(Atot < 1e-10) KRATOS_THROW_ERROR(std::logic_error,"area can not be zero!!","") #pragma omp parallel { int k = OpenMPUtils::ThisThread(); // Initialize the iterator boundaries for this thread ModelPart::ElementsContainerType::iterator ElemBegin = rModelPart.ElementsBegin() + ElementPartition[k]; ModelPart::ElementsContainerType::iterator ElemEnd = rModelPart.ElementsBegin() + ElementPartition[k+1]; ProcessInfo& rProcessInfo = rModelPart.GetProcessInfo(); double Error; // Ask each element to calculate its Error ratio for( ModelPart::ElementsContainerType::iterator itElem = ElemBegin; itElem != ElemEnd; ++itElem) { itElem->Calculate(ERROR_RATIO,Error,rProcessInfo); Error/=avg_vel; itElem->SetValue(ERROR_RATIO,Error); } } } ///@} //Operators private: }; ///@} //Kratos Classes ///@} } // namespace Kratos. #endif // KRATOS_MARK_FOR_REFINEMENT defined
GB_unop__sinh_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__sinh_fc64_fc64 // op(A') function: GB_unop_tran__sinh_fc64_fc64 // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = csinh (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = csinh (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = csinh (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_SINH || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__sinh_fc64_fc64 ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = csinh (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = csinh (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__sinh_fc64_fc64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
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] = 32; tile_size[1] = 32; tile_size[2] = 32; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<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,16);t1++) { lbp=max(ceild(t1,2),ceild(32*t1-Nt+3,32)); ubp=min(floord(Nt+Nz-4,32),floord(16*t1+Nz+13,32)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-1,2)),ceild(32*t2-Nz-28,32));t3<=min(min(min(floord(Nt+Ny-4,32),floord(16*t1+Ny+29,32)),floord(32*t2+Ny+28,32)),floord(32*t1-32*t2+Nz+Ny+27,32));t3++) { for (t4=max(max(max(0,ceild(t1-63,64)),ceild(32*t2-Nz-1020,1024)),ceild(32*t3-Ny-1020,1024));t4<=min(min(min(min(floord(Nt+Nx-4,1024),floord(16*t1+Nx+29,1024)),floord(32*t2+Nx+28,1024)),floord(32*t3+Nx+28,1024)),floord(32*t1-32*t2+Nz+Nx+27,1024));t4++) { for (t5=max(max(max(max(max(0,16*t1),32*t1-32*t2+1),32*t2-Nz+2),32*t3-Ny+2),1024*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,16*t1+31),32*t2+30),32*t3+30),1024*t4+1022),32*t1-32*t2+Nz+29);t5++) { for (t6=max(max(32*t2,t5+1),-32*t1+32*t2+2*t5-31);t6<=min(min(32*t2+31,-32*t1+32*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(32*t3,t5+1);t7<=min(32*t3+31,t5+Ny-2);t7++) { lbv=max(1024*t4,t5+1); ubv=min(1024*t4+1023,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; }
GB_unaryop__abs_int64_fp32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_int64_fp32 // op(A') function: GB_tran__abs_int64_fp32 // C type: int64_t // A type: float // cast: int64_t cij ; GB_CAST_SIGNED(cij,aij,64) // unaryop: cij = GB_IABS (aij) #define GB_ATYPE \ float #define GB_CTYPE \ int64_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 = GB_IABS (x) ; // casting #define GB_CASTING(z, x) \ int64_t z ; GB_CAST_SIGNED(z,x,64) ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_INT64 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_int64_fp32 ( int64_t *restrict Cx, const float *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_int64_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
NETLM_fmt_plug.c
/* * NETLM_fmt.c -- LM Challenge/Response * * Written by JoMo-Kun <jmk at foofus.net> in 2007 * and placed in the public domain. * * Performance and OMP fixes by magnum 2011 * * This algorithm is designed for performing brute-force cracking of the LM * challenge/response pairs exchanged during network-based authentication * attempts [1]. The captured challenge/response pairs from these attempts * should be stored using the L0phtCrack 2.0 LC format, specifically: * username:unused:unused:lm response:ntlm response:challenge. For example: * * CORP\Administrator:::25B2B477CE101D83648BB087CE7A1C217F51C7FC64C0EBB1:: * C8BD0C1630A9ECF7A95F494A8F0B2CB4A3F25B1225514304:1122334455667788 * * It should be noted that a LM authentication response is not same as a LM * password hash, which can be extracted using tools such as FgDump [2]. LM * responses can be gathered via normal network capture or via tools which * perform layer 2 attacks, such as Ettercap [3] and Cain [4]. The responses can * also be harvested using a modified Samba service [5] in conjunction with * some trickery to convince the user to connect to it. I leave what that * trickery may actually be as an exercise for the reader (HINT: Karma, NMB * broadcasts, IE, Outlook, social engineering, ...). * * [1] http://davenport.sourceforge.net/ntlm.html#theLmResponse * [2] http://www.foofus.net/~fizzgig/fgdump/ * [3] http://ettercap.sourceforge.net/ * [4] http://www.oxid.it/cain.html * [5] http://www.foofus.net/jmk/smbchallenge.html * */ #if FMT_EXTERNS_H extern struct fmt_main fmt_NETLM; #elif FMT_REGISTERS_H john_register_one(&fmt_NETLM); #else #include <string.h> #ifdef _OPENMP #include <omp.h> #endif #include "misc.h" #include "common.h" #include "formats.h" #include "memory.h" #include "unicode.h" #include <openssl/des.h> #include "memdbg.h" #ifndef uchar #define uchar unsigned char #endif #define FORMAT_LABEL "netlm" #define FORMAT_NAME "LM C/R" #define ALGORITHM_NAME "DES 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 14 #define PARTIAL_BINARY_SIZE 8 #define BINARY_SIZE 24 #define BINARY_ALIGN 4 #define SALT_SIZE 8 #define SALT_ALIGN 4 #define CIPHERTEXT_LENGTH 48 #define TOTAL_LENGTH 8 + 2 * SALT_SIZE + CIPHERTEXT_LENGTH // these may be altered in init() if running OMP // and that formula is subject to change #define MIN_KEYS_PER_CRYPT 1 #define THREAD_RATIO 256 #ifdef _OPENMP #define MAX_KEYS_PER_CRYPT 0x10000 #else #define MAX_KEYS_PER_CRYPT THREAD_RATIO #endif static struct fmt_tests tests[] = { {"", "G3RG3P00!", {"User", "", "", "6E1EC36D3417CE9E09A4424309F116C4C991948DAEB4ADAD", "ntlm-hash", "1122334455667788"} }, {"$NETLM$1122334455667788$16A7FDFE0CA109B937BFFB041F0E5B2D8B94A97D3FCA1A18", "HIYAGERGE"}, {"$NETLM$1122334455667788$B3A1B87DBBD4DF3CFA296198DD390C2F4E2E93C5C07B1D8B", "MEDUSAFGDUMP12"}, {"$NETLM$1122334455667788$0836F085B124F33895875FB1951905DD2F85252CC731BB25", "CORY21"}, {"$NETLM$1122334455667788$6E1EC36D3417CE9E09A4424309F116C4C991948DAEB4ADAD", "G3RG3P00!"}, {"", "HIYAGERGE", {"User", "", "", "16A7FDFE0CA109B937BFFB041F0E5B2D8B94A97D3FCA1A18", "ntlm-hash", "1122334455667788"} }, {"", "MEDUSAFGDUMP12", {"User", "", "", "B3A1B87DBBD4DF3CFA296198DD390C2F4E2E93C5C07B1D8B", "ntlm-hash", "1122334455667788"} }, {"", "CORY21", {"User", "", "", "0836F085B124F33895875FB1951905DD2F85252CC731BB25", "ntlm-hash", "1122334455667788"} }, {NULL} }; static uchar (*saved_key)[21]; static uchar (*saved_plain)[PLAINTEXT_LENGTH + 1]; static uchar (*output)[PARTIAL_BINARY_SIZE]; static uchar *challenge; static void init(struct fmt_main *self) { #ifdef _OPENMP int n = MIN_KEYS_PER_CRYPT * omp_get_max_threads(); if (n < MIN_KEYS_PER_CRYPT) n = MIN_KEYS_PER_CRYPT; if (n > MAX_KEYS_PER_CRYPT) n = MAX_KEYS_PER_CRYPT; self->params.min_keys_per_crypt = n; n = n * n * ((n >> 1) + 1) * THREAD_RATIO; if (n > MAX_KEYS_PER_CRYPT) n = MAX_KEYS_PER_CRYPT; self->params.max_keys_per_crypt = n; #endif saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_NONE); saved_plain = mem_calloc_tiny(sizeof(*saved_plain) * self->params.max_keys_per_crypt, MEM_ALIGN_NONE); output = mem_calloc_tiny(sizeof(*output) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); } static int valid(char *ciphertext, struct fmt_main *self) { char *pos; if (strncmp(ciphertext, "$NETLM$", 7)!=0) return 0; if (strlen(ciphertext) < TOTAL_LENGTH) return 0; if (ciphertext[23] != '$') return 0; if (strncmp(&ciphertext[24 + 2 * SALT_SIZE], "00000000000000000000000000000000", 32) == 0) return 0; // This is NTLM ESS C/R for (pos = &ciphertext[24]; atoi16[ARCH_INDEX(*pos)] != 0x7F; pos++) ; if (!*pos && pos - ciphertext - 24 == CIPHERTEXT_LENGTH) return 1; else return 0; } static char *prepare(char *split_fields[10], struct fmt_main *self) { char *cp; if (!strncmp(split_fields[1], "$NETLM$", 7)) return split_fields[1]; if (!split_fields[3]||!split_fields[4]||!split_fields[5]) return split_fields[1]; if (strlen(split_fields[3]) != CIPHERTEXT_LENGTH) return split_fields[1]; // if LMresp == NTresp then it's NTLM-only, not LM if (!strncmp(split_fields[3], split_fields[4], 48)) return split_fields[1]; // this string suggests we have an improperly formatted NTLMv2 if (strlen(split_fields[4]) > 31) { if (!strncmp(&split_fields[4][32], "0101000000000000", 16)) return split_fields[1]; } cp = mem_alloc(7+strlen(split_fields[3])+1+strlen(split_fields[5])+1); sprintf(cp, "$NETLM$%s$%s", split_fields[5], split_fields[3]); if (valid(cp,self)) { char *cp2 = str_alloc_copy(cp); MEM_FREE(cp); return cp2; } MEM_FREE(cp); return split_fields[1]; } static char *split(char *ciphertext, int index, struct fmt_main *self) { static char out[TOTAL_LENGTH + 1]; memset(out, 0, TOTAL_LENGTH + 1); memcpy(out, ciphertext, TOTAL_LENGTH); strlwr(&out[6]); /* Exclude: $NETLM$ */ return out; } static void *get_binary(char *ciphertext) { static uchar *binary; int i; if (!binary) binary = mem_alloc_tiny(BINARY_SIZE, MEM_ALIGN_WORD); ciphertext+=24; for (i=0; i<BINARY_SIZE; i++) { binary[i] = (atoi16[ARCH_INDEX(ciphertext[i*2])])<<4; binary[i] |= (atoi16[ARCH_INDEX(ciphertext[i*2+1])]); } return binary; } static inline void setup_des_key(unsigned char key_56[], DES_key_schedule *ks) { DES_cblock key; key[0] = key_56[0]; key[1] = (key_56[0] << 7) | (key_56[1] >> 1); key[2] = (key_56[1] << 6) | (key_56[2] >> 2); key[3] = (key_56[2] << 5) | (key_56[3] >> 3); key[4] = (key_56[3] << 4) | (key_56[4] >> 4); key[5] = (key_56[4] << 3) | (key_56[5] >> 5); key[6] = (key_56[5] << 2) | (key_56[6] >> 6); key[7] = (key_56[6] << 1); DES_set_key(&key, ks); } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; DES_key_schedule ks; int i; #ifdef _OPENMP #pragma omp parallel for default(none) private(i, ks) shared(count, output, challenge, saved_key) #endif for(i=0; i<count; i++) { /* Just do a partial binary, the first DES operation */ setup_des_key(saved_key[i], &ks); DES_ecb_encrypt((DES_cblock*)challenge, (DES_cblock*)output[i], &ks, DES_ENCRYPT); } return count; } static int cmp_all(void *binary, int count) { int index; for(index=0; index<count; index++) if (!memcmp(output[index], binary, PARTIAL_BINARY_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(output[index], binary, PARTIAL_BINARY_SIZE); } static int cmp_exact(char *source, int index) { DES_key_schedule ks; uchar binary[BINARY_SIZE]; /* NULL-pad 16-byte LM hash to 21-bytes (we postponed it until now) */ memset(&saved_key[index][16], 0, 5); /* Split padded LM hash into three 7-byte thirds DES-encrypt challenge using each third as a key Concatenate three 8-byte resulting values to form 24-byte LM response */ setup_des_key(saved_key[index], &ks); DES_ecb_encrypt((DES_cblock*)challenge, (DES_cblock*)binary, &ks, DES_ENCRYPT); setup_des_key(&saved_key[index][7], &ks); DES_ecb_encrypt((DES_cblock*)challenge, (DES_cblock*)&binary[8], &ks, DES_ENCRYPT); setup_des_key(&saved_key[index][14], &ks); DES_ecb_encrypt((DES_cblock*)challenge, (DES_cblock*)&binary[16], &ks, DES_ENCRYPT); return (!memcmp(binary, get_binary(source), BINARY_SIZE)); } static void *get_salt(char *ciphertext) { static unsigned char *binary_salt; int i; if (!binary_salt) binary_salt = mem_alloc_tiny(SALT_SIZE, MEM_ALIGN_WORD); ciphertext += 7; for (i = 0; i < SALT_SIZE; ++i) binary_salt[i] = (atoi16[ARCH_INDEX(ciphertext[i*2])] << 4) + atoi16[ARCH_INDEX(ciphertext[i*2+1])]; return (void*)binary_salt; } static void set_salt(void *salt) { challenge = salt; } static void netlm_set_key(char *key, int index) { const unsigned char magic[] = {0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25}; DES_key_schedule ks; strncpy((char *)saved_plain[index], key, sizeof(saved_plain[index])); saved_plain[index][sizeof(saved_plain[index])-1] = 0; /* Upper-case password */ enc_strupper((char*)saved_plain[index]); /* Generate 16-byte LM hash */ setup_des_key(saved_plain[index], &ks); DES_ecb_encrypt((DES_cblock*)magic, (DES_cblock*)saved_key[index], &ks, DES_ENCRYPT); setup_des_key(&saved_plain[index][7], &ks); DES_ecb_encrypt((DES_cblock*)magic, (DES_cblock*)&saved_key[index][8], &ks, DES_ENCRYPT); /* NULL-padding the 16-byte LM hash to 21-bytes is done in cmp_exact */ } static char *get_key(int index) { return (char*)saved_plain[index]; } static int salt_hash(void *salt) { return *(ARCH_WORD_32 *)salt & (SALT_HASH_SIZE - 1); } static int get_hash_0(int index) { return *(ARCH_WORD_32 *)output[index] & 0xF; } static int get_hash_1(int index) { return *(ARCH_WORD_32 *)output[index] & 0xFF; } static int get_hash_2(int index) { return *(ARCH_WORD_32 *)output[index] & 0xFFF; } static int get_hash_3(int index) { return *(ARCH_WORD_32 *)output[index] & 0xFFFF; } static int get_hash_4(int index) { return *(ARCH_WORD_32 *)output[index] & 0xFFFFF; } static int get_hash_5(int index) { return *(ARCH_WORD_32 *)output[index] & 0xFFFFFF; } static int get_hash_6(int index) { return *(ARCH_WORD_32 *)output[index] & 0x7FFFFFF; } struct fmt_main fmt_NETLM = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE | FMT_OMP, #if FMT_MAIN_VERSION > 11 { NULL }, #endif tests }, { init, fmt_default_done, fmt_default_reset, prepare, valid, split, get_binary, get_salt, #if FMT_MAIN_VERSION > 11 { NULL }, #endif fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, set_salt, netlm_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 */
jacobi.pluto.h
/* ----------------------------------------------------------------------- Copyright 2013 Pieter Ghysels, University of Antwerp Contact: ghyselsp@gmail.com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 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, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------- */ #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define pmax(x,y) ((x) > (y)? (x) : (y)) #define pmin(x,y) ((x) < (y)? (x) : (y)) // cannot be 8 or below #ifndef TS #define TS 32 #endif #ifndef T3 #define T3 64 #endif void jacobi( GRID* u, GRID* f, GRID* tmp, int nu ) { //printf("Tile sizes: %d %d %d\n", TS, TS, T3); int i, j, k; int N = u->n; int lda = u->lda; double hh = u->h*u->h; double invhh = 1.0 / hh; double DinvXomega = hh/4.0 * 4.0/5.0; double* w = &(tmp->p[0][0]); double* a = &(u->p[0][0]); double* b = &(f->p[0][0]); #ifdef USE_MM_ALLOC __assume_aligned(w,64); __assume_aligned(a,64); __assume_aligned(b,64); #endif if ((N >= 1) && (nu >= 1)) { for (int t1=-1;t1<=floord(nu-1,TS/2);t1++) { int lbp=pmax(ceild(t1,2),ceild(TS*t1-nu+2,TS)); int ubp=pmin(floord(nu+N-1,TS),floord((TS/2)*t1+N+(TS/2-1),TS)); #pragma omp parallel for for (int t2=lbp;t2<=ubp;t2++) { for (int t3=pmax(pmax(0,ceild(t1-1,2)),ceild(TS*t2-N-(T3-2),T3));t3<=pmin(pmin(floord(nu+N-1,T3),floord((TS/2)*t1+N+(TS-1),T3)),floord(TS*t2+N+(TS-2),T3));t3++) { for (int t4=pmax(pmax(pmax(pmax(0,(TS/2)*t1),TS*t2-N),T3*t3-N),TS*t1-TS*t2+1);t4<=pmin(pmin(pmin(pmin(nu-1,(TS/2)*t1+(TS-1)),TS*t2+(TS-2)),T3*t3+(T3-2)),TS*t1-TS*t2+N+(TS-1));t4++) { #pragma loop_count min(1),max(TS),avg(TS/2) for (int t5=pmax(pmax(TS*t2,t4+1),-TS*t1+TS*t2+2*t4-(TS-1));t5<=pmin(pmin(TS*t2+(TS-1),t4+N),-TS*t1+TS*t2+2*t4);t5++) { int lbv=(-t4+t5)*lda-t4+pmax(T3*t3,t4+1); int ubv=(-t4+t5)*lda-t4+pmin(T3*t3+(T3-1),t4+N); int t6l=lbv-1; int t6r=lbv+1; int t6u=lbv+lda; int t6b=lbv-lda; if (t4%2==0) { #pragma loop_count min(1),max(TS),avg((TS/2)) #pragma ivdep #pragma vector always for (int t6=lbv;t6<=ubv;t6++) { w[t6]=a[t6]-DinvXomega*((4.0*a[t6]-a[t6b]-a[t6l]-a[t6u]-a[t6r])*invhh-b[t6]); t6l++; t6r++; t6u++; t6b++; } } else { #pragma loop_count min(1),max(TS),avg((TS/2)) #pragma ivdep #pragma vector always for (int t6=lbv;t6<=ubv;t6++) { a[t6]=w[t6]-DinvXomega*((4.0*w[t6]-w[t6b]-w[t6l]-w[t6u]-w[t6r])*invhh-b[t6]); t6l++; t6r++; t6u++; t6b++; } } } } } } } } if (nu%2==1) { double** t = u->p; u->p = tmp->p; tmp->p = t; } }
kpoint.c
/* kpoint.c */ /* Copyright (C) 2008 Atsushi Togo */ #include <stdio.h> #include <stdlib.h> #include "mathfunc.h" #include "symmetry.h" #include "kpoint.h" #include "debug.h" /* #define GRID_ORDER_XYZ */ /* The addressing order of mesh grid is defined as running left */ /* element first. But when GRID_ORDER_XYZ is defined, it is changed to right */ /* element first. */ static int search_space[][3] = {{0, 0, 0}, {0, 0, 1}, {0, 1, -1}, {0, 1, 0}, {0, 1, 1}, {1, -1, -1}, {1, -1, 0}, {1, -1, 1}, {1, 0, -1}, {1, 0, 0}, {1, 0, 1}, {1, 1, -1}, {1, 1, 0}, {1, 1, 1}, {-1, -1, -1}, {-1, -1, 0}, {-1, -1, 1}, {-1, 0, -1}, {-1, 0, 0}, {-1, 0, 1}, {-1, 1, -1}, {-1, 1, 0}, {-1, 1, 1}, {0, -1, -1}, {0, -1, 0}, {0, -1, 1}, {0, 0, -1}}; static PointSymmetry get_point_group_reciprocal(const MatINT * rotations, const int is_time_reversal); static PointSymmetry get_point_group_reciprocal_with_q(SPGCONST PointSymmetry * pointgroup, const double symprec, const int num_q, SPGCONST double qpoints[][3]); static int get_ir_kpoints(int map[], SPGCONST double kpoints[][3], const int num_kpoint, SPGCONST PointSymmetry * point_symmetry, const double symprec); static int get_ir_reciprocal_mesh(int grid_address[][3], int map[], const int mesh[3], const int is_shift[3], SPGCONST PointSymmetry * point_symmetry); static int get_ir_reciprocal_mesh_openmp(int grid_address[][3], int map[], const int mesh[3], const int is_shift[3], SPGCONST PointSymmetry * point_symmetry); static int relocate_BZ_grid_address(int bz_grid_address[][3], int bz_map[], int grid_address[][3], const int mesh[3], SPGCONST double rec_lattice[3][3], const int is_shift[3]); static double get_tolerance_for_BZ_reduction(SPGCONST double rec_lattice[3][3]); static int get_ir_triplets_at_q(int weights[], int grid_address[][3], int third_q[], const int grid_point, const int mesh[3], SPGCONST PointSymmetry * pointgroup); static int get_BZ_triplets_at_q(int triplets[][3], const int grid_point, SPGCONST int bz_grid_address[][3], const int bz_map[], const int weights[], const int mesh[3]); static void get_third_q_of_triplets_at_q(int address[3][3], const int bz_map[], const int mesh[3], const int bzmesh[3], const int bzmesh_double[3]); static void grid_point_to_grid_double(int grid_double[3], const int address, const int mesh[3], const int is_shift[3]); static void get_grid_address(int grid_address[3], const int grid[3], const int mesh[3]); static void get_vector_modulo(int v[3], const int m[3]); static int get_grid_point(const int grid[3], const int mesh[3]); int kpt_get_irreducible_kpoints(int map[], SPGCONST double kpoints[][3], const int num_kpoint, const Symmetry * symmetry, const int is_time_reversal, const double symprec) { int i; PointSymmetry point_symmetry; MatINT *rotations; rotations = mat_alloc_MatINT(symmetry->size); for (i = 0; i < symmetry->size; i++) { mat_copy_matrix_i3(rotations->mat[i], symmetry->rot[i]); } point_symmetry = get_point_group_reciprocal(rotations, is_time_reversal); mat_free_MatINT(rotations); return get_ir_kpoints(map, kpoints, num_kpoint, &point_symmetry, symprec); } /* grid_address (e.g. 4x4x4 mesh) */ /* [[ 0 0 0] */ /* [ 1 0 0] */ /* [ 2 0 0] */ /* [-1 0 0] */ /* [ 0 1 0] */ /* [ 1 1 0] */ /* [ 2 1 0] */ /* [-1 1 0] */ /* .... ] */ /* */ /* Each value of 'map' correspnds to the index of grid_point. */ int kpt_get_irreducible_reciprocal_mesh(int grid_address[][3], int map[], const int mesh[3], const int is_shift[3], const int is_time_reversal, const Symmetry * symmetry) { int i; PointSymmetry point_symmetry; MatINT *rotations; rotations = mat_alloc_MatINT(symmetry->size); for (i = 0; i < symmetry->size; i++) { mat_copy_matrix_i3(rotations->mat[i], symmetry->rot[i]); } point_symmetry = get_point_group_reciprocal(rotations, is_time_reversal); mat_free_MatINT(rotations); #ifdef _OPENMP return get_ir_reciprocal_mesh_openmp(grid_address, map, mesh, is_shift, &point_symmetry); #else return get_ir_reciprocal_mesh(grid_address, map, mesh, is_shift, &point_symmetry); #endif } int kpt_get_stabilized_reciprocal_mesh(int grid_address[][3], int map[], const int mesh[3], const int is_shift[3], const int is_time_reversal, const MatINT * rotations, const int num_q, SPGCONST double qpoints[][3]) { PointSymmetry pointgroup, pointgroup_q; double tolerance; pointgroup = get_point_group_reciprocal(rotations, is_time_reversal); tolerance = 0.1 / (mesh[0] + mesh[1] + mesh[2]); pointgroup_q = get_point_group_reciprocal_with_q(&pointgroup, tolerance, num_q, qpoints); #ifdef _OPENMP return get_ir_reciprocal_mesh_openmp(grid_address, map, mesh, is_shift, &pointgroup_q); #else return get_ir_reciprocal_mesh(grid_address, map, mesh, is_shift, &pointgroup_q); #endif } int kpt_relocate_BZ_grid_address(int bz_grid_address[][3], int bz_map[], int grid_address[][3], const int mesh[3], SPGCONST double rec_lattice[3][3], const int is_shift[3]) { return relocate_BZ_grid_address(bz_grid_address, bz_map, grid_address, mesh, rec_lattice, is_shift); } int kpt_get_ir_triplets_at_q(int weights[], int grid_address[][3], int third_q[], const int grid_point, const int mesh[3], const int is_time_reversal, const MatINT * rotations) { PointSymmetry pointgroup; pointgroup = get_point_group_reciprocal(rotations, is_time_reversal); return get_ir_triplets_at_q(weights, grid_address, third_q, grid_point, mesh, &pointgroup); } int kpt_get_BZ_triplets_at_q(int triplets[][3], const int grid_point, SPGCONST int bz_grid_address[][3], const int bz_map[], const int weights[], const int mesh[3]) { return get_BZ_triplets_at_q(triplets, grid_point, bz_grid_address, bz_map, weights, mesh); } static PointSymmetry get_point_group_reciprocal(const MatINT * rotations, const int is_time_reversal) { int i, j, num_pt = 0; MatINT *rot_reciprocal; PointSymmetry point_symmetry; SPGCONST int inversion[3][3] = { {-1, 0, 0 }, { 0,-1, 0 }, { 0, 0,-1 } }; if (is_time_reversal) { rot_reciprocal = mat_alloc_MatINT(rotations->size * 2); } else { rot_reciprocal = mat_alloc_MatINT(rotations->size); } for (i = 0; i < rotations->size; i++) { mat_transpose_matrix_i3(rot_reciprocal->mat[i], rotations->mat[i]); if (is_time_reversal) { mat_multiply_matrix_i3(rot_reciprocal->mat[rotations->size+i], inversion, rot_reciprocal->mat[i]); } } for (i = 0; i < rot_reciprocal->size; i++) { for (j = 0; j < num_pt; j++) { if (mat_check_identity_matrix_i3(point_symmetry.rot[j], rot_reciprocal->mat[i])) { goto escape; } } mat_copy_matrix_i3(point_symmetry.rot[num_pt], rot_reciprocal->mat[i]); num_pt++; escape: ; } point_symmetry.size = num_pt; mat_free_MatINT(rot_reciprocal); return point_symmetry; } static PointSymmetry get_point_group_reciprocal_with_q(SPGCONST PointSymmetry * pointgroup, const double symprec, const int num_q, SPGCONST double qpoints[][3]) { int i, j, k, l, is_all_ok=0, num_ptq = 0; double q_rot[3], diff[3]; PointSymmetry pointgroup_q; for (i = 0; i < pointgroup->size; i++) { for (j = 0; j < num_q; j++) { is_all_ok = 0; mat_multiply_matrix_vector_id3(q_rot, pointgroup->rot[i], qpoints[j]); for (k = 0; k < num_q; k++) { for (l = 0; l < 3; l++) { diff[l] = q_rot[l] - qpoints[k][l]; diff[l] -= mat_Nint(diff[l]); } if (mat_Dabs(diff[0]) < symprec && mat_Dabs(diff[1]) < symprec && mat_Dabs(diff[2]) < symprec) { is_all_ok = 1; break; } } if (! is_all_ok) { break; } } if (is_all_ok) { mat_copy_matrix_i3(pointgroup_q.rot[num_ptq], pointgroup->rot[i]); num_ptq++; } } pointgroup_q.size = num_ptq; return pointgroup_q; } static int get_ir_kpoints(int map[], SPGCONST double kpoints[][3], const int num_kpoint, SPGCONST PointSymmetry * point_symmetry, const double symprec) { int i, j, k, l, num_ir_kpoint = 0, is_found; int *ir_map; double kpt_rot[3], diff[3]; ir_map = (int*)malloc(num_kpoint*sizeof(int)); for (i = 0; i < num_kpoint; i++) { map[i] = i; is_found = 1; for (j = 0; j < point_symmetry->size; j++) { mat_multiply_matrix_vector_id3(kpt_rot, point_symmetry->rot[j], kpoints[i]); for (k = 0; k < 3; k++) { diff[k] = kpt_rot[k] - kpoints[i][k]; diff[k] = diff[k] - mat_Nint(diff[k]); } if (mat_Dabs(diff[0]) < symprec && mat_Dabs(diff[1]) < symprec && mat_Dabs(diff[2]) < symprec) { continue; } for (k = 0; k < num_ir_kpoint; k++) { mat_multiply_matrix_vector_id3(kpt_rot, point_symmetry->rot[j], kpoints[i]); for (l = 0; l < 3; l++) { diff[l] = kpt_rot[l] - kpoints[ir_map[k]][l]; diff[l] = diff[l] - mat_Nint(diff[l]); } if (mat_Dabs(diff[0]) < symprec && mat_Dabs(diff[1]) < symprec && mat_Dabs(diff[2]) < symprec) { is_found = 0; map[i] = ir_map[k]; break; } } if (! is_found) break; } if (is_found) { ir_map[num_ir_kpoint] = i; num_ir_kpoint++; } } free(ir_map); ir_map = NULL; return num_ir_kpoint; } static int get_ir_reciprocal_mesh(int grid_address[][3], int map[], const int mesh[3], const int is_shift[3], SPGCONST PointSymmetry * point_symmetry) { /* In the following loop, mesh is doubled. */ /* Even and odd mesh numbers correspond to */ /* is_shift[i] = 0 and 1, respectively. */ /* is_shift = [0,0,0] gives Gamma center mesh. */ /* grid: reducible grid points */ /* map: the mapping from each point to ir-point. */ int i, j, k, l, grid_point, grid_point_rot, num_ir = 0; int grid_double[3], grid_rot[3], mesh_double[3]; for (i = 0; i < 3; i++) { mesh_double[i] = mesh[i] * 2; } /* "-1" means the element is not touched yet. */ for (i = 0; i < mesh[0] * mesh[1] * mesh[2]; i++) { map[i] = -1; } #ifndef GRID_ORDER_XYZ for (i = 0; i < mesh[2]; i++) { for (j = 0; j < mesh[1]; j++) { for (k = 0; k < mesh[0]; k++) { grid_double[0] = k * 2 + is_shift[0]; grid_double[1] = j * 2 + is_shift[1]; grid_double[2] = i * 2 + is_shift[2]; #else for (i = 0; i < mesh[0]; i++) { for (j = 0; j < mesh[1]; j++) { for (k = 0; k < mesh[2]; k++) { grid_double[0] = i * 2 + is_shift[0]; grid_double[1] = j * 2 + is_shift[1]; grid_double[2] = k * 2 + is_shift[2]; #endif grid_point = get_grid_point(grid_double, mesh); get_grid_address(grid_address[grid_point], grid_double, mesh); for (l = 0; l < point_symmetry->size; l++) { mat_multiply_matrix_vector_i3(grid_rot, point_symmetry->rot[l], grid_double); get_vector_modulo(grid_rot, mesh_double); grid_point_rot = get_grid_point(grid_rot, mesh); if (grid_point_rot > -1) { /* Invalid if even --> odd or odd --> even */ if (map[grid_point_rot] > -1) { map[grid_point] = map[grid_point_rot]; break; } } } if (map[grid_point] == -1) { map[grid_point] = grid_point; num_ir++; } } } } return num_ir; } static int get_ir_reciprocal_mesh_openmp(int grid_address[][3], int map[], const int mesh[3], const int is_shift[3], SPGCONST PointSymmetry * point_symmetry) { int i, j, k, l, grid_point, grid_point_rot, num_ir; int grid_double[3], grid_rot[3], mesh_double[3]; for (i = 0; i < 3; i++) { mesh_double[i] = mesh[i] * 2; } #ifndef GRID_ORDER_XYZ #pragma omp parallel for private(j, k, l, grid_point, grid_point_rot, grid_double, grid_rot) for (i = 0; i < mesh[2]; i++) { for (j = 0; j < mesh[1]; j++) { for (k = 0; k < mesh[0]; k++) { grid_double[0] = k * 2 + is_shift[0]; grid_double[1] = j * 2 + is_shift[1]; grid_double[2] = i * 2 + is_shift[2]; #else #pragma omp parallel for private(j, k, l, grid_point, grid_point_rot, grid_double, grid_rot) for (i = 0; i < mesh[0]; i++) { for (j = 0; j < mesh[1]; j++) { for (k = 0; k < mesh[2]; k++) { grid_double[0] = i * 2 + is_shift[0]; grid_double[1] = j * 2 + is_shift[1]; grid_double[2] = k * 2 + is_shift[2]; #endif grid_point = get_grid_point(grid_double, mesh); map[grid_point] = grid_point; get_grid_address(grid_address[grid_point], grid_double, mesh); for (l = 0; l < point_symmetry->size; l++) { mat_multiply_matrix_vector_i3(grid_rot, point_symmetry->rot[l], grid_double); get_vector_modulo(grid_rot, mesh_double); grid_point_rot = get_grid_point(grid_rot, mesh); if (grid_point_rot > -1) { /* Invalid if even --> odd or odd --> even */ if (grid_point_rot < map[grid_point]) { map[grid_point] = grid_point_rot; } } } } } } num_ir = 0; #pragma omp parallel for reduction(+:num_ir) for (i = 0; i < mesh[0] * mesh[1] * mesh[2]; i++) { if (map[i] == i) { num_ir++; } } return num_ir; } /* Relocate grid addresses to first Brillouin zone */ /* bz_grid_address[prod(mesh + 1)][3] */ /* bz_map[prod(mesh * 2 - 1)] */ static int relocate_BZ_grid_address(int bz_grid_address[][3], int bz_map[], int grid_address[][3], const int mesh[3], SPGCONST double rec_lattice[3][3], const int is_shift[3]) { double tolerance, min_distance; double vector[3], distance[27]; int bzmesh[3], bzmesh_double[3], address_double[3]; int i, j, k, min_index, boundary_gp, total_num_gp, bzgp, gp; tolerance = get_tolerance_for_BZ_reduction(rec_lattice); for (i = 0; i < 3; i++) { bzmesh[i] = mesh[i] * 2 - 1; bzmesh_double[i] = bzmesh[i] * 2; } for (i = 0; i < bzmesh[0] * bzmesh[1] * bzmesh[2]; i++) { bz_map[i] = -1; } boundary_gp = 0; total_num_gp = mesh[0] * mesh[1] * mesh[2]; for (i = 0; i < total_num_gp; i++) { for (j = 0; j < 27; j++) { for (k = 0; k < 3; k++) { address_double[k] = (grid_address[i][k] + search_space[j][k] * mesh[k]) * 2 + is_shift[k]; } mat_multiply_matrix_vector_di3(vector, rec_lattice, address_double); distance[j] = mat_norm_squared_d3(vector); } min_distance = distance[0]; min_index = 0; for (j = 1; j < 27; j++) { if (distance[j] + tolerance < min_distance) { min_distance = distance[j]; min_index = j; } } for (j = 0; j < 27; j++) { if (distance[j] < min_distance + tolerance) { if (j == min_index) { gp = i; } else { gp = boundary_gp + total_num_gp; } for (k = 0; k < 3; k++) { bz_grid_address[gp][k] = grid_address[i][k] + search_space[j][k] * mesh[k]; address_double[k] = bz_grid_address[gp][k] * 2 + is_shift[k]; if (address_double[k] < 0) { address_double[k] += bzmesh_double[k]; } } bzgp = get_grid_point(address_double, bzmesh); bz_map[bzgp] = gp; if (j != min_index) { boundary_gp++; } } } } return boundary_gp + total_num_gp; } static double get_tolerance_for_BZ_reduction(SPGCONST double rec_lattice[3][3]) { int i, j; double tolerance; double length[3]; for (i = 0; i < 3; i++) { length[i] = 0; for (j = 0; j < 3; j++) { length[i] += rec_lattice[j][i] * rec_lattice[j][i]; } } tolerance = length[0]; for (i = 1; i < 3; i++) { if (tolerance > length[i]) { tolerance = length[i]; } } tolerance /= 100; return tolerance; } static int get_ir_triplets_at_q(int weights[], int grid_address[][3], int third_q[], const int grid_point, const int mesh[3], SPGCONST PointSymmetry * pointgroup) { int i, j, num_grid, q_2, num_ir_q, num_ir_triplets, ir_grid_point; int mesh_double[3], is_shift[3]; int grid_double0[3], grid_double1[3], grid_double2[3]; int *map_q, *ir_grid_points, *weight_q; double tolerance; double stabilizer_q[1][3]; PointSymmetry pointgroup_q; tolerance = 0.1 / (mesh[0] + mesh[1] + mesh[2]); num_grid = mesh[0] * mesh[1] * mesh[2]; for (i = 0; i < 3; i++) { /* Only consider the gamma-point */ is_shift[i] = 0; mesh_double[i] = mesh[i] * 2; } /* Search irreducible q-points (map_q) with a stabilizer */ grid_point_to_grid_double(grid_double0, grid_point, mesh, is_shift); /* q */ for (i = 0; i < 3; i++) { stabilizer_q[0][i] = (double)grid_double0[i] / mesh_double[i] - (grid_double0[i] > mesh[i]); } pointgroup_q = get_point_group_reciprocal_with_q(pointgroup, tolerance, 1, stabilizer_q); map_q = (int*) malloc(sizeof(int) * num_grid); #ifdef _OPENMP num_ir_q = get_ir_reciprocal_mesh_openmp(grid_address, map_q, mesh, is_shift, &pointgroup_q); #else num_ir_q = get_ir_reciprocal_mesh(grid_address, map_q, mesh, is_shift, &pointgroup_q); #endif ir_grid_points = (int*) malloc(sizeof(int) * num_ir_q); weight_q = (int*) malloc(sizeof(int) * num_grid); num_ir_q = 0; for (i = 0; i < num_grid; i++) { if (map_q[i] == i) { ir_grid_points[num_ir_q] = i; num_ir_q++; } weight_q[i] = 0; third_q[i] = -1; weights[i] = 0; } for (i = 0; i < num_grid; i++) { weight_q[map_q[i]]++; } #pragma omp parallel for private(j, grid_double1, grid_double2) for (i = 0; i < num_ir_q; i++) { grid_point_to_grid_double(grid_double1, ir_grid_points[i], mesh, is_shift); /* q' */ for (j = 0; j < 3; j++) { /* q'' */ grid_double2[j] = - grid_double0[j] - grid_double1[j]; } get_vector_modulo(grid_double2, mesh_double); third_q[ir_grid_points[i]] = get_grid_point(grid_double2, mesh); } num_ir_triplets = 0; for (i = 0; i < num_ir_q; i++) { ir_grid_point = ir_grid_points[i]; q_2 = third_q[ir_grid_point]; if (weights[map_q[q_2]]) { weights[map_q[q_2]] += weight_q[ir_grid_point]; } else { weights[ir_grid_point] = weight_q[ir_grid_point]; num_ir_triplets++; } } free(map_q); map_q = NULL; free(weight_q); weight_q = NULL; free(ir_grid_points); ir_grid_points = NULL; return num_ir_triplets; } static int get_BZ_triplets_at_q(int triplets[][3], const int grid_point, SPGCONST int bz_grid_address[][3], const int bz_map[], const int weights[], const int mesh[3]) { int i, j, k, num_ir; int address[3][3], address_double[3], bzmesh[3], bzmesh_double[3]; int *ir_grid_points; for (i = 0; i < 3; i++) { bzmesh[i] = mesh[i] * 2 - 1; bzmesh_double[i] = bzmesh[i] * 2; } num_ir = 0; ir_grid_points = (int*) malloc(sizeof(int) * mesh[0] * mesh[1] * mesh[2]); for (i = 0; i < mesh[0] * mesh[1] * mesh[2]; i++) { if (weights[i] > 0) { ir_grid_points[num_ir] = i; num_ir++; } } #pragma omp parallel for private(j, k, address, address_double) for (i = 0; i < num_ir; i++) { for (j = 0; j < 3; j++) { address[0][j] = bz_grid_address[grid_point][j]; address[1][j] = bz_grid_address[ir_grid_points[i]][j]; address[2][j] = - address[0][j] - address[1][j]; } get_third_q_of_triplets_at_q(address, bz_map, mesh, bzmesh, bzmesh_double); for (j = 0; j < 3; j++) { for (k = 0; k < 3; k++) { address_double[k] = address[j][k] * 2; if (address_double[k] < 0) { address_double[k] += bzmesh_double[k]; } } triplets[i][j] = bz_map[get_grid_point(address_double, bzmesh)]; } } free(ir_grid_points); return num_ir; } static void get_third_q_of_triplets_at_q(int address[3][3], const int bz_map[], const int mesh[3], const int bzmesh[3], const int bzmesh_double[3]) { int i, j, smallest_g, smallest_index, sum_g, delta_g[3]; int bzgp[27], address_double[3]; get_vector_modulo(address[2], mesh); for (i = 0; i < 3; i++) { delta_g[i] = 0; for (j = 0; j < 3; j++) { delta_g[i] += address[j][i]; } delta_g[i] /= mesh[i]; } for (i = 0; i < 27; i++) { for (j = 0; j < 3; j++) { address_double[j] = (address[2][j] + search_space[i][j] * mesh[j]) * 2; } if (abs(address_double[0] > bzmesh[0]) || abs(address_double[1] > bzmesh[1]) || abs(address_double[2] > bzmesh[2]) || abs(address_double[0] < -bzmesh[0]) || abs(address_double[1] < -bzmesh[1]) || abs(address_double[2] < -bzmesh[2])) { /* outside extended zone */ bzgp[i] = -1; continue; } for (j = 0; j < 3; j++) { if (address_double[j] < 0) { address_double[j] += bzmesh_double[j]; } } bzgp[i] = bz_map[get_grid_point(address_double, bzmesh)]; } for (i = 0; i < 27; i++) { if (bzgp[i] != -1) { goto escape; } } printf("******* Warning *******\n"); printf(" No third-q was found.\n"); printf("******* Warning *******\n"); escape: smallest_g = 4; smallest_index = 0; for (i = 0; i < 27; i++) { if (bzgp[i] > -1) { /* q'' is in BZ */ sum_g = (abs(delta_g[0] + search_space[i][0]) + abs(delta_g[1] + search_space[i][1]) + abs(delta_g[2] + search_space[i][2])); if (sum_g < smallest_g) { smallest_index = i; smallest_g = sum_g; } } } for (i = 0; i < 3; i++) { address[2][i] += search_space[smallest_index][i] * mesh[i]; } } static int get_grid_point(const int grid_double[3], const int mesh[3]) { int i, grid[3]; for (i = 0; i < 3; i++) { if (grid_double[i] % 2 == 0) { grid[i] = grid_double[i] / 2; } else { grid[i] = (grid_double[i] - 1) / 2; } } #ifndef GRID_ORDER_XYZ return grid[2] * mesh[0] * mesh[1] + grid[1] * mesh[0] + grid[0]; #else return grid[0] * mesh[1] * mesh[2] + grid[1] * mesh[2] + grid[2]; #endif } static void grid_point_to_grid_double(int grid_double[3], const int grid_point, const int mesh[3], const int is_shift[3]) { int i; int grid[3]; #ifndef GRID_ORDER_XYZ grid[2] = grid_point / (mesh[0] * mesh[1]); grid[1] = (grid_point - grid[2] * mesh[0] * mesh[1]) / mesh[0]; grid[0] = grid_point % mesh[0]; #else grid[0] = grid_point / (mesh[1] * mesh[2]); grid[1] = (grid_point - grid[0] * mesh[1] * mesh[2]) / mesh[2]; grid[2] = grid_point % mesh[2]; #endif for (i = 0; i < 3; i++) { grid_double[i] = grid[i] * 2 + is_shift[i]; } } static void get_grid_address(int address[3], const int grid_double[3], const int mesh[3]) { int i; for (i = 0; i < 3; i++) { if (grid_double[i] % 2 == 0) { address[i] = grid_double[i] / 2; } else { address[i] = (grid_double[i] - 1) / 2; } #ifndef GRID_BOUNDARY_AS_NEGATIVE address[i] = address[i] - mesh[i] * (address[i] > mesh[i] / 2); #else address[i] = address[i] - mesh[i] * (address[i] >= mesh[i] / 2); #endif } } static void get_vector_modulo(int v[3], const int m[3]) { int i; for (i = 0; i < 3; i++) { v[i] = v[i] % m[i]; if (v[i] < 0) v[i] += m[i]; } }
kcenter.h
#ifndef FGC_OPTIM_KCENTER_H__ #define FGC_OPTIM_KCENTER_H__ #include "minicore/coreset/matrix_coreset.h" #include "minicore/util/div.h" #include "minicore/util/blaze_adaptor.h" #include "minicore/util/fpq.h" #include "libsimdsampling/argminmax.h" namespace minicore { namespace coresets { using std::partial_sum; using blz::L2Norm; using blz::sqrL2Norm; using blz::push_back; using util::fpq; /* * * 2-approximate solution * T. F. Gonzalez. Clustering to minimize the maximum intercluster distance. Theoretical Computer Science, 38:293-306, 1985. */ template<typename Iter, typename FT=shared::ContainedTypeFromIterator<Iter>, typename IT=std::uint32_t, typename RNG, typename Norm=L2Norm> auto kcenter_greedy_2approx_costs(Iter first, Iter end, RNG &rng, size_t k, const Norm &norm=Norm(), size_t maxdest=0) { static_assert(sizeof(typename RNG::result_type) >= sizeof(IT), "IT must have the same size as the result type of the RNG"); static_assert(std::is_arithmetic<FT>::value, "FT must be arithmetic"); auto dm = make_index_dm(first, norm); size_t np = end - first; if(maxdest == 0) maxdest = np; std::vector<IT> centers(k); std::vector<FT> distances(np, 0.); IT bestind = 0; VERBOSE_ONLY(std::fprintf(stderr, "[%s] Starting kcenter_greedy_2approx\n", __PRETTY_FUNCTION__);) auto newc = rng() % maxdest; centers[0] = newc; distances[newc] = 0.; #ifdef _OPENMP OMP_PFOR #else SK_UNROLL_8 #endif for(IT i = 0; i < maxdest; ++i) { if(unlikely(i == newc)) continue; distances[i] = dm(newc, i); } bestind = reservoir_simd::argmax(distances, /*mutithread=*/true); assert(distances[newc] == 0.); if(k == 1) return std::make_pair(centers, distances); centers[1] = newc = bestind; distances[newc] = 0.; for(size_t ci = 2; ci < std::min(k, np); ++ci) { #ifdef _OPENMP OMP_PFOR #else SK_UNROLL_8 #endif for(IT i = 0; i < maxdest; ++i) { if(unlikely(i == bestind)) continue; auto &ldist = distances[i]; if(!ldist) continue; auto dist = dm(newc, i); if(dist < ldist) ldist = dist; } bestind = reservoir_simd::argmax(distances, true); centers[ci] = newc = bestind; distances[newc] = 0.; } return std::make_pair(centers, distances); } // kcenter_greedy_2approx_costs template<typename Oracle, typename FT=std::decay_t<decltype(std::declval<Oracle>()(0, 0))>, typename IT=std::uint32_t, typename RNG, typename Norm=L2Norm> auto kcenter_greedy_2approx_costs(Oracle &oracle, const size_t np, size_t k, RNG &rng) { static_assert(sizeof(typename RNG::result_type) >= sizeof(IT), "IT must have the same size as the result type of the RNG"); static_assert(std::is_arithmetic<FT>::value, "FT must be arithmetic"); std::vector<IT> centers; std::vector<FT> distances(np, 0.); VERBOSE_ONLY(std::fprintf(stderr, "[%s] Starting kcenter_greedy_2approx\n", __PRETTY_FUNCTION__);) auto newc = rng() % np; centers.push_back(newc); distances[newc] = 0.; #ifdef _OPENMP OMP_PFOR #else SK_UNROLL_8 #endif for(IT i = 0; i < np; ++i) { if(likely(i != newc)) { distances[i] = oracle(i, newc); } } if(k == 1) return std::make_pair(centers, distances); newc = reservoir_simd::argmax(distances, true); distances[newc] = 0.; centers.push_back(newc); while(centers.size() < k) { OMP_PFOR for(IT i = 0; i < np; ++i) { if(!distances[i]) continue; auto v = oracle(i, newc); if(v < distances[i]) distances[i] = v; } IT bestind = reservoir_simd::argmax(distances, true); newc = bestind; #ifndef NDEBUG FT bestcost = distances[bestind]; IT ind = std::max_element(distances.begin(), distances.end()) - distances.begin(); assert(bestind == ind || distances[ind] == bestcost); #endif centers.push_back(newc); distances[newc] = 0.; } return std::make_pair(centers, distances); } // kcenter_greedy_2approx_costs template<typename...Args> auto kcenter_greedy_2approx(Args &&...args) { return kcenter_greedy_2approx_costs(std::forward<Args>(args)...).first; } /* // Algorithm 2 from: // Greedy Strategy Works for k-Center Clustering with Outliers and Coreset Construction // Hu Ding, Haikuo Yu, Zixiu Wang // Z = # outliers // \gamma = z / n */ template<typename Iter, typename FT=shared::ContainedTypeFromIterator<Iter>, typename IT=std::uint32_t, typename RNG, typename Norm=L2Norm> auto kcenter_greedy_2approx_outliers_costs(Iter first, Iter end, RNG &rng, size_t k, double eps, double gamma=0.001, const Norm &norm=Norm()) { static_assert(std::is_floating_point_v<FT>, "Sanity check: FT floating point"); static_assert(std::is_integral_v<IT>, "Sanity check: IT must be integral"); auto dm = make_index_dm(first, norm); const size_t np = end - first; size_t farthestchunksize = std::ceil((1. + eps) * gamma * np); if(farthestchunksize > np) farthestchunksize = np; fpq<IT, FT> pq(farthestchunksize); auto &pqc = pq.getc(); //pq.reserve(farthestchunksize + 1); std::vector<IT> ret; std::vector<FT> distances(np, std::numeric_limits<FT>::max()); ret.reserve(k); auto newc = rng() % np; ret.push_back(newc); do { // Fill pq #ifdef _OPENMP #pragma omp declare reduction (merge : fpq<IT, FT> : omp_out.update(omp_in)) initializer(omp_priv(omp_orig)) #pragma omp parallel for reduction(merge: pq) #endif for(IT i = 0; i < np; ++i) { double dist = distances[i]; if(dist == 0.) continue; double newdist; if((newdist = dm(i, newc)) < dist) dist = newdist; distances[i] = dist; pq.add(dist, i); } // Sample point newc = pqc[rng() % farthestchunksize].second; ret.push_back(newc); pqc.clear(); } while(ret.size() < k); return std::make_pair(ret, distances); }// kcenter_greedy_2approx_outliers_costs template<typename Oracle, typename FT=double, typename IT=std::uint32_t, typename RNG, typename Norm=L2Norm> auto kcenter_greedy_2approx_outliers_costs(Oracle &oracle, size_t np, RNG &rng, size_t k, double eps, double gamma=0.001) { size_t farthestchunksize = std::ceil((1. + eps) * gamma * np); fpq<IT, FT> pq(farthestchunksize); //pq.reserve(farthestchunksize + 1); std::vector<IT> ret; std::vector<FT> distances(np, std::numeric_limits<FT>::max()); ret.reserve(k); // TODO: extend argminmax to sample top/bottom k // and replace its use here. auto newc = rng() % np; ret.push_back(newc); do { //const auto &newel = first[newc]; // Fill pq #ifdef _OPENMP #pragma omp declare reduction (merge : fpq<IT, FT> : omp_out.update(omp_in)) initializer(omp_priv(omp_orig)) #pragma omp parallel for reduction(merge: pq) #endif for(IT i = 0; i < np; ++i) { double dist = distances[i]; if(dist == 0.) continue; double newdist; if((newdist = oracle(i, newc)) < dist) dist = newdist; distances[i] = dist; pq.add(dist, i); } // Sample point newc = pq.getc()[rng() % farthestchunksize].second; assert(newc < np); ret.push_back(newc); pq.getc().clear(); } while(ret.size() < k); return std::make_pair(ret, distances); }// kcenter_greedy_2approx_outliers_costs template<typename...Args> auto kcenter_greedy_2approx_outliers(Args &&...args) { return kcenter_greedy_2approx_outliers_costs(std::forward<Args>(args)...).first; } template<typename Iter, typename FT=double, typename IT=std::uint32_t, typename RNG, typename Norm> auto solve_kcenter(Iter first, Iter end, const Norm &norm, RNG &rng, size_t k=50, double eps=1., double gamma=0, int nrep=0) { auto get_sol = [&]() { if(gamma == 0.) return kcenter_greedy_2approx_costs(first, end, rng, k, norm); else return kcenter_greedy_2approx_outliers_costs<Iter, FT>(first, end, rng, k, eps, gamma, norm); }; auto [ret, costs] = get_sol(); auto current_cost = blz::sum(costs); while(nrep-- > 0) { auto [ret2, costs2] = get_sol(); if(auto newcost = blz::sum(ret2); newcost < current_cost) std::tie(ret, costs, current_cost) = std::move(std::tie(ret2, costs2, newcost)); } return std::make_pair(ret, costs); } template<typename MT, typename FT=double, typename IT=std::uint32_t, typename RNG, typename Norm, bool SO> auto solve_kcenter(blaze::Matrix<MT, SO> &matrix, const Norm &norm, RNG &rng, size_t k=50, double eps=1., double gamma=0, int nrep=0) { auto &_mat = *matrix; auto rit = blz::rowiterator(_mat); return solve_kcenter<decltype(rit.begin()), FT>(rit.begin(), rit.end(), norm, rng, k, eps, gamma, nrep); } } // coresets using coresets::solve_kcenter; using coresets::kcenter_greedy_2approx_outliers; using coresets::kcenter_greedy_2approx; } // minicore #endif /* FGC_OPTIM_KCENTER_H__ */
GB_binop__min_uint8.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__min_uint8) // A.*B function (eWiseMult): GB (_AemultB_08__min_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__min_uint8) // A.*B function (eWiseMult): GB (_AemultB_04__min_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__min_uint8) // A*D function (colscale): GB (_AxD__min_uint8) // D*A function (rowscale): GB (_DxB__min_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__min_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__min_uint8) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__min_uint8) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__min_uint8) // C=scalar+B GB (_bind1st__min_uint8) // C=scalar+B' GB (_bind1st_tran__min_uint8) // C=A+scalar GB (_bind2nd__min_uint8) // C=A'+scalar GB (_bind2nd_tran__min_uint8) // C type: uint8_t // A type: uint8_t // A pattern? 0 // B type: uint8_t // B pattern? 0 // BinaryOp: cij = GB_IMIN (aij, bij) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint8_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint8_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) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_IMIN (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MIN || GxB_NO_UINT8 || GxB_NO_MIN_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__min_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__min_uint8) ( 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__min_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__min_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__min_uint8) ( 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 uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__min_uint8) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__min_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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) ; uint8_t alpha_scalar ; uint8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ; beta_scalar = (*((uint8_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__min_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__min_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__min_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__min_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__min_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IMIN (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__min_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IMIN (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMIN (x, aij) ; \ } GrB_Info GB (_bind1st_tran__min_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMIN (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__min_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
fill_nr_3c.c
/* * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <stdio.h> #include "config.h" #include "cint.h" int GTOmax_shell_dim(int *ao_loc, int *shls_slice, int ncenter); int GTOmax_cache_size(int (*intor)(), int *shls_slice, int ncenter, int *atm, int natm, int *bas, int nbas, double *env); /* * out[naoi,naoj,naok,comp] in F-order */ void GTOnr3c_fill_s1(int (*intor)(), double *out, double *buf, int comp, int ish, int jsh, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const size_t naoi = ao_loc[ish1] - ao_loc[ish0]; const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; const size_t nij = naoi * naoj; const int dims[] = {naoi, naoj, naok}; ish += ish0; jsh += jsh0; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int ip = ao_loc[ish] - ao_loc[ish0]; const int jp = ao_loc[jsh] - ao_loc[jsh0]; out += jp * naoi + ip; int ksh, dk, k0; int shls[3]; shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh < ksh1; ksh++) { shls[2] = ksh; k0 = ao_loc[ksh ] - ao_loc[ksh0]; dk = ao_loc[ksh+1] - ao_loc[ksh]; (*intor)(out+k0*nij, dims, shls, atm, natm, bas, nbas, env, cintopt, buf); } } static void dcopy_s2_igtj(double *out, double *in, int comp, int ip, int nij, int nijk, int di, int dj, int dk) { const size_t dij = di * dj; const size_t ip1 = ip + 1; int i, j, k, ic; double *pout, *pin; for (ic = 0; ic < comp; ic++) { for (k = 0; k < dk; k++) { pout = out + k * nij; pin = in + k * dij; for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { pout[j] = pin[j*di+i]; } pout += ip1 + i; } } out += nijk; in += dij * dk; } } static void dcopy_s2_ieqj(double *out, double *in, int comp, int ip, int nij, int nijk, int di, int dj, int dk) { const size_t dij = di * dj; const size_t ip1 = ip + 1; int i, j, k, ic; double *pout, *pin; for (ic = 0; ic < comp; ic++) { for (k = 0; k < dk; k++) { pout = out + k * nij; pin = in + k * dij; for (i = 0; i < di; i++) { for (j = 0; j <= i; j++) { pout[j] = pin[j*di+i]; } pout += ip1 + i; } } out += nijk; in += dij * dk; } } /* * out[comp,naok,nij] in C-order * nij = i1*(i1+1)/2 - i0*(i0+1)/2 * [ \ ] * [**** ] * [***** ] * [*****. ] <= . may not be filled, if jsh-upper-bound < ish-upper-bound * [ \] */ void GTOnr3c_fill_s2ij(int (*intor)(), double *out, double *buf, int comp, int ish, int jsh, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; ish += ish0; jsh += jsh0; const int ip = ao_loc[ish]; const int jp = ao_loc[jsh] - ao_loc[jsh0]; if (ip < jp) { return; } const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const int i0 = ao_loc[ish0]; const int i1 = ao_loc[ish1]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; const size_t off = i0 * (i0 + 1) / 2; const size_t nij = i1 * (i1 + 1) / 2 - off; const size_t nijk = nij * naok; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; out += ip * (ip + 1) / 2 - off + jp; int ksh, dk, k0; int shls[3]; dk = GTOmax_shell_dim(ao_loc, shls_slice, 3); double *cache = buf + di * dj * dk * comp; shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh < ksh1; ksh++) { shls[2] = ksh; dk = ao_loc[ksh+1] - ao_loc[ksh]; k0 = ao_loc[ksh ] - ao_loc[ksh0]; (*intor)(buf, NULL, shls, atm, natm, bas, nbas, env, cintopt, cache); if (ip != jp) { dcopy_s2_igtj(out+k0*nij, buf, comp, ip, nij, nijk, di, dj, dk); } else { dcopy_s2_ieqj(out+k0*nij, buf, comp, ip, nij, nijk, di, dj, dk); } } } void GTOnr3c_fill_s2jk(int (*intor)(), double *out, double *buf, int comp, int ish, int jsh, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { fprintf(stderr, "GTOnr3c_fill_s2jk not implemented\n"); exit(1); } void GTOnr3c_drv(int (*intor)(), void (*fill)(), double *eri, int comp, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int nish = ish1 - ish0; const int njsh = jsh1 - jsh0; const int di = GTOmax_shell_dim(ao_loc, shls_slice, 3); const int cache_size = GTOmax_cache_size(intor, shls_slice, 3, atm, natm, bas, nbas, env); #pragma omp parallel default(none) \ shared(intor, fill, eri, comp, shls_slice, ao_loc, cintopt, \ atm, natm, bas, nbas, env) { int ish, jsh, ij; double *buf = malloc(sizeof(double) * (di*di*di*comp + cache_size)); #pragma omp for schedule(dynamic) for (ij = 0; ij < nish*njsh; ij++) { ish = ij / njsh; jsh = ij % njsh; (*fill)(intor, eri, buf, comp, ish, jsh, shls_slice, ao_loc, cintopt, atm, natm, bas, nbas, env); } free(buf); } }
kendalltau.c
/*KENDALLTAU Internal code for homogeneous region detection ** Please refer to file kendalltau.m ** License ** ------- ** This work is protected by the CeCILL-C Licence, see ** - Licence_CeCILL_V2.1-en.txt ** - Licence_CeCILL_V2.1-fr.txt ** ** Copyright 2015 Charles Deledalle */ /*#ifdef MATLAB_MEX_FILE*/ # include <mex.h> /*#endif*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #if defined(_WIN32) || defined(_WIN64) /* For Microsoft Windows SKD C++ compiler */ #define isnan mxIsNaN #define NAN (mxGetNaN()) double roundf(double number) { return (number >= 0) ? (int)(number + 0.5) : (int)(number - 0.5); } #endif /* Lookup table for "1-2*abs(normcdf(linspace(0, 5, 4096), 0, 1) - 0.5)" */ const int normpvalues_2sided_size = 4096; const double normpvalues_2sided_max = 5; const double normpvalues_2sided[] = { 1.000000, 0.999026, 0.998052, 0.997077, 0.996103, 0.995129, 0.994155, 0.993181, 0.992206, 0.991232, 0.990258, 0.989284, 0.988310, 0.987336, 0.986362, 0.985388, 0.984414, 0.983439, 0.982465, 0.981492, 0.980518, 0.979544, 0.978570, 0.977596, 0.976622, 0.975648, 0.974675, 0.973701, 0.972727, 0.971754, 0.970780, 0.969806, 0.968833, 0.967860, 0.966886, 0.965913, 0.964939, 0.963966, 0.962993, 0.962020, 0.961047, 0.960074, 0.959101, 0.958128, 0.957155, 0.956182, 0.955210, 0.954237, 0.953264, 0.952292, 0.951319, 0.950347, 0.949375, 0.948402, 0.947430, 0.946458, 0.945486, 0.944514, 0.943543, 0.942571, 0.941599, 0.940628, 0.939656, 0.938685, 0.937713, 0.936742, 0.935771, 0.934800, 0.933829, 0.932858, 0.931888, 0.930917, 0.929947, 0.928976, 0.928006, 0.927036, 0.926066, 0.925096, 0.924126, 0.923156, 0.922186, 0.921217, 0.920247, 0.919278, 0.918309, 0.917340, 0.916371, 0.915402, 0.914433, 0.913465, 0.912497, 0.911528, 0.910560, 0.909592, 0.908624, 0.907656, 0.906689, 0.905721, 0.904754, 0.903787, 0.902820, 0.901853, 0.900886, 0.899919, 0.898953, 0.897987, 0.897020, 0.896054, 0.895089, 0.894123, 0.893157, 0.892192, 0.891227, 0.890262, 0.889297, 0.888332, 0.887367, 0.886403, 0.885439, 0.884475, 0.883511, 0.882547, 0.881584, 0.880620, 0.879657, 0.878694, 0.877731, 0.876768, 0.875806, 0.874844, 0.873881, 0.872920, 0.871958, 0.870996, 0.870035, 0.869074, 0.868113, 0.867152, 0.866191, 0.865231, 0.864271, 0.863311, 0.862351, 0.861391, 0.860432, 0.859473, 0.858514, 0.857555, 0.856597, 0.855638, 0.854680, 0.853722, 0.852765, 0.851807, 0.850850, 0.849893, 0.848936, 0.847979, 0.847023, 0.846067, 0.845111, 0.844155, 0.843200, 0.842245, 0.841290, 0.840335, 0.839380, 0.838426, 0.837472, 0.836518, 0.835565, 0.834611, 0.833658, 0.832705, 0.831753, 0.830800, 0.829848, 0.828896, 0.827945, 0.826993, 0.826042, 0.825091, 0.824141, 0.823191, 0.822240, 0.821291, 0.820341, 0.819392, 0.818443, 0.817494, 0.816546, 0.815597, 0.814649, 0.813702, 0.812754, 0.811807, 0.810860, 0.809914, 0.808967, 0.808021, 0.807076, 0.806130, 0.805185, 0.804240, 0.803296, 0.802351, 0.801407, 0.800464, 0.799520, 0.798577, 0.797634, 0.796692, 0.795749, 0.794807, 0.793866, 0.792924, 0.791983, 0.791042, 0.790102, 0.789162, 0.788222, 0.787282, 0.786343, 0.785404, 0.784466, 0.783527, 0.782589, 0.781652, 0.780714, 0.779777, 0.778841, 0.777904, 0.776968, 0.776032, 0.775097, 0.774162, 0.773227, 0.772293, 0.771359, 0.770425, 0.769491, 0.768558, 0.767625, 0.766693, 0.765761, 0.764829, 0.763898, 0.762967, 0.762036, 0.761106, 0.760176, 0.759246, 0.758316, 0.757387, 0.756459, 0.755531, 0.754603, 0.753675, 0.752748, 0.751821, 0.750894, 0.749968, 0.749042, 0.748117, 0.747192, 0.746267, 0.745343, 0.744419, 0.743495, 0.742572, 0.741649, 0.740727, 0.739804, 0.738883, 0.737961, 0.737040, 0.736120, 0.735199, 0.734280, 0.733360, 0.732441, 0.731522, 0.730604, 0.729686, 0.728768, 0.727851, 0.726934, 0.726018, 0.725102, 0.724186, 0.723271, 0.722356, 0.721442, 0.720528, 0.719614, 0.718701, 0.717788, 0.716876, 0.715964, 0.715052, 0.714141, 0.713230, 0.712320, 0.711410, 0.710500, 0.709591, 0.708682, 0.707774, 0.706866, 0.705959, 0.705051, 0.704145, 0.703239, 0.702333, 0.701427, 0.700522, 0.699618, 0.698714, 0.697810, 0.696907, 0.696004, 0.695102, 0.694200, 0.693298, 0.692397, 0.691496, 0.690596, 0.689696, 0.688797, 0.687898, 0.686999, 0.686101, 0.685204, 0.684307, 0.683410, 0.682514, 0.681618, 0.680723, 0.679828, 0.678933, 0.678039, 0.677146, 0.676252, 0.675360, 0.674468, 0.673576, 0.672685, 0.671794, 0.670903, 0.670014, 0.669124, 0.668235, 0.667347, 0.666459, 0.665571, 0.664684, 0.663797, 0.662911, 0.662025, 0.661140, 0.660255, 0.659371, 0.658487, 0.657604, 0.656721, 0.655839, 0.654957, 0.654076, 0.653195, 0.652314, 0.651434, 0.650555, 0.649676, 0.648797, 0.647919, 0.647042, 0.646165, 0.645288, 0.644412, 0.643537, 0.642662, 0.641787, 0.640913, 0.640040, 0.639167, 0.638294, 0.637422, 0.636550, 0.635679, 0.634809, 0.633939, 0.633069, 0.632200, 0.631332, 0.630464, 0.629596, 0.628729, 0.627863, 0.626997, 0.626131, 0.625266, 0.624402, 0.623538, 0.622674, 0.621812, 0.620949, 0.620087, 0.619226, 0.618365, 0.617505, 0.616645, 0.615786, 0.614927, 0.614069, 0.613212, 0.612354, 0.611498, 0.610642, 0.609786, 0.608931, 0.608077, 0.607223, 0.606370, 0.605517, 0.604664, 0.603813, 0.602961, 0.602111, 0.601261, 0.600411, 0.599562, 0.598713, 0.597865, 0.597018, 0.596171, 0.595325, 0.594479, 0.593634, 0.592789, 0.591945, 0.591101, 0.590258, 0.589416, 0.588574, 0.587733, 0.586892, 0.586052, 0.585212, 0.584373, 0.583534, 0.582696, 0.581859, 0.581022, 0.580186, 0.579350, 0.578515, 0.577680, 0.576846, 0.576013, 0.575180, 0.574347, 0.573516, 0.572684, 0.571854, 0.571024, 0.570194, 0.569365, 0.568537, 0.567709, 0.566882, 0.566055, 0.565229, 0.564404, 0.563579, 0.562755, 0.561931, 0.561108, 0.560285, 0.559463, 0.558642, 0.557821, 0.557001, 0.556182, 0.555363, 0.554544, 0.553726, 0.552909, 0.552092, 0.551276, 0.550461, 0.549646, 0.548832, 0.548018, 0.547205, 0.546393, 0.545581, 0.544769, 0.543959, 0.543149, 0.542339, 0.541530, 0.540722, 0.539914, 0.539107, 0.538301, 0.537495, 0.536690, 0.535885, 0.535081, 0.534278, 0.533475, 0.532672, 0.531871, 0.531070, 0.530270, 0.529470, 0.528671, 0.527872, 0.527074, 0.526277, 0.525480, 0.524684, 0.523889, 0.523094, 0.522300, 0.521506, 0.520713, 0.519921, 0.519129, 0.518338, 0.517547, 0.516758, 0.515968, 0.515180, 0.514392, 0.513604, 0.512818, 0.512032, 0.511246, 0.510461, 0.509677, 0.508893, 0.508111, 0.507328, 0.506547, 0.505765, 0.504985, 0.504205, 0.503426, 0.502648, 0.501870, 0.501093, 0.500316, 0.499540, 0.498765, 0.497990, 0.497216, 0.496443, 0.495670, 0.494898, 0.494126, 0.493355, 0.492585, 0.491816, 0.491047, 0.490279, 0.489511, 0.488744, 0.487978, 0.487212, 0.486447, 0.485683, 0.484919, 0.484156, 0.483394, 0.482632, 0.481871, 0.481110, 0.480351, 0.479592, 0.478833, 0.478075, 0.477318, 0.476562, 0.475806, 0.475051, 0.474296, 0.473542, 0.472789, 0.472036, 0.471284, 0.470533, 0.469783, 0.469033, 0.468284, 0.467535, 0.466787, 0.466040, 0.465293, 0.464547, 0.463802, 0.463057, 0.462313, 0.461570, 0.460828, 0.460086, 0.459344, 0.458604, 0.457864, 0.457125, 0.456386, 0.455648, 0.454911, 0.454174, 0.453439, 0.452703, 0.451969, 0.451235, 0.450502, 0.449769, 0.449037, 0.448306, 0.447576, 0.446846, 0.446117, 0.445388, 0.444661, 0.443934, 0.443207, 0.442481, 0.441756, 0.441032, 0.440308, 0.439585, 0.438863, 0.438141, 0.437420, 0.436700, 0.435980, 0.435262, 0.434543, 0.433826, 0.433109, 0.432393, 0.431677, 0.430962, 0.430248, 0.429535, 0.428822, 0.428110, 0.427399, 0.426688, 0.425978, 0.425269, 0.424560, 0.423852, 0.423145, 0.422439, 0.421733, 0.421028, 0.420323, 0.419619, 0.418916, 0.418214, 0.417512, 0.416811, 0.416111, 0.415411, 0.414712, 0.414014, 0.413317, 0.412620, 0.411924, 0.411228, 0.410534, 0.409840, 0.409146, 0.408454, 0.407762, 0.407071, 0.406380, 0.405690, 0.405001, 0.404313, 0.403625, 0.402938, 0.402252, 0.401566, 0.400881, 0.400197, 0.399513, 0.398830, 0.398148, 0.397467, 0.396786, 0.396106, 0.395427, 0.394748, 0.394070, 0.393393, 0.392717, 0.392041, 0.391366, 0.390692, 0.390018, 0.389345, 0.388673, 0.388001, 0.387330, 0.386660, 0.385991, 0.385322, 0.384654, 0.383987, 0.383320, 0.382654, 0.381989, 0.381325, 0.380661, 0.379998, 0.379336, 0.378674, 0.378013, 0.377353, 0.376694, 0.376035, 0.375377, 0.374719, 0.374063, 0.373407, 0.372752, 0.372097, 0.371443, 0.370790, 0.370138, 0.369486, 0.368835, 0.368185, 0.367536, 0.366887, 0.366239, 0.365592, 0.364945, 0.364299, 0.363654, 0.363009, 0.362366, 0.361722, 0.361080, 0.360438, 0.359798, 0.359157, 0.358518, 0.357879, 0.357241, 0.356604, 0.355967, 0.355331, 0.354696, 0.354062, 0.353428, 0.352795, 0.352163, 0.351531, 0.350900, 0.350270, 0.349640, 0.349012, 0.348384, 0.347756, 0.347130, 0.346504, 0.345879, 0.345255, 0.344631, 0.344008, 0.343386, 0.342764, 0.342143, 0.341523, 0.340904, 0.340285, 0.339667, 0.339050, 0.338434, 0.337818, 0.337203, 0.336588, 0.335975, 0.335362, 0.334750, 0.334138, 0.333528, 0.332918, 0.332308, 0.331700, 0.331092, 0.330485, 0.329878, 0.329273, 0.328668, 0.328063, 0.327460, 0.326857, 0.326255, 0.325654, 0.325053, 0.324453, 0.323854, 0.323256, 0.322658, 0.322061, 0.321464, 0.320869, 0.320274, 0.319680, 0.319086, 0.318494, 0.317902, 0.317311, 0.316720, 0.316130, 0.315541, 0.314953, 0.314365, 0.313778, 0.313192, 0.312606, 0.312022, 0.311438, 0.310854, 0.310272, 0.309690, 0.309109, 0.308528, 0.307949, 0.307370, 0.306791, 0.306214, 0.305637, 0.305061, 0.304485, 0.303911, 0.303337, 0.302764, 0.302191, 0.301619, 0.301048, 0.300478, 0.299908, 0.299339, 0.298771, 0.298204, 0.297637, 0.297071, 0.296506, 0.295941, 0.295377, 0.294814, 0.294252, 0.293690, 0.293129, 0.292569, 0.292009, 0.291450, 0.290892, 0.290335, 0.289778, 0.289222, 0.288667, 0.288113, 0.287559, 0.287006, 0.286453, 0.285902, 0.285351, 0.284801, 0.284251, 0.283702, 0.283154, 0.282607, 0.282061, 0.281515, 0.280969, 0.280425, 0.279881, 0.279338, 0.278796, 0.278254, 0.277714, 0.277173, 0.276634, 0.276095, 0.275557, 0.275020, 0.274483, 0.273947, 0.273412, 0.272878, 0.272344, 0.271811, 0.271279, 0.270747, 0.270217, 0.269686, 0.269157, 0.268628, 0.268100, 0.267573, 0.267046, 0.266521, 0.265995, 0.265471, 0.264947, 0.264424, 0.263902, 0.263380, 0.262859, 0.262339, 0.261820, 0.261301, 0.260783, 0.260266, 0.259749, 0.259233, 0.258718, 0.258204, 0.257690, 0.257177, 0.256664, 0.256153, 0.255642, 0.255132, 0.254622, 0.254113, 0.253605, 0.253098, 0.252591, 0.252085, 0.251580, 0.251075, 0.250572, 0.250068, 0.249566, 0.249064, 0.248563, 0.248063, 0.247563, 0.247064, 0.246566, 0.246069, 0.245572, 0.245076, 0.244580, 0.244086, 0.243592, 0.243098, 0.242606, 0.242114, 0.241623, 0.241132, 0.240643, 0.240154, 0.239665, 0.239177, 0.238691, 0.238204, 0.237719, 0.237234, 0.236750, 0.236266, 0.235783, 0.235301, 0.234820, 0.234339, 0.233859, 0.233380, 0.232901, 0.232424, 0.231946, 0.231470, 0.230994, 0.230519, 0.230045, 0.229571, 0.229098, 0.228625, 0.228154, 0.227683, 0.227213, 0.226743, 0.226274, 0.225806, 0.225339, 0.224872, 0.224406, 0.223940, 0.223476, 0.223012, 0.222548, 0.222086, 0.221624, 0.221162, 0.220702, 0.220242, 0.219783, 0.219324, 0.218866, 0.218409, 0.217953, 0.217497, 0.217042, 0.216587, 0.216134, 0.215681, 0.215228, 0.214777, 0.214326, 0.213875, 0.213426, 0.212977, 0.212529, 0.212081, 0.211634, 0.211188, 0.210743, 0.210298, 0.209854, 0.209410, 0.208967, 0.208525, 0.208084, 0.207643, 0.207203, 0.206763, 0.206325, 0.205887, 0.205449, 0.205013, 0.204577, 0.204141, 0.203706, 0.203272, 0.202839, 0.202406, 0.201975, 0.201543, 0.201113, 0.200683, 0.200253, 0.199825, 0.199397, 0.198969, 0.198543, 0.198117, 0.197692, 0.197267, 0.196843, 0.196420, 0.195997, 0.195575, 0.195154, 0.194733, 0.194313, 0.193894, 0.193475, 0.193058, 0.192640, 0.192224, 0.191808, 0.191392, 0.190978, 0.190564, 0.190150, 0.189738, 0.189326, 0.188914, 0.188504, 0.188094, 0.187684, 0.187276, 0.186868, 0.186460, 0.186054, 0.185647, 0.185242, 0.184837, 0.184433, 0.184030, 0.183627, 0.183225, 0.182823, 0.182422, 0.182022, 0.181623, 0.181224, 0.180826, 0.180428, 0.180031, 0.179635, 0.179239, 0.178844, 0.178450, 0.178056, 0.177663, 0.177271, 0.176879, 0.176488, 0.176097, 0.175708, 0.175318, 0.174930, 0.174542, 0.174155, 0.173768, 0.173382, 0.172997, 0.172612, 0.172228, 0.171845, 0.171462, 0.171080, 0.170698, 0.170317, 0.169937, 0.169558, 0.169179, 0.168800, 0.168423, 0.168046, 0.167669, 0.167294, 0.166918, 0.166544, 0.166170, 0.165797, 0.165424, 0.165052, 0.164681, 0.164310, 0.163940, 0.163571, 0.163202, 0.162834, 0.162466, 0.162099, 0.161733, 0.161367, 0.161002, 0.160638, 0.160274, 0.159911, 0.159548, 0.159186, 0.158825, 0.158464, 0.158104, 0.157744, 0.157386, 0.157027, 0.156670, 0.156313, 0.155956, 0.155601, 0.155245, 0.154891, 0.154537, 0.154184, 0.153831, 0.153479, 0.153127, 0.152777, 0.152426, 0.152077, 0.151728, 0.151379, 0.151032, 0.150684, 0.150338, 0.149992, 0.149646, 0.149302, 0.148958, 0.148614, 0.148271, 0.147929, 0.147587, 0.147246, 0.146905, 0.146565, 0.146226, 0.145887, 0.145549, 0.145212, 0.144875, 0.144539, 0.144203, 0.143868, 0.143533, 0.143199, 0.142866, 0.142533, 0.142201, 0.141870, 0.141539, 0.141208, 0.140878, 0.140549, 0.140221, 0.139893, 0.139565, 0.139239, 0.138912, 0.138587, 0.138262, 0.137937, 0.137613, 0.137290, 0.136967, 0.136645, 0.136324, 0.136003, 0.135683, 0.135363, 0.135044, 0.134725, 0.134407, 0.134089, 0.133773, 0.133456, 0.133141, 0.132826, 0.132511, 0.132197, 0.131884, 0.131571, 0.131259, 0.130947, 0.130636, 0.130325, 0.130015, 0.129706, 0.129397, 0.129089, 0.128781, 0.128474, 0.128168, 0.127862, 0.127556, 0.127251, 0.126947, 0.126644, 0.126340, 0.126038, 0.125736, 0.125434, 0.125134, 0.124833, 0.124534, 0.124234, 0.123936, 0.123638, 0.123340, 0.123043, 0.122747, 0.122451, 0.122156, 0.121861, 0.121567, 0.121273, 0.120980, 0.120688, 0.120396, 0.120105, 0.119814, 0.119524, 0.119234, 0.118945, 0.118656, 0.118368, 0.118080, 0.117793, 0.117507, 0.117221, 0.116936, 0.116651, 0.116367, 0.116083, 0.115800, 0.115517, 0.115235, 0.114954, 0.114673, 0.114392, 0.114112, 0.113833, 0.113554, 0.113276, 0.112998, 0.112721, 0.112444, 0.112168, 0.111893, 0.111618, 0.111343, 0.111069, 0.110796, 0.110523, 0.110250, 0.109978, 0.109707, 0.109436, 0.109166, 0.108896, 0.108627, 0.108358, 0.108090, 0.107822, 0.107555, 0.107289, 0.107023, 0.106757, 0.106492, 0.106227, 0.105963, 0.105700, 0.105437, 0.105175, 0.104913, 0.104651, 0.104390, 0.104130, 0.103870, 0.103611, 0.103352, 0.103094, 0.102836, 0.102579, 0.102322, 0.102066, 0.101810, 0.101555, 0.101300, 0.101046, 0.100792, 0.100539, 0.100286, 0.100034, 0.099782, 0.099531, 0.099281, 0.099030, 0.098781, 0.098532, 0.098283, 0.098035, 0.097787, 0.097540, 0.097293, 0.097047, 0.096802, 0.096556, 0.096312, 0.096068, 0.095824, 0.095581, 0.095338, 0.095096, 0.094854, 0.094613, 0.094372, 0.094132, 0.093892, 0.093653, 0.093414, 0.093176, 0.092938, 0.092701, 0.092464, 0.092228, 0.091992, 0.091757, 0.091522, 0.091288, 0.091054, 0.090820, 0.090587, 0.090355, 0.090123, 0.089891, 0.089660, 0.089430, 0.089200, 0.088970, 0.088741, 0.088513, 0.088284, 0.088057, 0.087830, 0.087603, 0.087377, 0.087151, 0.086925, 0.086701, 0.086476, 0.086252, 0.086029, 0.085806, 0.085583, 0.085361, 0.085140, 0.084919, 0.084698, 0.084478, 0.084258, 0.084039, 0.083820, 0.083602, 0.083384, 0.083167, 0.082950, 0.082733, 0.082517, 0.082302, 0.082087, 0.081872, 0.081658, 0.081444, 0.081231, 0.081018, 0.080805, 0.080594, 0.080382, 0.080171, 0.079960, 0.079750, 0.079541, 0.079331, 0.079123, 0.078914, 0.078706, 0.078499, 0.078292, 0.078085, 0.077879, 0.077674, 0.077468, 0.077264, 0.077059, 0.076855, 0.076652, 0.076449, 0.076246, 0.076044, 0.075842, 0.075641, 0.075440, 0.075240, 0.075040, 0.074840, 0.074641, 0.074443, 0.074244, 0.074047, 0.073849, 0.073652, 0.073456, 0.073260, 0.073064, 0.072869, 0.072674, 0.072480, 0.072286, 0.072092, 0.071899, 0.071707, 0.071514, 0.071322, 0.071131, 0.070940, 0.070750, 0.070559, 0.070370, 0.070180, 0.069991, 0.069803, 0.069615, 0.069427, 0.069240, 0.069053, 0.068867, 0.068681, 0.068495, 0.068310, 0.068125, 0.067941, 0.067757, 0.067574, 0.067391, 0.067208, 0.067026, 0.066844, 0.066662, 0.066481, 0.066301, 0.066120, 0.065941, 0.065761, 0.065582, 0.065403, 0.065225, 0.065047, 0.064870, 0.064693, 0.064516, 0.064340, 0.064164, 0.063989, 0.063814, 0.063639, 0.063465, 0.063291, 0.063117, 0.062944, 0.062772, 0.062599, 0.062427, 0.062256, 0.062085, 0.061914, 0.061744, 0.061574, 0.061404, 0.061235, 0.061066, 0.060898, 0.060730, 0.060562, 0.060395, 0.060228, 0.060061, 0.059895, 0.059730, 0.059564, 0.059399, 0.059235, 0.059071, 0.058907, 0.058743, 0.058580, 0.058417, 0.058255, 0.058093, 0.057932, 0.057770, 0.057610, 0.057449, 0.057289, 0.057129, 0.056970, 0.056811, 0.056652, 0.056494, 0.056336, 0.056179, 0.056022, 0.055865, 0.055709, 0.055552, 0.055397, 0.055241, 0.055087, 0.054932, 0.054778, 0.054624, 0.054470, 0.054317, 0.054164, 0.054012, 0.053860, 0.053708, 0.053557, 0.053406, 0.053255, 0.053105, 0.052955, 0.052806, 0.052656, 0.052507, 0.052359, 0.052211, 0.052063, 0.051915, 0.051768, 0.051622, 0.051475, 0.051329, 0.051183, 0.051038, 0.050893, 0.050748, 0.050604, 0.050460, 0.050316, 0.050173, 0.050030, 0.049887, 0.049745, 0.049603, 0.049462, 0.049320, 0.049179, 0.049039, 0.048899, 0.048759, 0.048619, 0.048480, 0.048341, 0.048202, 0.048064, 0.047926, 0.047789, 0.047651, 0.047515, 0.047378, 0.047242, 0.047106, 0.046970, 0.046835, 0.046700, 0.046565, 0.046431, 0.046297, 0.046164, 0.046030, 0.045897, 0.045765, 0.045632, 0.045500, 0.045369, 0.045237, 0.045106, 0.044975, 0.044845, 0.044715, 0.044585, 0.044456, 0.044327, 0.044198, 0.044069, 0.043941, 0.043813, 0.043686, 0.043558, 0.043432, 0.043305, 0.043179, 0.043053, 0.042927, 0.042802, 0.042677, 0.042552, 0.042427, 0.042303, 0.042179, 0.042056, 0.041933, 0.041810, 0.041687, 0.041565, 0.041443, 0.041321, 0.041200, 0.041079, 0.040958, 0.040837, 0.040717, 0.040597, 0.040478, 0.040358, 0.040239, 0.040121, 0.040002, 0.039884, 0.039767, 0.039649, 0.039532, 0.039415, 0.039298, 0.039182, 0.039066, 0.038950, 0.038835, 0.038720, 0.038605, 0.038490, 0.038376, 0.038262, 0.038148, 0.038035, 0.037922, 0.037809, 0.037696, 0.037584, 0.037472, 0.037360, 0.037249, 0.037138, 0.037027, 0.036916, 0.036806, 0.036696, 0.036586, 0.036477, 0.036367, 0.036258, 0.036150, 0.036041, 0.035933, 0.035826, 0.035718, 0.035611, 0.035504, 0.035397, 0.035291, 0.035185, 0.035079, 0.034973, 0.034868, 0.034763, 0.034658, 0.034553, 0.034449, 0.034345, 0.034242, 0.034138, 0.034035, 0.033932, 0.033829, 0.033727, 0.033625, 0.033523, 0.033421, 0.033320, 0.033219, 0.033118, 0.033018, 0.032917, 0.032817, 0.032718, 0.032618, 0.032519, 0.032420, 0.032321, 0.032223, 0.032125, 0.032027, 0.031929, 0.031832, 0.031734, 0.031637, 0.031541, 0.031444, 0.031348, 0.031252, 0.031157, 0.031061, 0.030966, 0.030871, 0.030776, 0.030682, 0.030588, 0.030494, 0.030400, 0.030307, 0.030214, 0.030121, 0.030028, 0.029936, 0.029844, 0.029752, 0.029660, 0.029568, 0.029477, 0.029386, 0.029295, 0.029205, 0.029115, 0.029025, 0.028935, 0.028845, 0.028756, 0.028667, 0.028578, 0.028490, 0.028401, 0.028313, 0.028225, 0.028138, 0.028050, 0.027963, 0.027876, 0.027790, 0.027703, 0.027617, 0.027531, 0.027445, 0.027360, 0.027274, 0.027189, 0.027104, 0.027020, 0.026935, 0.026851, 0.026767, 0.026683, 0.026600, 0.026517, 0.026434, 0.026351, 0.026268, 0.026186, 0.026104, 0.026022, 0.025940, 0.025859, 0.025777, 0.025696, 0.025616, 0.025535, 0.025455, 0.025374, 0.025295, 0.025215, 0.025135, 0.025056, 0.024977, 0.024898, 0.024820, 0.024741, 0.024663, 0.024585, 0.024507, 0.024430, 0.024352, 0.024275, 0.024198, 0.024121, 0.024045, 0.023969, 0.023893, 0.023817, 0.023741, 0.023666, 0.023590, 0.023515, 0.023440, 0.023366, 0.023291, 0.023217, 0.023143, 0.023069, 0.022996, 0.022922, 0.022849, 0.022776, 0.022703, 0.022631, 0.022558, 0.022486, 0.022414, 0.022343, 0.022271, 0.022200, 0.022128, 0.022057, 0.021987, 0.021916, 0.021846, 0.021775, 0.021705, 0.021636, 0.021566, 0.021497, 0.021427, 0.021358, 0.021290, 0.021221, 0.021153, 0.021084, 0.021016, 0.020948, 0.020881, 0.020813, 0.020746, 0.020679, 0.020612, 0.020545, 0.020479, 0.020412, 0.020346, 0.020280, 0.020214, 0.020149, 0.020083, 0.020018, 0.019953, 0.019888, 0.019824, 0.019759, 0.019695, 0.019631, 0.019567, 0.019503, 0.019439, 0.019376, 0.019313, 0.019250, 0.019187, 0.019124, 0.019062, 0.018999, 0.018937, 0.018875, 0.018813, 0.018752, 0.018690, 0.018629, 0.018568, 0.018507, 0.018446, 0.018386, 0.018326, 0.018265, 0.018205, 0.018145, 0.018086, 0.018026, 0.017967, 0.017908, 0.017849, 0.017790, 0.017731, 0.017673, 0.017614, 0.017556, 0.017498, 0.017440, 0.017383, 0.017325, 0.017268, 0.017211, 0.017154, 0.017097, 0.017040, 0.016984, 0.016928, 0.016871, 0.016815, 0.016760, 0.016704, 0.016648, 0.016593, 0.016538, 0.016483, 0.016428, 0.016373, 0.016319, 0.016264, 0.016210, 0.016156, 0.016102, 0.016048, 0.015995, 0.015941, 0.015888, 0.015835, 0.015782, 0.015729, 0.015676, 0.015624, 0.015572, 0.015519, 0.015467, 0.015416, 0.015364, 0.015312, 0.015261, 0.015210, 0.015158, 0.015107, 0.015057, 0.015006, 0.014955, 0.014905, 0.014855, 0.014805, 0.014755, 0.014705, 0.014656, 0.014606, 0.014557, 0.014508, 0.014459, 0.014410, 0.014361, 0.014312, 0.014264, 0.014216, 0.014167, 0.014119, 0.014071, 0.014024, 0.013976, 0.013929, 0.013881, 0.013834, 0.013787, 0.013740, 0.013694, 0.013647, 0.013601, 0.013554, 0.013508, 0.013462, 0.013416, 0.013370, 0.013325, 0.013279, 0.013234, 0.013189, 0.013144, 0.013099, 0.013054, 0.013009, 0.012965, 0.012920, 0.012876, 0.012832, 0.012788, 0.012744, 0.012700, 0.012657, 0.012613, 0.012570, 0.012527, 0.012484, 0.012441, 0.012398, 0.012355, 0.012313, 0.012270, 0.012228, 0.012186, 0.012144, 0.012102, 0.012060, 0.012019, 0.011977, 0.011936, 0.011894, 0.011853, 0.011812, 0.011771, 0.011731, 0.011690, 0.011649, 0.011609, 0.011569, 0.011529, 0.011489, 0.011449, 0.011409, 0.011369, 0.011330, 0.011290, 0.011251, 0.011212, 0.011173, 0.011134, 0.011095, 0.011057, 0.011018, 0.010980, 0.010941, 0.010903, 0.010865, 0.010827, 0.010789, 0.010752, 0.010714, 0.010676, 0.010639, 0.010602, 0.010565, 0.010528, 0.010491, 0.010454, 0.010417, 0.010381, 0.010344, 0.010308, 0.010272, 0.010236, 0.010200, 0.010164, 0.010128, 0.010092, 0.010057, 0.010021, 0.009986, 0.009951, 0.009916, 0.009881, 0.009846, 0.009811, 0.009776, 0.009742, 0.009707, 0.009673, 0.009639, 0.009605, 0.009571, 0.009537, 0.009503, 0.009469, 0.009436, 0.009402, 0.009369, 0.009336, 0.009302, 0.009269, 0.009236, 0.009204, 0.009171, 0.009138, 0.009106, 0.009073, 0.009041, 0.009009, 0.008977, 0.008945, 0.008913, 0.008881, 0.008849, 0.008818, 0.008786, 0.008755, 0.008723, 0.008692, 0.008661, 0.008630, 0.008599, 0.008568, 0.008538, 0.008507, 0.008476, 0.008446, 0.008416, 0.008385, 0.008355, 0.008325, 0.008295, 0.008266, 0.008236, 0.008206, 0.008177, 0.008147, 0.008118, 0.008089, 0.008059, 0.008030, 0.008001, 0.007972, 0.007944, 0.007915, 0.007886, 0.007858, 0.007829, 0.007801, 0.007773, 0.007745, 0.007717, 0.007689, 0.007661, 0.007633, 0.007605, 0.007578, 0.007550, 0.007523, 0.007495, 0.007468, 0.007441, 0.007414, 0.007387, 0.007360, 0.007333, 0.007307, 0.007280, 0.007253, 0.007227, 0.007201, 0.007174, 0.007148, 0.007122, 0.007096, 0.007070, 0.007044, 0.007018, 0.006993, 0.006967, 0.006942, 0.006916, 0.006891, 0.006866, 0.006840, 0.006815, 0.006790, 0.006765, 0.006740, 0.006716, 0.006691, 0.006666, 0.006642, 0.006617, 0.006593, 0.006569, 0.006545, 0.006520, 0.006496, 0.006472, 0.006449, 0.006425, 0.006401, 0.006377, 0.006354, 0.006330, 0.006307, 0.006284, 0.006260, 0.006237, 0.006214, 0.006191, 0.006168, 0.006145, 0.006122, 0.006100, 0.006077, 0.006055, 0.006032, 0.006010, 0.005987, 0.005965, 0.005943, 0.005921, 0.005899, 0.005877, 0.005855, 0.005833, 0.005811, 0.005790, 0.005768, 0.005747, 0.005725, 0.005704, 0.005682, 0.005661, 0.005640, 0.005619, 0.005598, 0.005577, 0.005556, 0.005535, 0.005514, 0.005494, 0.005473, 0.005453, 0.005432, 0.005412, 0.005391, 0.005371, 0.005351, 0.005331, 0.005311, 0.005291, 0.005271, 0.005251, 0.005231, 0.005212, 0.005192, 0.005172, 0.005153, 0.005134, 0.005114, 0.005095, 0.005076, 0.005056, 0.005037, 0.005018, 0.004999, 0.004980, 0.004961, 0.004943, 0.004924, 0.004905, 0.004887, 0.004868, 0.004850, 0.004831, 0.004813, 0.004795, 0.004776, 0.004758, 0.004740, 0.004722, 0.004704, 0.004686, 0.004668, 0.004651, 0.004633, 0.004615, 0.004598, 0.004580, 0.004563, 0.004545, 0.004528, 0.004511, 0.004493, 0.004476, 0.004459, 0.004442, 0.004425, 0.004408, 0.004391, 0.004374, 0.004358, 0.004341, 0.004324, 0.004308, 0.004291, 0.004275, 0.004258, 0.004242, 0.004226, 0.004209, 0.004193, 0.004177, 0.004161, 0.004145, 0.004129, 0.004113, 0.004097, 0.004081, 0.004066, 0.004050, 0.004034, 0.004019, 0.004003, 0.003988, 0.003972, 0.003957, 0.003942, 0.003927, 0.003911, 0.003896, 0.003881, 0.003866, 0.003851, 0.003836, 0.003821, 0.003806, 0.003792, 0.003777, 0.003762, 0.003748, 0.003733, 0.003719, 0.003704, 0.003690, 0.003675, 0.003661, 0.003647, 0.003633, 0.003618, 0.003604, 0.003590, 0.003576, 0.003562, 0.003548, 0.003534, 0.003521, 0.003507, 0.003493, 0.003480, 0.003466, 0.003452, 0.003439, 0.003425, 0.003412, 0.003399, 0.003385, 0.003372, 0.003359, 0.003346, 0.003332, 0.003319, 0.003306, 0.003293, 0.003280, 0.003267, 0.003255, 0.003242, 0.003229, 0.003216, 0.003204, 0.003191, 0.003178, 0.003166, 0.003153, 0.003141, 0.003128, 0.003116, 0.003104, 0.003092, 0.003079, 0.003067, 0.003055, 0.003043, 0.003031, 0.003019, 0.003007, 0.002995, 0.002983, 0.002971, 0.002959, 0.002948, 0.002936, 0.002924, 0.002913, 0.002901, 0.002890, 0.002878, 0.002867, 0.002855, 0.002844, 0.002833, 0.002821, 0.002810, 0.002799, 0.002788, 0.002777, 0.002765, 0.002754, 0.002743, 0.002732, 0.002722, 0.002711, 0.002700, 0.002689, 0.002678, 0.002668, 0.002657, 0.002646, 0.002636, 0.002625, 0.002614, 0.002604, 0.002594, 0.002583, 0.002573, 0.002562, 0.002552, 0.002542, 0.002532, 0.002521, 0.002511, 0.002501, 0.002491, 0.002481, 0.002471, 0.002461, 0.002451, 0.002441, 0.002431, 0.002422, 0.002412, 0.002402, 0.002392, 0.002383, 0.002373, 0.002363, 0.002354, 0.002344, 0.002335, 0.002325, 0.002316, 0.002307, 0.002297, 0.002288, 0.002279, 0.002269, 0.002260, 0.002251, 0.002242, 0.002233, 0.002224, 0.002215, 0.002206, 0.002197, 0.002188, 0.002179, 0.002170, 0.002161, 0.002152, 0.002143, 0.002135, 0.002126, 0.002117, 0.002109, 0.002100, 0.002091, 0.002083, 0.002074, 0.002066, 0.002057, 0.002049, 0.002041, 0.002032, 0.002024, 0.002016, 0.002007, 0.001999, 0.001991, 0.001983, 0.001975, 0.001967, 0.001958, 0.001950, 0.001942, 0.001934, 0.001926, 0.001919, 0.001911, 0.001903, 0.001895, 0.001887, 0.001879, 0.001872, 0.001864, 0.001856, 0.001848, 0.001841, 0.001833, 0.001826, 0.001818, 0.001811, 0.001803, 0.001796, 0.001788, 0.001781, 0.001773, 0.001766, 0.001759, 0.001751, 0.001744, 0.001737, 0.001730, 0.001723, 0.001715, 0.001708, 0.001701, 0.001694, 0.001687, 0.001680, 0.001673, 0.001666, 0.001659, 0.001652, 0.001645, 0.001639, 0.001632, 0.001625, 0.001618, 0.001611, 0.001605, 0.001598, 0.001591, 0.001585, 0.001578, 0.001571, 0.001565, 0.001558, 0.001552, 0.001545, 0.001539, 0.001532, 0.001526, 0.001519, 0.001513, 0.001507, 0.001500, 0.001494, 0.001488, 0.001482, 0.001475, 0.001469, 0.001463, 0.001457, 0.001451, 0.001445, 0.001438, 0.001432, 0.001426, 0.001420, 0.001414, 0.001408, 0.001402, 0.001397, 0.001391, 0.001385, 0.001379, 0.001373, 0.001367, 0.001362, 0.001356, 0.001350, 0.001344, 0.001339, 0.001333, 0.001327, 0.001322, 0.001316, 0.001310, 0.001305, 0.001299, 0.001294, 0.001288, 0.001283, 0.001277, 0.001272, 0.001267, 0.001261, 0.001256, 0.001250, 0.001245, 0.001240, 0.001235, 0.001229, 0.001224, 0.001219, 0.001214, 0.001208, 0.001203, 0.001198, 0.001193, 0.001188, 0.001183, 0.001178, 0.001173, 0.001168, 0.001163, 0.001158, 0.001153, 0.001148, 0.001143, 0.001138, 0.001133, 0.001128, 0.001123, 0.001119, 0.001114, 0.001109, 0.001104, 0.001100, 0.001095, 0.001090, 0.001085, 0.001081, 0.001076, 0.001071, 0.001067, 0.001062, 0.001058, 0.001053, 0.001049, 0.001044, 0.001040, 0.001035, 0.001031, 0.001026, 0.001022, 0.001017, 0.001013, 0.001008, 0.001004, 0.001000, 0.000995, 0.000991, 0.000987, 0.000983, 0.000978, 0.000974, 0.000970, 0.000966, 0.000961, 0.000957, 0.000953, 0.000949, 0.000945, 0.000941, 0.000937, 0.000933, 0.000928, 0.000924, 0.000920, 0.000916, 0.000912, 0.000908, 0.000904, 0.000900, 0.000897, 0.000893, 0.000889, 0.000885, 0.000881, 0.000877, 0.000873, 0.000869, 0.000866, 0.000862, 0.000858, 0.000854, 0.000851, 0.000847, 0.000843, 0.000839, 0.000836, 0.000832, 0.000828, 0.000825, 0.000821, 0.000818, 0.000814, 0.000810, 0.000807, 0.000803, 0.000800, 0.000796, 0.000793, 0.000789, 0.000786, 0.000782, 0.000779, 0.000775, 0.000772, 0.000769, 0.000765, 0.000762, 0.000758, 0.000755, 0.000752, 0.000748, 0.000745, 0.000742, 0.000739, 0.000735, 0.000732, 0.000729, 0.000726, 0.000722, 0.000719, 0.000716, 0.000713, 0.000710, 0.000706, 0.000703, 0.000700, 0.000697, 0.000694, 0.000691, 0.000688, 0.000685, 0.000682, 0.000679, 0.000676, 0.000673, 0.000670, 0.000667, 0.000664, 0.000661, 0.000658, 0.000655, 0.000652, 0.000649, 0.000646, 0.000643, 0.000640, 0.000637, 0.000635, 0.000632, 0.000629, 0.000626, 0.000623, 0.000621, 0.000618, 0.000615, 0.000612, 0.000610, 0.000607, 0.000604, 0.000601, 0.000599, 0.000596, 0.000593, 0.000591, 0.000588, 0.000585, 0.000583, 0.000580, 0.000577, 0.000575, 0.000572, 0.000570, 0.000567, 0.000565, 0.000562, 0.000559, 0.000557, 0.000554, 0.000552, 0.000549, 0.000547, 0.000544, 0.000542, 0.000540, 0.000537, 0.000535, 0.000532, 0.000530, 0.000527, 0.000525, 0.000523, 0.000520, 0.000518, 0.000516, 0.000513, 0.000511, 0.000509, 0.000506, 0.000504, 0.000502, 0.000499, 0.000497, 0.000495, 0.000493, 0.000490, 0.000488, 0.000486, 0.000484, 0.000482, 0.000479, 0.000477, 0.000475, 0.000473, 0.000471, 0.000468, 0.000466, 0.000464, 0.000462, 0.000460, 0.000458, 0.000456, 0.000454, 0.000452, 0.000450, 0.000447, 0.000445, 0.000443, 0.000441, 0.000439, 0.000437, 0.000435, 0.000433, 0.000431, 0.000429, 0.000427, 0.000425, 0.000423, 0.000421, 0.000420, 0.000418, 0.000416, 0.000414, 0.000412, 0.000410, 0.000408, 0.000406, 0.000404, 0.000402, 0.000401, 0.000399, 0.000397, 0.000395, 0.000393, 0.000391, 0.000390, 0.000388, 0.000386, 0.000384, 0.000382, 0.000381, 0.000379, 0.000377, 0.000375, 0.000374, 0.000372, 0.000370, 0.000369, 0.000367, 0.000365, 0.000363, 0.000362, 0.000360, 0.000358, 0.000357, 0.000355, 0.000353, 0.000352, 0.000350, 0.000348, 0.000347, 0.000345, 0.000344, 0.000342, 0.000340, 0.000339, 0.000337, 0.000336, 0.000334, 0.000333, 0.000331, 0.000329, 0.000328, 0.000326, 0.000325, 0.000323, 0.000322, 0.000320, 0.000319, 0.000317, 0.000316, 0.000314, 0.000313, 0.000311, 0.000310, 0.000308, 0.000307, 0.000306, 0.000304, 0.000303, 0.000301, 0.000300, 0.000298, 0.000297, 0.000296, 0.000294, 0.000293, 0.000292, 0.000290, 0.000289, 0.000287, 0.000286, 0.000285, 0.000283, 0.000282, 0.000281, 0.000279, 0.000278, 0.000277, 0.000275, 0.000274, 0.000273, 0.000272, 0.000270, 0.000269, 0.000268, 0.000266, 0.000265, 0.000264, 0.000263, 0.000261, 0.000260, 0.000259, 0.000258, 0.000257, 0.000255, 0.000254, 0.000253, 0.000252, 0.000250, 0.000249, 0.000248, 0.000247, 0.000246, 0.000245, 0.000243, 0.000242, 0.000241, 0.000240, 0.000239, 0.000238, 0.000237, 0.000235, 0.000234, 0.000233, 0.000232, 0.000231, 0.000230, 0.000229, 0.000228, 0.000227, 0.000225, 0.000224, 0.000223, 0.000222, 0.000221, 0.000220, 0.000219, 0.000218, 0.000217, 0.000216, 0.000215, 0.000214, 0.000213, 0.000212, 0.000211, 0.000210, 0.000209, 0.000208, 0.000207, 0.000206, 0.000205, 0.000204, 0.000203, 0.000202, 0.000201, 0.000200, 0.000199, 0.000198, 0.000197, 0.000196, 0.000195, 0.000194, 0.000193, 0.000192, 0.000191, 0.000190, 0.000190, 0.000189, 0.000188, 0.000187, 0.000186, 0.000185, 0.000184, 0.000183, 0.000182, 0.000181, 0.000181, 0.000180, 0.000179, 0.000178, 0.000177, 0.000176, 0.000175, 0.000174, 0.000174, 0.000173, 0.000172, 0.000171, 0.000170, 0.000169, 0.000169, 0.000168, 0.000167, 0.000166, 0.000165, 0.000165, 0.000164, 0.000163, 0.000162, 0.000161, 0.000161, 0.000160, 0.000159, 0.000158, 0.000157, 0.000157, 0.000156, 0.000155, 0.000154, 0.000154, 0.000153, 0.000152, 0.000151, 0.000151, 0.000150, 0.000149, 0.000148, 0.000148, 0.000147, 0.000146, 0.000146, 0.000145, 0.000144, 0.000143, 0.000143, 0.000142, 0.000141, 0.000141, 0.000140, 0.000139, 0.000139, 0.000138, 0.000137, 0.000137, 0.000136, 0.000135, 0.000134, 0.000134, 0.000133, 0.000133, 0.000132, 0.000131, 0.000131, 0.000130, 0.000129, 0.000129, 0.000128, 0.000127, 0.000127, 0.000126, 0.000125, 0.000125, 0.000124, 0.000124, 0.000123, 0.000122, 0.000122, 0.000121, 0.000121, 0.000120, 0.000119, 0.000119, 0.000118, 0.000118, 0.000117, 0.000116, 0.000116, 0.000115, 0.000115, 0.000114, 0.000114, 0.000113, 0.000112, 0.000112, 0.000111, 0.000111, 0.000110, 0.000110, 0.000109, 0.000109, 0.000108, 0.000107, 0.000107, 0.000106, 0.000106, 0.000105, 0.000105, 0.000104, 0.000104, 0.000103, 0.000103, 0.000102, 0.000102, 0.000101, 0.000101, 0.000100, 0.000100, 0.000099, 0.000099, 0.000098, 0.000098, 0.000097, 0.000097, 0.000096, 0.000096, 0.000095, 0.000095, 0.000094, 0.000094, 0.000093, 0.000093, 0.000092, 0.000092, 0.000092, 0.000091, 0.000091, 0.000090, 0.000090, 0.000089, 0.000089, 0.000088, 0.000088, 0.000087, 0.000087, 0.000087, 0.000086, 0.000086, 0.000085, 0.000085, 0.000084, 0.000084, 0.000084, 0.000083, 0.000083, 0.000082, 0.000082, 0.000081, 0.000081, 0.000081, 0.000080, 0.000080, 0.000079, 0.000079, 0.000079, 0.000078, 0.000078, 0.000077, 0.000077, 0.000077, 0.000076, 0.000076, 0.000075, 0.000075, 0.000075, 0.000074, 0.000074, 0.000074, 0.000073, 0.000073, 0.000072, 0.000072, 0.000072, 0.000071, 0.000071, 0.000071, 0.000070, 0.000070, 0.000069, 0.000069, 0.000069, 0.000068, 0.000068, 0.000068, 0.000067, 0.000067, 0.000067, 0.000066, 0.000066, 0.000066, 0.000065, 0.000065, 0.000065, 0.000064, 0.000064, 0.000064, 0.000063, 0.000063, 0.000063, 0.000062, 0.000062, 0.000062, 0.000061, 0.000061, 0.000061, 0.000060, 0.000060, 0.000060, 0.000060, 0.000059, 0.000059, 0.000059, 0.000058, 0.000058, 0.000058, 0.000057, 0.000057, 0.000057, 0.000057, 0.000056, 0.000056, 0.000056, 0.000055, 0.000055, 0.000055, 0.000055, 0.000054, 0.000054, 0.000054, 0.000053, 0.000053, 0.000053, 0.000053, 0.000052, 0.000052, 0.000052, 0.000051, 0.000051, 0.000051, 0.000051, 0.000050, 0.000050, 0.000050, 0.000050, 0.000049, 0.000049, 0.000049, 0.000049, 0.000048, 0.000048, 0.000048, 0.000048, 0.000047, 0.000047, 0.000047, 0.000047, 0.000046, 0.000046, 0.000046, 0.000046, 0.000045, 0.000045, 0.000045, 0.000045, 0.000044, 0.000044, 0.000044, 0.000044, 0.000044, 0.000043, 0.000043, 0.000043, 0.000043, 0.000042, 0.000042, 0.000042, 0.000042, 0.000042, 0.000041, 0.000041, 0.000041, 0.000041, 0.000040, 0.000040, 0.000040, 0.000040, 0.000040, 0.000039, 0.000039, 0.000039, 0.000039, 0.000039, 0.000038, 0.000038, 0.000038, 0.000038, 0.000038, 0.000037, 0.000037, 0.000037, 0.000037, 0.000037, 0.000036, 0.000036, 0.000036, 0.000036, 0.000036, 0.000035, 0.000035, 0.000035, 0.000035, 0.000035, 0.000034, 0.000034, 0.000034, 0.000034, 0.000034, 0.000034, 0.000033, 0.000033, 0.000033, 0.000033, 0.000033, 0.000033, 0.000032, 0.000032, 0.000032, 0.000032, 0.000032, 0.000031, 0.000031, 0.000031, 0.000031, 0.000031, 0.000031, 0.000030, 0.000030, 0.000030, 0.000030, 0.000030, 0.000030, 0.000030, 0.000029, 0.000029, 0.000029, 0.000029, 0.000029, 0.000029, 0.000028, 0.000028, 0.000028, 0.000028, 0.000028, 0.000028, 0.000028, 0.000027, 0.000027, 0.000027, 0.000027, 0.000027, 0.000027, 0.000027, 0.000026, 0.000026, 0.000026, 0.000026, 0.000026, 0.000026, 0.000026, 0.000025, 0.000025, 0.000025, 0.000025, 0.000025, 0.000025, 0.000025, 0.000024, 0.000024, 0.000024, 0.000024, 0.000024, 0.000024, 0.000024, 0.000024, 0.000023, 0.000023, 0.000023, 0.000023, 0.000023, 0.000023, 0.000023, 0.000023, 0.000022, 0.000022, 0.000022, 0.000022, 0.000022, 0.000022, 0.000022, 0.000022, 0.000021, 0.000021, 0.000021, 0.000021, 0.000021, 0.000021, 0.000021, 0.000021, 0.000021, 0.000020, 0.000020, 0.000020, 0.000020, 0.000020, 0.000020, 0.000020, 0.000020, 0.000020, 0.000019, 0.000019, 0.000019, 0.000019, 0.000019, 0.000019, 0.000019, 0.000019, 0.000019, 0.000019, 0.000018, 0.000018, 0.000018, 0.000018, 0.000018, 0.000018, 0.000018, 0.000018, 0.000018, 0.000018, 0.000017, 0.000017, 0.000017, 0.000017, 0.000017, 0.000017, 0.000017, 0.000017, 0.000017, 0.000017, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000016, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000015, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000014, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000013, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000011, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000010, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000009, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000008, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000007, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000006, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000005, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000004, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000003, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000002, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001 }; #define MOD(a, b) (((b) + (a) % (b)) % (b)) #define GET(buf, M, N, i, j) (buf[MOD(i, M) * N + MOD(j, N)]) #define SIGN(a) ((a) < 0 ? -1 : ((a) > 0 ? 1 : 0)) typedef struct { double data[2]; } double2; /* conquier phase of merge sort algorithm */ static int merge(double2* left, int nl, double2* right, int nr, int idx, double2* tmp) { int kl, kr, k; int i; /* number of inversions in bubble sort */ kl = 0; kr = 0; i = 0; for (k = 0; k < nl + nr; ++k) if (kr == nr || (kl < nl && (left[kl].data[idx] < right[kr].data[idx] || (left[kl].data[idx] == right[kr].data[idx] && left[kl].data[1-idx] <= right[kr].data[1-idx])))) { tmp[k].data[0] = left[kl].data[0]; tmp[k].data[1] = left[kl].data[1]; ++kl; } else { tmp[k].data[0] = right[kr].data[0]; tmp[k].data[1] = right[kr].data[1]; ++kr; i += nl - kl; } for (k = 0; k < nl + nr; ++k) { left[k].data[0] = tmp[k].data[0]; left[k].data[1] = tmp[k].data[1]; } return i; } /* merge sort algorithm (divide phase) return number of swaps that a bubble sort would have done */ static int merge_sort(double2* buf, int n, int idx, double2* tmp) { int m; int i, j; if (n <= 1) return 0; m = n / 2; i = merge_sort(buf, m, idx, tmp); j = merge_sort(buf + m, n - m, idx, tmp); return i + j + merge(buf, m, buf + m, n - m, idx, tmp); } /* Compute Kendall-tau coefficient in O(n log n) (not accounting for ties) */ static double2 kendalltau_noties(double2* buf, long n) { double2* buf1; double2* buf2; double2* tmp; double2 tau_z; long n0; double v; int disc; /* number of discordant pairs */ int conc; /* number of concordant pairs */ buf1 = malloc(n * sizeof(double2)); buf1 = memcpy(buf1, buf, n * sizeof(double2)); buf2 = malloc(n * sizeof(double2)); buf2 = memcpy(buf2, buf, n * sizeof(double2)); tmp = malloc(n * sizeof(double2)); merge_sort(buf1, n, 0, tmp); merge_sort(buf2, n, 1, tmp); n0 = n * (n - 1) / 2; /* number of pairs */ v = n * (n - 1) * (2 * n + 5) / 2; disc = merge_sort(buf1, n, 1, tmp); conc = n0 - disc; tau_z.data[0] = (conc - disc) / (double) n0; tau_z.data[1] = 3 * (conc - disc) / sqrt(v); free(buf1); free(buf2); free(tmp); return tau_z; } /* Compute Kendall-tau coefficient in O(n log n) (accounting for ties) */ static double2 kendalltau(double2* buf, long n) { double2* buf1; double2* buf2; double2* tmp; double2 tau_z; long n0, n1, n2, n3, t; long v0, v1, v2, v11, v22; double v; int disc; /* number of discordant pairs */ int conc; /* number of concordant pairs */ int k; buf1 = malloc(n * sizeof(double2)); buf1 = memcpy(buf1, buf, n * sizeof(double2)); buf2 = malloc(n * sizeof(double2)); buf2 = memcpy(buf2, buf, n * sizeof(double2)); tmp = malloc(n * sizeof(double2)); merge_sort(buf1, n, 0, tmp); merge_sort(buf2, n, 1, tmp); n0 = n * (n - 1) / 2; /* number of pairs */ v0 = n * (n - 1) * (2 * n + 5); n1 = 0; /* pair of ties wrt first list */ n2 = 0; /* pair of ties wrt second list */ n3 = 0; /* pair of ties wrt both list */ v1 = 0; v2 = 0; v11 = 0; v22 = 0; t = 1; for (k = 0; k < n - 1; ++k) if (buf1[k].data[0] == buf1[k+1].data[0]) ++t; else { n1 += t * (t - 1) / 2; v1 += t * (t - 1) * (2 * t + 5); v11 += t * (t - 1) * (t - 2); t = 1; } n1 += t * (t - 1) / 2; v1 += t * (t - 1) * (2 * t + 5); v11 += t * (t - 1) * (t - 2); t = 1; for (k = 0; k < n - 1; ++k) if (buf2[k].data[1] == buf2[k+1].data[1]) ++t; else { n2 += t * (t - 1) / 2; v2 += t * (t - 1) * (2 * t + 5); v22 += t * (t - 1) * (t - 2); t = 1; } n2 += t * (t - 1) / 2; v2 += t * (t - 1) * (2 * t + 5); v22 += t * (t - 1) * (t - 2); t = 1; for (k = 0; k < n - 1; ++k) { if (buf2[k].data[0] == buf2[k+1].data[0] && buf2[k].data[1] == buf2[k+1].data[1]) ++t; else { n3 += t * (t - 1) / 2; t = 1; } } n3 += t * (t - 1) / 2; v = (v0 - v1 - v2) / 18.0 + n1 * n2 / (double) n0 + v11 * v22 / (9.0 * n * (n - 1) * (n - 2)); disc = merge_sort(buf1, n, 1, tmp); conc = n0 - n1 - n2 + n3 - disc; tau_z.data[0] = (conc - disc) / sqrt((n0 - n1) * (n0 - n2)); tau_z.data[1] = (conc - disc) / sqrt(v); free(buf1); free(buf2); free(tmp); return tau_z; } /* Compute Kendall-tau coefficient in O(n^2) (not accounting for ties) */ static double2 kendalltau_naive_noties(double2* buf, long n) { int i, j; double2 tau_z; long n0; double v; n0 = n * (n - 1) / 2; v = n * (n - 1) * (2 * n + 5) / 2; tau_z.data[0] = 0; for (i = 1; i < n; ++i) for (j = 0; j < i; ++j) tau_z.data[0] += SIGN(buf[i].data[0] - buf[j].data[0]) * SIGN(buf[i].data[1] - buf[j].data[1]); tau_z.data[1] = 3 * tau_z.data[0] / sqrt(v); tau_z.data[0] /= n0; return tau_z; } /* Compute Kendall-tau coefficient in O(n^2) (accounting for ties) */ static double2 kendalltau_naive(double2* buf, long n) { int i, j, k; double2 tau_z; double2* buf1; double2* buf2; double2* tmp; long n0, n1, n2, t; long v0, v1, v2, v11, v22; double v; buf1 = malloc(n * sizeof(double2)); buf1 = memcpy(buf1, buf, n * sizeof(double2)); buf2 = malloc(n * sizeof(double2)); buf2 = memcpy(buf2, buf, n * sizeof(double2)); tmp = malloc(n * sizeof(double2)); merge_sort(buf1, n, 0, tmp); merge_sort(buf2, n, 1, tmp); n0 = n * (n - 1) / 2; /* number of pairs */ v0 = n * (n - 1) * (2 * n + 5); n1 = 0; /* pair of ties wrt first list */ n2 = 0; /* pair of ties wrt second list */ v1 = 0; v2 = 0; v11 = 0; v22 = 0; t = 1; for (k = 0; k < n - 1; ++k) if (buf1[k].data[0] == buf1[k+1].data[0]) ++t; else { n1 += t * (t - 1) / 2; v1 += t * (t - 1) * (2 * t + 5); v11 += t * (t - 1) * (t - 2); t = 1; } n1 += t * (t - 1) / 2; v1 += t * (t - 1) * (2 * t + 5); v11 += t * (t - 1) * (t - 2); t = 1; for (k = 0; k < n - 1; ++k) if (buf2[k].data[1] == buf2[k+1].data[1]) ++t; else { n2 += t * (t - 1) / 2; v2 += t * (t - 1) * (2 * t + 5); v22 += t * (t - 1) * (t - 2); t = 1; } n2 += t * (t - 1) / 2; v2 += t * (t - 1) * (2 * t + 5); v22 += t * (t - 1) * (t - 2); v = (v0 - v1 - v2) / 18.0 + n1 * n2 / (double) n0 + v11 * v22 / (9.0 * n * (n - 1) * (n - 2)); tau_z.data[0] = 0; for (i = 1; i < n; ++i) for (j = 0; j < i; ++j) tau_z.data[0] += SIGN(buf[i].data[0] - buf[j].data[0]) * SIGN(buf[i].data[1] - buf[j].data[1]); tau_z.data[1] = tau_z.data[0] / sqrt(v); tau_z.data[0] /= sqrt((n0 - n1) * (n0 - n2)); free(buf1); free(buf2); return tau_z; } /* Get p-value for 2sided test on z ~ N(0, 1) */ static double pvalue_2sided_from_z(double z) { if (isnan(z)) return NAN; z = fabs(z); if (z > normpvalues_2sided_max) return 0; else return normpvalues_2sided[(int) roundf((normpvalues_2sided_size-1) * z / normpvalues_2sided_max)]; } /* Compute tau on non-overlapping moving windows */ static int core(double* ima, double* ima_tau, double* ima_pvalue, int M, int N, int W, int dx, int dy, double2 (*kendalltau_func)(double2*, long)) { int* mask; double2* buf; double2 tau_z; double pvalue; int ij, i, j, k, l; long s; buf = malloc(W * W * sizeof(double2)); for (k = 0; k < M*N; ++k) ima_tau[k] = NAN; if (ima_pvalue) ima_pvalue = memcpy(ima_pvalue, ima_tau, M*N * sizeof(double)); mask = calloc(W * W, sizeof(int)); for (k = 0; k < W; ++k) for (l = 0; l < W; ++l) if (!GET(mask, W, W, k, l) && !GET(mask, W, W, k + dx, l + dy)) { GET(mask, W, W, k, l) = 1; GET(mask, W, W, k + dx, l + dy) = 2; } /*#pragma omp parallel default(shared) private(ij, i, j, k, l, s, tau_z, pvalue) */ { /*# pragma omp for schedule(dynamic) nowait*/ for (ij = 0; ij < (M / W) * (N / W); ++ij) { i = W * (ij / (N / W)); j = W * (ij % (N / W)); s = 0; for (k = 0; k < W; ++k) for (l = 0; l < W; ++l) if (GET(mask, W, W, k, l) == 1) { buf[s].data[0] = GET(ima, M, N, i + k, j + l); buf[s].data[1] = GET(ima, M, N, i + k + dx, j + l + dy); ++s; } tau_z = kendalltau_func(buf, s); for (k = 0; k < W; ++k) for (l = 0; l < W; ++l) GET(ima_tau, M, N, i + k, j + l) = tau_z.data[0]; if (ima_pvalue) { pvalue = pvalue_2sided_from_z(tau_z.data[1]); for (k = 0; k < W; ++k) for (l = 0; l < W; ++l) GET(ima_pvalue, M, N, i + k, j + l) = pvalue; } } } free(buf); free(mask); return 0; } #define isScalarValue(a) (mxIsNumeric(a) && !mxIsComplex(a) && mxGetM(a) == 1 && mxGetN(a) == 1) static void usage() { char str[1024]; sprintf(str, "usage: [tau, pvalue] = kendalltau(image, window_size, dx, dy,\n" \ " ['fast' | 'noties' | 'naive' | 'naive-noties'])\n"); mexErrMsgTxt(str); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double* ima; double* ima_tau; double* ima_pvalue; int W, dx, dy; int M, N; const size_t* sizes; double2 (*kendalltau_func)(double2*, long) = kendalltau; if (nrhs < 4 || nrhs > 5 || nlhs > 2) { usage(); return; } if (mxIsDouble(prhs[0]) != 1 || mxIsNumeric(prhs[0]) != 1 || mxGetNumberOfDimensions(prhs[0]) != 2 || !isScalarValue(prhs[1]) || !isScalarValue(prhs[2]) || !isScalarValue(prhs[3]) || (nrhs >= 5 && (!mxIsChar(prhs[4]) || mxGetM(prhs[4]) != 1))) { usage(); return; } if (nrhs >= 5) { int type_len = mxGetM(prhs[4]) * mxGetN(prhs[4]) + 1; char* type = mxCalloc(type_len, sizeof(char)); mxGetString(prhs[4], type, type_len); if (!strcmp(type, "fast")) kendalltau_func = kendalltau; else if (!strcmp(type, "noties")) kendalltau_func = kendalltau_noties; else if (!strcmp(type, "naive")) kendalltau_func = kendalltau_naive; else if (!strcmp(type, "naive-noties")) kendalltau_func = kendalltau_naive_noties; else { usage(); return; } }; sizes = mxGetDimensions(prhs[0]); M = sizes[1]; N = sizes[0]; ima = mxGetData(prhs[0]); W = (int) *mxGetPr(prhs[1]); dx = (int) *mxGetPr(prhs[2]); dy = (int) *mxGetPr(prhs[3]); plhs[0] = mxCreateNumericArray(2, sizes, mxDOUBLE_CLASS, mxREAL); ima_tau = mxGetData(plhs[0]); if (nlhs >= 2) { plhs[1] = mxCreateNumericArray(2, sizes, mxDOUBLE_CLASS, mxREAL); ima_pvalue = mxGetData(plhs[1]); } else ima_pvalue = NULL; switch (core(ima, ima_tau, ima_pvalue, M, N, W, dx, dy, kendalltau_func)) { case 0: break; ;; default: mexErrMsgTxt("Unexpected error"); ;; } }
partition.h
/** * Author: Kartik Lakhotia Sourav Pati * Email id: klakhoti@usc.edu spati@usc.edu * Date: 27-Feb-2018 * * This code implements work optimized propagation blocking with * transposed bin graph to reduce cache misses in scatter */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <omp.h> #include <math.h> #include "../include/graph.h" //#define MAX_UINT 0xffffffffffffffff #if defined (HUGE_EDGE) || defined (HUGE_VERTEX) #define MAX_UINT 0xffffffffffffffff #else #define MAX_UINT 0xffffffff #endif //#define MAX_NEG 0x80000000 //#define MAX_POS 0x7fffffff //#define MSB_ROT 31 #ifdef HUGE_VERTEX #define MAX_NEG 0x8000000000000000 #define MAX_POS 0x7fffffffffffffff #define MSB_ROT 63 #else #define MAX_NEG 0x80000000 #define MAX_POS 0x7fffffff #define MSB_ROT 31 #endif ////////////////////////////////////////// //partition centric programming variables ////////////////////////////////////////// extern intV binWidth; extern unsigned int binOffsetBits; extern intV NUM_BINS; ////////////////////////////////////////// //////// pre-processing functions //////// ////////////////////////////////////////// //compute equal sized (vertex/edge) partitions template<class graph> void partition(partitionData* TD, graph* G) { intV numVertexPerBin = binWidth; G->activeScatter = new intV [G->numBins](); G->activeGather = new intV [G->numBins](); G->partListPtr = 0; #pragma omp parallel for for (intV i=0; i<G->numBins; i++) { TD[i].tid = i; TD[i].PNG = NULL; TD[i].IPG = NULL; //for asynch processing TD[i].isDense = false; TD[i].startVertex = i*numVertexPerBin; TD[i].endVertex = (i+1)*numVertexPerBin; TD[i].endVertex = (TD[i].endVertex > G->numVertex) ? G->numVertex : TD[i].endVertex; TD[i].frontier = new intV [TD[i].endVertex - TD[i].startVertex]; TD[i].frontierSize = 0; TD[i].activeEdges = 0; TD[i].totalEdges = G->VI[TD[i].endVertex] - G->VI[TD[i].startVertex]; TD[i].binListPtr = 0; #ifdef DENSE G->activeScatter[i] = i; G->activeGather[i] = i; G->partListPtr = G->numBins; TD[i].binListPtr = G->numBins; #endif } } //transpose the graph to sort on destination template<class graph> void transposePartition(graph* G, partitionData* TD, intE* updateBinAddrOffset, intE* destIdBinAddrOffset) { // graph* G = TD->G; partitionGraph* GSort = new partitionGraph [1]; intV currBin, prevBin; GSort->numVertex = G->numBins; GSort->VI = new intE [GSort->numVertex+1](); //for intra partition asynch processing partitionGraph* IGSort = new partitionGraph [1]; IGSort->numVertex = TD->endVertex - TD->startVertex; IGSort->VI = new intE [IGSort->numVertex+1](); for (intV i=TD->startVertex; i<TD->endVertex; i++) { prevBin = G->numBins+1; intV intraPartId = i - TD->startVertex; for (intE j=G->VI[i]; j<G->VI[i+1]; j++) { currBin = (G->EI[j] >> binOffsetBits); destIdBinAddrOffset[currBin]++; if (currBin == prevBin) continue; GSort->VI[currBin+1]++; prevBin = currBin; IGSort->VI[intraPartId+1] += (currBin == TD->tid); //for intra partition asynch processing } } for (intV i=0; i<G->numBins; i++) updateBinAddrOffset[i] = GSort->VI[i+1]; for (intV i=0; i<GSort->numVertex; i++) GSort->VI[i+1] += GSort->VI[i]; GSort->numEdges = GSort->VI[GSort->numVertex]; GSort->EI = new intV [GSort->numEdges]; intE* binOffset = new intE [G->numBins](); //for intra partition asynch processing for (intV i=0; i<IGSort->numVertex; i++) IGSort->VI[i+1] += IGSort->VI[i]; IGSort->numEdges = IGSort->VI[IGSort->numVertex]; IGSort->EI = new intV [IGSort->numEdges]; #ifdef WEIGHTED IGSort->EW = new intV [IGSort->numEdges]; #endif intE IGoffset = 0; for (intV i=TD->startVertex; i<TD->endVertex; i++) { prevBin = G->numBins; for (intE j=G->VI[i]; j<G->VI[i+1]; j++) { currBin = (G->EI[j] >> binOffsetBits); if (currBin == prevBin) continue; GSort->EI[GSort->VI[currBin] + (binOffset[currBin]++)] = i; if (currBin == TD->tid) //for intra partition asynch processing { #ifdef WEIGHTED IGSort->EW[IGoffset] = G->EW[j]; #endif IGSort->EI[IGoffset++] = G->EI[j]; } prevBin = currBin; } } TD->PNG = GSort; TD->IPG = IGSort; //for intra partition asynch processing delete[] binOffset; } template<class graph> #ifdef WEIGHTED void writeDestIds(graph* G, partitionData* TD, intV** destIdBins, unsigned int** weightBins, intE* destIdBinPointers) #else void writeDestIds(graph* G, partitionData* TD, intV** destIdBins, intE* destIdBinPointers) #endif { intV destId = 0; intV destBin = 0; intV prevBin = 0; #ifdef DEBUGL2 for (intV i=0; i<G->numBins; i++) assert(destIdBinPointers[i] == 0); #endif for (intV i=TD->startVertex; i<TD->endVertex; i++) { prevBin = G->numBins; for (intE j=G->VI[i]; j<G->VI[i+1]; j++) { destId = G->EI[j]; destBin = (destId >> binOffsetBits); if (destBin != prevBin) { destId |= MAX_NEG; prevBin = destBin; } #ifdef WEIGHTED weightBins[destBin][destIdBinPointers[destBin]] = G->EW[j]; #endif destIdBins[destBin][destIdBinPointers[destBin]++] = destId; } } for (intV i=0; i<G->numBins; i++) destIdBinPointers[i] = 0; } ////////////////////////////////////////// //////////// memory allocation /////////// ////////////////////////////////////////// //allocate BIN x BIN space for offsets, pointers template <class T> T** allocateBinMat (intV numRows, intV numCols) { T** pointerMat; pointerMat = new T* [numRows]; for (intV i=0; i<numRows; i++) pointerMat[i] = new T [numCols](); return pointerMat; } //allocate BIN x BIN space for pointers template <class T> T*** allocateBinMatPtr (intV numRows, intV numCols) { T*** pointerMat; pointerMat = new T** [numRows]; for (intV i=0; i<numRows; i++) pointerMat[i] = new T* [numCols]; return pointerMat; } ////////////////////////////////////////// ////////////free the memory ////////////// ////////////////////////////////////////// template <class T> void freeMat (T** mat, intV numRows) { for (intV i=0; i<numRows; i++) delete[] mat[i]; delete[] mat; } template <class T> void freeMatPtr (T*** mat, intV numRows, intV numCols) { for (intV i=0; i<numRows; i++) for (intV j=0; j<numCols; j++) delete[] mat[i][j]; for (intV i=0; i<numRows; i++) delete[] mat[i]; delete[] mat; }
ab-totient-omp-8.c
// Distributed and parallel technologies, Andrew Beveridge, 03/03/2014 // To Compile: gcc -Wall -O -o ab-totient-omp -fopenmp ab-totient-omp.c // To Run / Time: /usr/bin/time -v ./ab-totient-omp range_start range_end #include <stdio.h> #include <omp.h> /* When input is a prime number, the totient is simply the prime number - 1. Totient is always even (except for 1). If n is a positive integer, then φ(n) is the number of integers k in the range 1 ≤ k ≤ n for which gcd(n, k) = 1 */ long getTotient (long number) { long result = number; // Check every prime number below the square root for divisibility if(number % 2 == 0){ result -= result / 2; do number /= 2; while(number %2 == 0); } // Primitive replacement for a list of primes, looping through every odd number long prime; for(prime = 3; prime * prime <= number; prime += 2){ if(number %prime == 0){ result -= result / prime; do number /= prime; while(number % prime == 0); } } // Last common factor if(number > 1) result -= result / number; // Return the result. return result; } // Main method. int main(int argc, char ** argv) { // Load inputs long lower, upper; sscanf(argv[1], "%ld", &lower); sscanf(argv[2], "%ld", &upper); int i; long result = 0.0; // We know the answer if it's 1; no need to execute the function if(lower == 1) { result = 1.0; lower = 2; } #pragma omp parallel for default(shared) private(i) schedule(auto) reduction(+:result) num_threads(8) // Sum all totients in the specified range for (i = lower; i <= upper; i++) { result = result + getTotient(i); } // Print the result printf("Sum of Totients between [%ld..%ld] is %ld \n", lower, upper, result); // A-OK! return 0; }
jacobi_omp.c
/* * Copyright (c) 2008, BSC (Barcelon Supercomputing Center) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 BSC ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <math.h> #include <time.h> #define NB 32 #define B 256 #define FALSE (0) #define TRUE (1) typedef double fp_type; typedef fp_type *vin; typedef fp_type *vout; typedef fp_type *bin; typedef fp_type *binout; fp_type *A[NB][NB]; fp_type *A_new[NB][NB]; fp_type *tmp[NB][NB]; void alloc_and_genmat() { int init_val, i, j, ii, jj; fp_type *p, *p_new; init_val = 1325; for (ii = 0; ii < NB; ii++) { for (jj = 0; jj < NB; jj++) { A[ii][jj] = (fp_type *)malloc(B * B * sizeof(fp_type)); A_new[ii][jj] = (fp_type *)malloc(B * B * sizeof(fp_type)); tmp[ii][jj] = (fp_type *)malloc(B * B * sizeof(fp_type)); if (A[ii][jj] == NULL || A_new[ii][jj] == NULL || tmp[ii][jj] == NULL) { printf("Out of memory\n"); exit(1); } p = A[ii][jj]; p_new = A_new[ii][jj]; for (i = 0; i < B; i++) { for (j = 0; j < B; j++) { init_val = (3125 * init_val) % 65536; (*p) = (fp_type)((init_val - 32768.0) / 16384.0); (*p_new) = (*p); p++; p_new++; } } } } } long usecs(void) { struct timeval t; gettimeofday(&t, NULL); return t.tv_sec * 1000000 + t.tv_usec; } void clear(vout v) { int i, j, k; for (i = 0; i < B; i++) v[i] = (fp_type)0.0; } void getlastrow(bin A, vout v) { int j; for (j = 0; j < B; j++) v[j] = A[(B - 1) * B + j]; } void getlastcol(bin A, vout v) { int i; for (i = 0; i < B; i++) v[i] = A[i * B + B - 1]; } void getfirstrow(bin A, vout v) { int j; for (j = 0; j < B; j++) v[j] = A[0 * B + j]; } void getfirstcol(bin A, vout v) { int i; for (i = 0; i < B; i++) v[i] = A[i * B + 0]; } void jacobi(vin lefthalo, vin tophalo, vin righthalo, vin bottomhalo, bin A, binout A_new) { int i, j; fp_type tmp; fp_type left, top, right, bottom; for (i = 0; (i < B); i++) { for (j = 0; j < B; j++) { tmp = A[i * B + j]; left = (j == 0 ? lefthalo[j] : A[i * B + j - 1]); top = (i == 0 ? tophalo[i] : A[(i - 1) * B + j]); right = (j == B - 1 ? righthalo[i] : A[i * B + j + 1]); bottom = (i == B - 1 ? bottomhalo[i] : A[(i + 1) * B + j]); A_new[i * B + j] = 0.2 * (A[i * B + j] + left + top + right + bottom); } } } double maxdelta() { double dmax = -__DBL_MAX__; int ii, jj, i, j; #pragma omp parallel for schedule(static) reduction(max: dmax) for (ii = 0; ii < NB; ii++) { for (jj = 0; jj < NB; jj++) { for (i = 0; (i < B); i++) { for (j = 0; j < B; j++) { double diff = fabs(A_new[ii][jj][i * B + j] - A[ii][jj][i * B + j]); if(diff > dmax) dmax = diff; } } } } return dmax; } void compute(int niters) { int iters; int ii, jj; fp_type lefthalo[B], tophalo[B], righthalo[B], bottomhalo[B]; double delta = 2.0; double epsilon = 1e-7; iters = 0; // for (iters = 0; iters < niters; iters++) while(iters < niters) { ++iters; #pragma omp parallel \ private(ii, jj, lefthalo, tophalo, righthalo, bottomhalo) \ shared(A, A_new) { #pragma omp for schedule(static) for (ii = 0; ii < NB; ii++) { for (jj = 0; jj < NB; jj++) { if (ii > 0) getlastrow(A[ii - 1][jj], tophalo); else clear(tophalo); if (jj > 0) getlastcol(A[ii][jj - 1], lefthalo); else clear(lefthalo); if (ii < NB - 1) getfirstrow(A[ii + 1][jj], bottomhalo); else clear(bottomhalo); if (jj < NB - 1) getfirstcol(A[ii][jj + 1], righthalo); else clear(lefthalo); jacobi(lefthalo, tophalo, righthalo, bottomhalo, A[ii][jj], A_new[ii][jj]); } // jj } // ii } // end parallel delta = maxdelta(); printf("iteration %d: delta = %e\n", iters, delta); // yes, this is an inefficient copy // however, the library version requires you to do a copy in this way // on all of the component parts to avoid segmentation fault #pragma omp parallel for schedule(static) shared(A, A_new) for(int i = 0; i < NB; ++i) { for(int j = 0; j < NB; ++j) { for(int k = 0; k < B; ++k) for(int l = 0; l < B; ++l) A[i][j][k * B + l] = A_new[i][j][k * B + l]; } } } // iter } int main(int argc, char *argv[]) { int niters; // pp_time_t tm; // memset( &tm, 0, sizeof(tm) ); struct timespec start, end; if (argc > 1) { niters = atoi(argv[1]); } else niters = 1; alloc_and_genmat(); clock_gettime(CLOCK_MONOTONIC, &start); compute(niters); clock_gettime(CLOCK_MONOTONIC, &end); double time_taken = (end.tv_sec - start.tv_sec) * 1e9; time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9; printf("Running time = %g %s\n", time_taken, "s"); /* FILE *outFile; outFile = fopen("./jacobi_omp_values.txt", "w"); if (outFile == NULL) { fprintf(stderr, "Error writing to file\n"); } else { int ii, jj, i, j; for (ii = 0; ii < NB; ++ii) for (jj = 0; jj < NB; ++jj) for (i = 0; i < B; ++i) for (j = 0; j < B; ++j) fprintf(outFile, "%.15f\n", A[ii][jj][i * B + j]); fclose(outFile); } */ return 0; }
main.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <time.h> #include "omp.h" #include "functions.h" int main (int argc, char **argv) { int Nthreads = 1; omp_set_num_threads(Nthreads); //seed value for the randomizer double seed = clock(); //this will make your program run differently everytime //double seed = 0; //uncomment this and your program will behave the same everytime it's run srand(seed); //declare storage for an ElGamal cryptosytem unsigned int p, g, h, x; //begin with rank 0 getting user's input unsigned int n; printf("Enter a number of bits: "); fflush(stdout); char status = scanf("%u",&n); //make sure the input makes sense if ((n<9)||(n>31)) {//Updated bounds. 8 is no good (need to encode chars) printf("Unsupported bit size.\n"); return 0; } printf("\n"); //setup an ElGamal cryptosystem setupElGamal(n,&p,&g,&h,&x); int bufferSize = 1024; unsigned char *message = (unsigned char *) malloc(bufferSize*sizeof(unsigned char)); //populate the string with a message strcpy(message, "Hello, this is the message as a string."); printf("Message = \"%s\"\n", message); /* Q1.1 Finish this line */ unsigned int charsPerInt = n/8; padString(message, charsPerInt); printf("Padded Message = \"%s\"\n", message); unsigned int Nchars = strlen(message); unsigned int Nints = strlen(message)/charsPerInt; //storage for message as elements of Z_p unsigned int *Zmessage = (unsigned int *) malloc(Nints*sizeof(unsigned int)); //storage for extra encryption coefficient unsigned int *a = (unsigned int *) malloc(Nints*sizeof(unsigned int)); // cast the string into an unsigned int array convertStringToZ(message, Nchars, Zmessage, Nints); //Encrypt the Zmessage with the ElGamal cyrptographic system ElGamalEncrypt(Zmessage,a,Nints,p,g,h); printf("The encrypted text is: "); for (unsigned int i=0;i<Nints;i++) { printf("(%u,%u) ", Zmessage[i], a[i]); } printf("]\n"); //Decrypt the Zmessage with the ElGamal cyrptographic system ElGamalDecrypt(Zmessage,a,Nints,p,x); convertZToString(Zmessage, Nints, message, Nchars); printf("Decrypted Message = \"%s\"\n", message); printf("\n"); //Suppose we don't know the secret key. Use OpenMP threads to try and find it in parallel printf("Using %d OpenMP threads to find the secret key...\n", Nthreads); /* Q2.3 Parallelize this loop with OpenMP */ int patsExit = 0; double startTime = omp_get_wtime(); #pragma omp parallel for shared(patsExit) for (unsigned int i=0;i<p-1;i++) { if (modExp(g,i+1,p)==h) { printf("Secret key found! x = %u \n", i+1); patsExit =1; } //end if (patsExit == 1){ i = p-1; //should end the for loop } } double endTime = omp_get_wtime(); double totalTime = endTime-startTime; double work = (double) p; double throughput = work/totalTime; printf("Searching all keys took %g seconds, throughput was %g values tested per second.\n", totalTime, throughput); return 0; }
GB_unop__asin_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__asin_fc64_fc64) // op(A') function: GB (_unop_tran__asin_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = casin (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = casin (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = casin (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_ASIN || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__asin_fc64_fc64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = casin (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = casin (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__asin_fc64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
omp_for_lastprivate.c
// RUN: %libomp-compile-and-run // REQUIRES: !(abt && (clang || gcc)) #include <stdio.h> #include <math.h> #include "omp_testsuite.h" int sum0; #pragma omp threadprivate(sum0) int test_omp_for_lastprivate() { int sum = 0; int known_sum; int i0; i0 = -1; #pragma omp parallel { sum0 = 0; { /* Begin of orphaned block */ int i; #pragma omp for schedule(static,7) lastprivate(i0) for (i = 1; i <= LOOPCOUNT; i++) { sum0 = sum0 + i; i0 = i; } /* end of for */ } /* end of orphaned block */ #pragma omp critical { sum = sum + sum0; } /* end of critical */ } /* end of parallel */ known_sum = (LOOPCOUNT * (LOOPCOUNT + 1)) / 2; fprintf(stderr, "known_sum = %d , sum = %d\n",known_sum,sum); fprintf(stderr, "LOOPCOUNT = %d , i0 = %d\n",LOOPCOUNT,i0); return ((known_sum == sum) && (i0 == LOOPCOUNT)); } int main() { int i; int num_failed=0; for (i = 0; i < REPETITIONS; i++) { if(!test_omp_for_lastprivate()) { num_failed++; } } return num_failed; }
DemNets.c
#include "Python.h" #include "numpy/arrayobject.h" #include <fcntl.h> #include <math.h> #include <omp.h> #include <sys/param.h> #define VERSION "0.2" typedef struct Stack Stack; typedef struct Queue Queue; typedef struct Node Node; struct Node { Node *next; unsigned int i; double d; }; struct Queue { Node *first; Node *last; }; struct Stack { Stack *head; unsigned int i; }; int put(Queue *q, const unsigned int i, const double d) { Node *n; n = malloc(sizeof(Node)); if(!n) return 1; n->i = i; n->d = d; if(!q->first) { q->first = q->last = n; } else { q->last->next = n; q->last = n; } n->next = NULL; return 0; } int get(Queue *q, unsigned int *i, double *d) { Node *tmp; if(!q->first) return 1; *i = q->first->i; *d = q->first->d; tmp = q->first; q->first = q->first->next; free(tmp); return 0; } void GridAggregate(double *ug, double *vg, unsigned int *cg, const double *xb, const unsigned int xbn, const double *yb, const unsigned int ybn, const double *x, const double *y, const double *u, const double *v, const unsigned int n) { unsigned int i, k, l, lk, id, count; double xl, yl, usum, vsum; #pragma omp parallel for private(i,k,l,lk,id,count,xl,yl,usum,vsum) for(i = 0; i < xbn; i++) { lk = 0; id = i * ybn; for(k = 0; k < ybn; k++) { count = 0; usum = vsum = 0; for(l = lk; l < n; l++) { yl = y[l]; if(yl >= yb[k+1]) { lk = l; break; } xl = x[l]; if(xb[i] <= xl && xl < xb[i+1]) { usum += u[l]; vsum += v[l]; count++; } } if(count) { ug[id+k] = usum / count; vg[id+k] = vsum / count; cg[id+k] = count; } } } } void GridAggregateVar(double *ug, double *vg, const double *xb, const unsigned int xbn, const double *yb, const unsigned int ybn, const double *x, const double *y, const double *u, const double *v, const double *umean, const double *vmean, const unsigned int n) { unsigned int i, k, l, lk, id, count, minc; double xl, yl, um, vm, usum, vsum; minc = 5; // unbiased two-pass variance with minimum sample size minc #pragma omp parallel for private(i,k,l,lk,id,count,xl,yl,um,vm,usum,vsum) for(i = 0; i < xbn; i++) { lk = 0; id = i * ybn; for(k = 0; k < ybn; k++) { count = 0; usum = vsum = 0; um = umean[id+k]; vm = vmean[id+k]; for(l = lk; l < n; l++) { yl = y[l]; if(yl >= yb[k+1]) { lk = l; break; } xl = x[l]; if(xb[i] <= xl && xl < xb[i+1]) { usum += (u[l] - um) * (u[l] - um); vsum += (v[l] - vm) * (v[l] - vm); count++; } } if(count > minc) { count--; ug[id+k] = usum / count; vg[id+k] = vsum / count; } } } } void GridMaximum(double *zg, const double *xb, const unsigned int xbn, const double *yb, const unsigned int ybn, const double *x, const double *y, const double *z, const unsigned int n) { unsigned int i, k, l, lk, id; double xl, yl, zmax; #pragma omp parallel for private(i,k,l,lk,id,xl,yl,zmax) for(i = 0; i < xbn; i++) { lk = 0; id = i * ybn; for(k = 0; k < ybn; k++) { zmax = 0; for(l = lk; l < n; l++) { yl = y[l]; if(yl >= yb[k+1]) { lk = l; break; } xl = x[l]; if(xb[i] <= xl && xl < xb[i+1]) { if(z[l] > zmax) zmax = z[l]; } } zg[id+k] = zmax; } } } void Thinning(int *idx, const double *xb, const unsigned int xbn, const double *yb, const unsigned int ybn, const double *x, const double *y, const double *z, const unsigned int n) { unsigned int i, k, l, lk, lmin; double xl, yl, zmin; #pragma omp parallel for private(i,k,l,lk,xl,yl,zmin,lmin) for(i = 0; i < xbn; i++) { lk = 0; for(k = 0; k < ybn; k++) { zmin = 9E9; lmin = 0; for(l = lk; l < n; l++) { yl = y[l]; if(yl >= yb[k+1]) { lk = l; break; } xl = x[l]; if(xb[i] <= xl && xl < xb[i+1]) { if(z[l] < zmin) { zmin = z[l]; lmin = l; } } } idx[lmin] = 1; } } } static PyArrayObject * Simplicies(const unsigned int *tri, const unsigned int m, const unsigned int n) { PyArrayObject *net; npy_intp dim[1]; unsigned int i, j, k, l, o; unsigned int *lst[n], *e, ex; // node to simplicies map // alloc list of arrays for(i = 0; i < n; i++) { lst[i] = malloc(8 * sizeof(unsigned int)); if(!lst[i]) { PyErr_SetString(PyExc_MemoryError, "malloc of list of arrays failed."); return NULL; } lst[i][0] = 8; lst[i][1] = 2; } l = 0; for(i = 0; i < m; i++) { for(j = 0; j < 3; j++) { k = tri[i*3+j]; ex = 0; for(o = 2; o < lst[k][1]; o++) { if(lst[k][o] == i) { ex = 1; break; } } if(!ex) { lst[k][lst[k][1]++] = i; l++; } if(lst[k][0] < lst[k][1] + 2) { lst[k][0] = lst[k][1] + 4; lst[k] = realloc(lst[k], lst[k][0] * sizeof(unsigned int)); if(!lst[k]) { PyErr_SetString(PyExc_MemoryError, "realloc of array in list failed."); return NULL; } } } } // alloc numpy array dim[0] = l + n + 1; net = (PyArrayObject *) PyArray_ZEROS(1, dim, PyArray_UINT, 0); if(!net) { PyErr_SetString(PyExc_MemoryError, "..."); return NULL; } e = (unsigned int *) net->data; // store in compressed row format j = n + 1; for(i = 0; i < n; i++) { e[i] = j; for(k = 2; k < lst[i][1]; k++) { e[j++] = lst[i][k]; } free(lst[i]); } e[n] = j; return net; } static PyArrayObject * UpstreamNetwork(const unsigned int *spx, const unsigned int m) { PyArrayObject *net; npy_intp dim[1]; unsigned int i, j, k, l, o; unsigned int *lst[m], *e, ex, itr; // reverse facet flow network spx // alloc list of arrays for(i = 0; i < m; i++) { lst[i] = malloc(8 * sizeof(unsigned int)); if(!lst[i]) { PyErr_SetString(PyExc_MemoryError, "malloc of list of arrays failed."); return NULL; } lst[i][0] = 8; lst[i][1] = 2; } l = 0; for(i = 0; i < m; i++) { itr = i * 2; for(j = 0; j < 2; j++) { k = spx[itr + j]; if(k == m) continue; ex = 0; for(o = 2; o < lst[k][1]; o++) { if(lst[k][o] == i) { ex = 1; break; } } if(!ex) { lst[k][lst[k][1]++] = i; l++; } if(lst[k][0] < lst[k][1] + 2) { lst[k][0] = lst[k][1] + 4; lst[k] = realloc(lst[k], lst[k][0] * sizeof(unsigned int)); if(!lst[k]) { PyErr_SetString(PyExc_MemoryError, "realloc of array in list failed."); return NULL; } } } } // alloc numpy array dim[0] = l + m + 1; net = (PyArrayObject *) PyArray_ZEROS(1, dim, PyArray_UINT, 0); if(!net) { PyErr_SetString(PyExc_MemoryError, "..."); return NULL; } e = (unsigned int *) net->data; // store in compressed row format j = m + 1; for(i = 0; i < m; i++) { e[i] = j; for(k = 2; k < lst[i][1]; k++) { e[j++] = lst[i][k]; } free(lst[i]); } e[m] = j; return net; } unsigned int SimplexOfNodes(const unsigned int *net, const unsigned int a, const unsigned int b, const unsigned int x, const unsigned int m) { unsigned int i, k; // find the not-x simplex of two nodes a and b for(i = net[a]; i < net[a+1]; i++) for(k = net[b]; k < net[b+1]; k++) if(net[i] == net[k] && net[i] != x) return net[i]; return m; } unsigned int NodeOfSimplicies(const unsigned int *tri, const unsigned int a, const unsigned int b, const double *z) { int r; unsigned int i, k, p, q; double zmin; // get the lowest node j of two facets a and b p = a*3; q = b*3; zmin = 1E99; r = -1; for(i = 0; i < 3; i++) { for(k = 0; k < 3; k++) { if(tri[p+i] == tri[q+k]) { if(z[tri[p+i]] < zmin) { zmin = z[tri[p+i]]; r = tri[p+i]; } } } } if(r == -1) { PyErr_SetString(PyExc_IndexError, "facets are not neighbors .."); exit(EXIT_FAILURE); } return r; } double HeronsTriangle(double a, double b, double c) { double d; // return the area of a facet // ! a >= b >= c if(a < b) { d = b; b = a; a = d; } if(b < c) { d = c; c = b; b = d; } if(a < b) { d = b; b = a; a = d; } return sqrt((a+(b+c))*(c-(a-b))*(c+(a-b))*(a+(b-c))) / 4; } void FacetFlowThroughput(double *ltp, const unsigned int *spx, const double *spw, const double *spa, const unsigned int m) { double ltpi; unsigned int i, j, k, l; unsigned int *seen, *ideg, itr; Queue *que; // initialize seen = calloc(m, sizeof(unsigned int)); ideg = calloc(m, sizeof(unsigned int)); que = malloc(sizeof(Queue)); if(!que || !ideg || !seen) { PyErr_SetString(PyExc_MemoryError, "..."); exit(EXIT_FAILURE); } que->first = que->last = NULL; // get in-degree for(i = 0; i < m; i++) { itr = i * 2; for(j = 0; j < 2; j++) { k = itr + j; l = spx[k]; if(m > l) ideg[l]++; } } // start at facets without in-degree draining into l for(i = 0; i < m; i++) { if(!ideg[i]) { itr = i * 2; for(j = 0; j < 2; j++) { k = itr + j; l = spx[k]; ltp[k] = spa[k]; if(m > l) { if(put(que, l, ltp[k])) { PyErr_SetString(PyExc_MemoryError, "failed to fill queue .."); exit(EXIT_FAILURE); } } } } } // work the queue while(!get(que, &i, &ltpi)) { seen[i]++; itr = i * 2; ltp[itr] += ltpi; if(seen[i] == ideg[i]) { // we collected all input for node i ltpi = ltp[itr]; ltp[itr] = 0; for(j = 0; j < 2; j++) { k = itr + j; l = spx[k]; // link throughput ltp[k] = ltpi * spw[k] + spa[k]; if(m > l) { if(put(que, l, ltp[k])) { PyErr_SetString(PyExc_MemoryError, "failed to fill queue .."); exit(EXIT_FAILURE); } } } } } } void FacetFlowNetwork(unsigned int *spx, double *spw, double *spa, double *spd, double *phi, const unsigned int *net, const unsigned int *tri, const unsigned int m, const double *x, const double *y, const double *z) { int sgn; double du, dv, dw, a, b, c; double xx, yy, slp, frc; double dx, dy, dz, dn, s, t; double xa, xb, xc, ya, yb, yc; double aa, ab, ac, bb, bc; double phii, beta; unsigned int i, j; unsigned int u, v, w, q, p; for(i = 0; i < m; i++) { // at p, q we store the pos of children p = i * 2; q = i * 2 + 1; for(j = 0; j < 3; j++) { u = tri[i*3 + j]; v = tri[i*3 + (j+1)%3]; w = tri[i*3 + (j+2)%3]; // grad (dx,dy) of three point plane dz = ((x[w]-x[u])*(y[v]-y[u]) - (y[w]-y[u])*(x[v]-x[u])); dy = ((z[w]-z[u])*(x[v]-x[u]) - (x[w]-x[u])*(z[v]-z[u])) / dz; dx = ((y[w]-y[u])*(z[v]-z[u]) - (z[w]-z[u])*(y[v]-y[u])) / dz; // tri sides vs grad xa = x[w] - x[u]; ya = y[w] - y[u]; xb = x[v] - x[u]; yb = y[v] - y[u]; // dot products aa = xa*xa + ya*ya; ab = xa*xb + ya*yb; bb = xb*xb + yb*yb; dn = 1. / (aa*bb - ab*ab); for(sgn = -1; sgn <= 1; sgn += 2) { xc = sgn * dx; yc = sgn * dy; ac = xa*xc + ya*yc; bc = xb*xc + yb*yc; s = (bb*ac - ab*bc) * dn; t = (aa*bc - ab*ac) * dn; if(s >= 0 && t >= 0) { phii = atan2(dy, dx); phi[i] = phii; //phi[i] = sqrt(dx*dx + dy*dy + dz*dz); if(phii < 0) phii += M_PI; a = sqrt(xa*xa + ya*ya); b = sqrt(xb*xb + yb*yb); if(sgn > 0) { spx[p] = SimplexOfNodes(net, w, v, i, m); spx[q] = m; spw[p] = 1; spw[q] = 0; c = sqrt((x[v]-x[w])*(x[v]-x[w])+(y[v]-y[w])*(y[v]-y[w])); spa[p] = HeronsTriangle(a, b, c); spa[q] = 0; beta = atan2(y[w]-y[v], x[w]-x[v]); if(beta < 0) beta += M_PI; beta -= phii; if(beta > M_PI / 2) beta = M_PI - beta; spd[i] = c * fabs(sin(beta)); } else { slp = dy / dx; frc = (y[w] - y[v]) / (x[w] - x[v]); if(dx) { if(x[w] != x[v]) xx = (yb + x[u]*slp - x[v]*frc) / (slp - frc); else xx = x[w]; yy = (xx - x[u])*slp + y[u]; } else { xx = x[u]; yy = (xx - x[w])*frc + y[w]; } if(isinf(yy)) { fprintf(stderr, "flat triangle %i (u:%.2f v:%.2f w:%.2f)\n", i, z[u], z[v], z[w]); spw[p] = 0.5; spw[q] = 0.5; c = sqrt((x[v]-x[w])*(x[v]-x[w])+(y[v]-y[w])*(y[v]-y[w])); spa[p] = HeronsTriangle(a, b, c) / 2.0; spa[q] = spa[p]; } else { du = sqrt((xx-x[u])*(xx-x[u])+(yy-y[u])*(yy-y[u])); dv = sqrt((xx-x[v])*(xx-x[v])+(yy-y[v])*(yy-y[v])); dw = sqrt((xx-x[w])*(xx-x[w])+(yy-y[w])*(yy-y[w])); spw[p] = dv / (dv+dw); spw[q] = dw / (dv+dw); spa[p] = HeronsTriangle(b, dv, du); spa[q] = HeronsTriangle(a, dw, du); } spx[p] = SimplexOfNodes(net, u, v, i, m); spx[q] = SimplexOfNodes(net, u, w, i, m); beta = atan2(yb, xb); if(beta < 0) beta += M_PI; beta -= phii; if(beta > M_PI / 2) beta = M_PI - beta; spd[i] = b * fabs(sin(beta)); beta = atan2(ya, xa); if(beta < 0) beta += M_PI; beta -= phii; if(beta > M_PI / 2) beta = M_PI - beta; spd[i] += a * fabs(sin(beta)); } j = 3; break; } } } } } void Tubes(unsigned int *spx, double *spw, double *spa, const unsigned int *net, const unsigned int *tri, const unsigned int m, const unsigned int n, const double *x, const double *y, const double *z) { double zu, zv, dv; //double tini, tend; unsigned int p, q, u, v, w; unsigned int i, j, k, l, s, t; unsigned int msinks, nsinks, mm; unsigned int *seen, *sinks, dst; unsigned int *sinku, *uniqu, *udest; Queue *que; //tini = omp_get_wtime(); // m is number of facets // n is number of points mm = m + m; sinks = malloc(mm * 2 * sizeof(unsigned int)); sinku = malloc(mm * 2 * sizeof(unsigned int)); if(!sinks || !sinku) { PyErr_SetString(PyExc_MemoryError, "..."); exit(EXIT_FAILURE); } //#pragma omp parallel for private(i,j,k,l,s,p,q,u,v,zu,zv,dst) //we don't want to have this in parallel because we manipulate spx[l*2+k] = dst for(i = 0; i < m; i++) { p = i * 2; for(j = 0; j < 2; j++) { q = p + j; sinks[q] = mm; sinku[q] = n; l = spx[q]; if(l == m) continue; // check whether two neighboring facets flow into each other if(spx[l*2] == i || spx[l*2+1] == i) { // get lowest node of these two facets u = NodeOfSimplicies(tri, i, l, z); zu = z[u]; dst = m; for(k = net[u]; k < net[u+1]; k++) { v = net[k]; if(v == i || v == l) continue; zv = z[tri[v*3]]; if(z[tri[v*3+1]] > zv) zv = z[tri[v*3+1]]; if(z[tri[v*3+2]] > zv) zv = z[tri[v*3+2]]; if(zv == zu) { dst = v; break; } } if(dst < m) { spx[q] = dst; // rewire also the other facet to that lower facet (l->dest) for(k = 0; k < 2; k++) if(spx[l*2+k] == i) spx[l*2+k] = dst; } else { sinks[q] = q; sinku[q] = u; } } } } //tend = omp_get_wtime(); //printf("%.4f\n", tend - tini); //tini = tend; msinks = 0; for(i = 0; i < mm; i++) { if(sinks[i] < mm) { sinks[msinks] = sinks[i]; sinku[msinks++] = sinku[i]; } } sinks = realloc(sinks, msinks * sizeof(unsigned int)); sinku = realloc(sinku, msinks * sizeof(unsigned int)); uniqu = malloc(n * sizeof(unsigned int)); udest = malloc(n * sizeof(unsigned int)); if(!uniqu || !udest) { PyErr_SetString(PyExc_MemoryError, "..."); exit(EXIT_FAILURE); } #pragma omp parallel for for(i = 0; i < n; i++) { uniqu[i] = n; udest[i] = m; } for(i = 0; i < msinks; i++) { u = sinku[i]; uniqu[u] = u; } nsinks = 0; for(i = 0; i < n; i++) if(uniqu[i] < n) uniqu[nsinks++] = uniqu[i]; uniqu = realloc(uniqu, nsinks * sizeof(unsigned int)); fprintf(stderr, "# n: %.1e, m: %.1e, nsinks: %.1e\n", (double)n, (double)m, (double)nsinks); fprintf(stderr, "# point, facet, distance\n"); //tend = omp_get_wtime(); //printf("%.4f\n", tend - tini); //tini = tend; #pragma omp parallel for private(i,k,s,t,u,v,w,zu,zv,dv,seen,que) schedule(dynamic, 4) for(i = 0; i < nsinks; i++) { u = uniqu[i]; zu = z[u]; que = malloc(sizeof(Queue)); seen = calloc(m, sizeof(unsigned int)); if(!que || !seen) { PyErr_SetString(PyExc_MemoryError, "..."); exit(EXIT_FAILURE); } que->first = que->last = NULL; for(k = net[u]; k < net[u+1]; k++) { v = net[k]; seen[v]++; if(put(que, v, 0)) { PyErr_SetString(PyExc_MemoryError, "failed to fill queue .."); exit(EXIT_FAILURE); } } while(!get(que, &v, &dv)) { if(dv > 99) { fprintf(stderr, "%i %i %.0f\n", u, m, dv); break; } zv = z[tri[v*3]]; if(z[tri[v*3+1]] > zv) zv = z[tri[v*3+1]]; if(z[tri[v*3+2]] > zv) zv = z[tri[v*3+2]]; if(zv < zu) { udest[u] = v; fprintf(stderr, "%i %i %.0f\n", u, v, dv); break; } for(s = 0; s < 3; s++) { t = tri[v*3+s]; for(k = net[t]; k < net[t+1]; k++) { w = net[k]; if(seen[w]) continue; seen[w]++; if(put(que, w, dv+1)) { PyErr_SetString(PyExc_MemoryError, "failed to fill queue .."); exit(EXIT_FAILURE); } } } } while(!get(que, &v, &dv)); free(seen); free(que); } free(uniqu); //tend = omp_get_wtime(); //printf("%.4f\n", tend - tini); //tini = tend; #pragma omp parallel for private(i,q,u) for(i = 0; i < msinks; i++) { q = sinks[i]; u = sinku[i]; spx[q] = udest[u]; } free(udest); free(sinks); free(sinku); // fix spw and spa #pragma omp parallel for private(i,p) for(i = 0; i < m; i++) { p = i * 2; if(spx[p] == m && spx[p+1] < m) { spa[p+1] += spa[p]; spw[p+1] = 1; spw[p] = 0; } else if(spx[p] < m && spx[p+1] == m) { spa[p] += spa[p+1]; spw[p] = 1; spw[p+1] = 0; } } //tend = omp_get_wtime(); //printf("%.4f\n", tend - tini); //tini = tend; } static PyObject * DemNets_Simplicies(PyObject *self, PyObject* args) { PyObject *triarg; PyArrayObject *tri, *net; unsigned int n; // parse input if(!PyArg_ParseTuple(args, "OI", &triarg, &n)) return NULL; tri = (PyArrayObject *) PyArray_ContiguousFromObject(triarg, PyArray_UINT, 2, 2); if(!tri) return NULL; // get simplicies for a given node net = Simplicies((unsigned int *)tri->data, tri->dimensions[0], n); Py_DECREF(tri); return PyArray_Return(net); } static PyObject * DemNets_GridAggregate(PyObject *self, PyObject* args) { PyObject *xbarg, *ybarg, *xarg, *yarg, *uarg, *varg; PyArrayObject *xb, *yb, *x, *y, *u, *v, *ugrid, *vgrid, *cgrid; unsigned int n; npy_intp dim[2]; // parse input if(!PyArg_ParseTuple(args, "OOOOOO", &xbarg, &ybarg, &xarg, &yarg, &uarg, &varg)) return NULL; xb = (PyArrayObject *) PyArray_ContiguousFromObject(xbarg, PyArray_DOUBLE, 1, 1); yb = (PyArrayObject *) PyArray_ContiguousFromObject(ybarg, PyArray_DOUBLE, 1, 1); x = (PyArrayObject *) PyArray_ContiguousFromObject(xarg, PyArray_DOUBLE, 1, 1); y = (PyArrayObject *) PyArray_ContiguousFromObject(yarg, PyArray_DOUBLE, 1, 1); u = (PyArrayObject *) PyArray_ContiguousFromObject(uarg, PyArray_DOUBLE, 1, 1); v = (PyArrayObject *) PyArray_ContiguousFromObject(varg, PyArray_DOUBLE, 1, 1); if(!xb || !yb || !x || !y || !u || !v) return NULL; // sanity check n = x->dimensions[0]; if(n != y->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "dimension mismatch between x and y coordinates."); return NULL; } if(n != u->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "dimension mismatch between vectors and coordinates."); return NULL; } if(n != v->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "dimension mismatch between u and v components."); return NULL; } // alloc numpy array dim[0] = (xb->dimensions[0] - 1); dim[1] = (yb->dimensions[0] - 1); ugrid = (PyArrayObject *) PyArray_ZEROS(2, dim, PyArray_DOUBLE, 0); vgrid = (PyArrayObject *) PyArray_ZEROS(2, dim, PyArray_DOUBLE, 0); cgrid = (PyArrayObject *) PyArray_ZEROS(2, dim, PyArray_UINT, 0); if(!ugrid || !vgrid || !cgrid) { PyErr_SetString(PyExc_MemoryError, "..."); return NULL; } // vectorial mean for each grid cell defined by (xb, yb) GridAggregate((double *)ugrid->data, (double *)vgrid->data, (unsigned int *)cgrid->data, (double *)xb->data, dim[0], (double *)yb->data, dim[1], (double *)x->data, (double *)y->data, (double *)u->data, (double *)v->data, n); Py_DECREF(xb); Py_DECREF(yb); Py_DECREF(x); Py_DECREF(y); Py_DECREF(u); Py_DECREF(v); return Py_BuildValue("(OOO)", ugrid, vgrid, cgrid); } static PyObject * DemNets_GridAggregateVar(PyObject *self, PyObject* args) { PyObject *xbarg, *ybarg, *xarg, *yarg, *uarg, *varg, *umarg, *vmarg; PyArrayObject *xb, *yb, *x, *y, *u, *v, *ugrid, *vgrid, *umean, *vmean; unsigned int n; npy_intp dim[2]; // parse input if(!PyArg_ParseTuple(args, "OOOOOOOO", &xbarg, &ybarg, &xarg, &yarg, &uarg, &varg, &umarg, &vmarg)) return NULL; xb = (PyArrayObject *) PyArray_ContiguousFromObject(xbarg, PyArray_DOUBLE, 1, 1); yb = (PyArrayObject *) PyArray_ContiguousFromObject(ybarg, PyArray_DOUBLE, 1, 1); x = (PyArrayObject *) PyArray_ContiguousFromObject(xarg, PyArray_DOUBLE, 1, 1); y = (PyArrayObject *) PyArray_ContiguousFromObject(yarg, PyArray_DOUBLE, 1, 1); u = (PyArrayObject *) PyArray_ContiguousFromObject(uarg, PyArray_DOUBLE, 1, 1); v = (PyArrayObject *) PyArray_ContiguousFromObject(varg, PyArray_DOUBLE, 1, 1); umean = (PyArrayObject *) PyArray_ContiguousFromObject(umarg, PyArray_DOUBLE, 2, 2); vmean = (PyArrayObject *) PyArray_ContiguousFromObject(vmarg, PyArray_DOUBLE, 2, 2); if(!xb || !yb || !x || !y || !u || !v || !umean || !vmean) return NULL; // sanity check n = x->dimensions[0]; if(n != y->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "dimension mismatch between x and y coordinates."); return NULL; } if(n != u->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "dimension mismatch between vectors and coordinates."); return NULL; } if(n != v->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "dimension mismatch between u and v components."); return NULL; } // alloc numpy array dim[0] = (xb->dimensions[0] - 1); dim[1] = (yb->dimensions[0] - 1); ugrid = (PyArrayObject *) PyArray_ZEROS(2, dim, PyArray_DOUBLE, 0); vgrid = (PyArrayObject *) PyArray_ZEROS(2, dim, PyArray_DOUBLE, 0); if(!ugrid || !vgrid) { PyErr_SetString(PyExc_MemoryError, "..."); return NULL; } // vectorial variance for each grid cell defined by (xb, yb) GridAggregateVar((double *)ugrid->data, (double *)vgrid->data, (double *)xb->data, dim[0], (double *)yb->data, dim[1], (double *)x->data, (double *)y->data, (double *)u->data, (double *)v->data, (double *)umean->data, (double *)vmean->data, n); Py_DECREF(xb); Py_DECREF(yb); Py_DECREF(x); Py_DECREF(y); Py_DECREF(u); Py_DECREF(v); Py_DECREF(umean); Py_DECREF(vmean); return Py_BuildValue("(OO)", ugrid, vgrid); } static PyObject * DemNets_GridMaximum(PyObject *self, PyObject* args) { PyObject *xbarg, *ybarg, *xarg, *yarg, *zarg; PyArrayObject *xb, *yb, *x, *y, *z, *zgrid; unsigned int n; npy_intp dim[2]; // parse input if(!PyArg_ParseTuple(args, "OOOOO", &xbarg, &ybarg, &xarg, &yarg, &zarg)) return NULL; xb = (PyArrayObject *) PyArray_ContiguousFromObject(xbarg, PyArray_DOUBLE, 1, 1); yb = (PyArrayObject *) PyArray_ContiguousFromObject(ybarg, PyArray_DOUBLE, 1, 1); x = (PyArrayObject *) PyArray_ContiguousFromObject(xarg, PyArray_DOUBLE, 1, 1); y = (PyArrayObject *) PyArray_ContiguousFromObject(yarg, PyArray_DOUBLE, 1, 1); z = (PyArrayObject *) PyArray_ContiguousFromObject(zarg, PyArray_DOUBLE, 1, 1); if(!xb || !yb || !x || !y || !z) return NULL; // sanity check n = x->dimensions[0]; if(n != y->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "dimension mismatch between x and y coordinates."); return NULL; } if(n != z->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "dimension mismatch between variable and coordinates."); return NULL; } // alloc numpy array dim[0] = (xb->dimensions[0] - 1); dim[1] = (yb->dimensions[0] - 1); zgrid = (PyArrayObject *) PyArray_ZEROS(2, dim, PyArray_DOUBLE, 0); if(!zgrid) { PyErr_SetString(PyExc_MemoryError, "..."); return NULL; } GridMaximum((double *)zgrid->data, (double *)xb->data, dim[0], (double *)yb->data, dim[1], (double *)x->data, (double *)y->data, (double *)z->data, n); Py_DECREF(xb); Py_DECREF(yb); Py_DECREF(x); Py_DECREF(y); Py_DECREF(z); return PyArray_Return(zgrid); } static PyObject * DemNets_Thinning(PyObject *self, PyObject* args) { PyObject *xbarg, *ybarg, *xarg, *yarg, *zarg; PyArrayObject *xb, *yb, *x, *y, *z, *idx; unsigned int n; // parse input if(!PyArg_ParseTuple(args, "OOOOO", &xbarg, &ybarg, &xarg, &yarg, &zarg)) return NULL; xb = (PyArrayObject *) PyArray_ContiguousFromObject(xbarg, PyArray_DOUBLE, 1, 1); yb = (PyArrayObject *) PyArray_ContiguousFromObject(ybarg, PyArray_DOUBLE, 1, 1); x = (PyArrayObject *) PyArray_ContiguousFromObject(xarg, PyArray_DOUBLE, 1, 1); y = (PyArrayObject *) PyArray_ContiguousFromObject(yarg, PyArray_DOUBLE, 1, 1); z = (PyArrayObject *) PyArray_ContiguousFromObject(zarg, PyArray_DOUBLE, 1, 1); if(!xb || !yb || !x || !y || !z) return NULL; // sanity check n = x->dimensions[0]; if(n != y->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "dimension mismatch between x and y coordinates."); return NULL; } if(n != z->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "dimension mismatch between variable and coordinates."); return NULL; } // alloc numpy array idx = (PyArrayObject *) PyArray_ZEROS(1, x->dimensions, PyArray_INT, 0); if(!idx) { PyErr_SetString(PyExc_MemoryError, "..."); return NULL; } Thinning((int *)idx->data, (double *)xb->data, xb->dimensions[0], (double *)yb->data, yb->dimensions[0], (double *)x->data, (double *)y->data, (double *)z->data, n); Py_DECREF(xb); Py_DECREF(yb); Py_DECREF(x); Py_DECREF(y); Py_DECREF(z); return PyArray_Return(idx); } static PyObject * DemNets_FacetUpstreamNetwork(PyObject *self, PyObject* args) { PyObject *spxarg; PyArrayObject *spx, *net; // parse input if(!PyArg_ParseTuple(args, "O", &spxarg)) return NULL; spx = (PyArrayObject *) PyArray_ContiguousFromObject(spxarg, PyArray_UINT, 2, 2); if(!spx) return NULL; // reverse the flow network net = UpstreamNetwork((unsigned int *)spx->data, spx->dimensions[0]); Py_DECREF(spx); return PyArray_Return(net); } static PyObject * DemNets_FacetFlowThroughput(PyObject *self, PyObject* args) { PyObject *spxarg, *spwarg, *spaarg; PyArrayObject *spx, *spw, *spa, *ltp; char errstr[30]; unsigned int i; // parse input if(!PyArg_ParseTuple(args, "OOO", &spxarg, &spwarg, &spaarg)) return NULL; spx = (PyArrayObject *) PyArray_ContiguousFromObject(spxarg, PyArray_UINT, 2, 2); spw = (PyArrayObject *) PyArray_ContiguousFromObject(spwarg, PyArray_DOUBLE, 2, 2); spa = (PyArrayObject *) PyArray_ContiguousFromObject(spaarg, PyArray_DOUBLE, 2, 2); if(!spx || !spw || !spa) return NULL; // check input for(i = 0; i < 2; i++) { if(spx->dimensions[i] != spw->dimensions[i]) { snprintf(errstr, 30 * sizeof(char), "spx.shape[%i] != spw.shape[%i]", i, i); PyErr_SetString(PyExc_IndexError, errstr); return NULL; } if(spx->dimensions[i] != spa->dimensions[i]) { snprintf(errstr, 30 * sizeof(char), "spx.shape[%i] != spa.shape[%i]", i, i); PyErr_SetString(PyExc_IndexError, errstr); return NULL; } } // allocate output arrays ltp = (PyArrayObject *) PyArray_ZEROS(2, spx->dimensions, PyArray_DOUBLE, 0); if(!ltp) { PyErr_SetString(PyExc_MemoryError, "Cannot allocate enough memory for output."); return NULL; } // get node throughput FacetFlowThroughput((double *)ltp->data, (unsigned int *)spx->data, (double *)spw->data, (double *)spa->data, ltp->dimensions[0]); Py_DECREF(spx); Py_DECREF(spw); Py_DECREF(spa); return PyArray_Return(ltp); } static PyObject * DemNets_FacetFlowNetwork(PyObject *self, PyObject* args) { PyObject *netarg, *triarg, *xarg, *yarg, *zarg; PyArrayObject *spx, *spw, *spa, *spd, *phi; PyArrayObject *x, *y, *z, *net, *tri; npy_intp dim[2]; unsigned int *e, n; // parse input if(!PyArg_ParseTuple(args, "OOOOO", &triarg, &netarg, &xarg, &yarg, &zarg)) return NULL; tri = (PyArrayObject *) PyArray_ContiguousFromObject(triarg, PyArray_UINT, 2, 2); net = (PyArrayObject *) PyArray_ContiguousFromObject(netarg, PyArray_UINT, 1, 1); x = (PyArrayObject *) PyArray_ContiguousFromObject(xarg, PyArray_DOUBLE, 1, 1); y = (PyArrayObject *) PyArray_ContiguousFromObject(yarg, PyArray_DOUBLE, 1, 1); z = (PyArrayObject *) PyArray_ContiguousFromObject(zarg, PyArray_DOUBLE, 1, 1); if(!tri || !net || !x || !y || !z) return NULL; // check input e = (unsigned int *) net->data; n = e[0] - 1; if(e[n] != net->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "corrupted network format."); return NULL; } if(n != x->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "x array does not match network."); return NULL; } if(n != y->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "y array does not match network."); return NULL; } if(n != z->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "z array does not match network."); return NULL; } // allocate output arrays dim[0] = tri->dimensions[0]; dim[1] = 2; spx = (PyArrayObject *) PyArray_ZEROS(2, dim, PyArray_UINT, 0); spw = (PyArrayObject *) PyArray_ZEROS(2, dim, PyArray_DOUBLE, 0); spa = (PyArrayObject *) PyArray_ZEROS(2, dim, PyArray_DOUBLE, 0); spd = (PyArrayObject *) PyArray_ZEROS(1, dim, PyArray_DOUBLE, 0); phi = (PyArrayObject *) PyArray_ZEROS(1, dim, PyArray_DOUBLE, 0); if(!spx || !spw || !spa || !spd || !phi) { PyErr_SetString(PyExc_MemoryError, "Cannot allocate enough memory for output."); return NULL; } // get basic voronoi shaped flow network FacetFlowNetwork((unsigned int *)spx->data, (double *)spw->data, (double *)spa->data, (double *)spd->data, (double *)phi->data, (unsigned int *)net->data, (unsigned int *)tri->data, dim[0], (double *)x->data, (double *)y->data, (double *)z->data); Py_DECREF(net); Py_DECREF(x); Py_DECREF(y); Py_DECREF(z); Py_DECREF(tri); return Py_BuildValue("(OOOOO)", spx, spw, spa, spd, phi); } static PyObject * DemNets_Tubes(PyObject *self, PyObject* args) { PyObject *netarg, *triarg, *xarg, *yarg, *zarg, *spxarg, *spwarg, *spaarg; PyArrayObject *spx, *spw, *spa; PyArrayObject *x, *y, *z, *net, *tri; unsigned int *e, n; // parse input if(!PyArg_ParseTuple(args, "OOOOOOOO", &triarg, &netarg, &xarg, &yarg, &zarg, &spxarg, &spwarg, &spaarg)) return NULL; tri = (PyArrayObject *) PyArray_ContiguousFromObject(triarg, PyArray_UINT, 2, 2); net = (PyArrayObject *) PyArray_ContiguousFromObject(netarg, PyArray_UINT, 1, 1); x = (PyArrayObject *) PyArray_ContiguousFromObject(xarg, PyArray_DOUBLE, 1, 1); y = (PyArrayObject *) PyArray_ContiguousFromObject(yarg, PyArray_DOUBLE, 1, 1); z = (PyArrayObject *) PyArray_ContiguousFromObject(zarg, PyArray_DOUBLE, 1, 1); spx = (PyArrayObject *) PyArray_ContiguousFromObject(spxarg, PyArray_UINT, 2, 2); spw = (PyArrayObject *) PyArray_ContiguousFromObject(spwarg, PyArray_DOUBLE, 2, 2); spa = (PyArrayObject *) PyArray_ContiguousFromObject(spaarg, PyArray_DOUBLE, 2, 2); if(!tri || !net || !x || !y || !z || !spx || !spw || !spa) return NULL; // check input e = (unsigned int *) net->data; n = e[0] - 1; if(e[n] != net->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "corrupted network format."); return NULL; } if(n != x->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "x array does not match network."); return NULL; } if(n != y->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "y array does not match network."); return NULL; } if(n != z->dimensions[0]) { PyErr_SetString(PyExc_IndexError, "z array does not match network."); return NULL; } // introduce tubes for subsurface flows in order to handle sinks Tubes((unsigned int *)spx->data, (double *)spw->data, (double *)spa->data, (unsigned int *)net->data, (unsigned int *)tri->data, tri->dimensions[0], x->dimensions[0], (double *)x->data, (double *)y->data, (double *)z->data); Py_DECREF(net); Py_DECREF(x); Py_DECREF(y); Py_DECREF(z); Py_DECREF(tri); return Py_BuildValue("(OOO)", spx, spw, spa); } static PyMethodDef DemNets_Methods[] = { {"Simplicies", DemNets_Simplicies, METH_VARARGS, "..."}, {"Tubes", DemNets_Tubes, METH_VARARGS, "..."}, {"GridAggregate", DemNets_GridAggregate, METH_VARARGS, "..."}, {"GridAggregateVar", DemNets_GridAggregateVar, METH_VARARGS, "..."}, {"GridMaximum", DemNets_GridMaximum, METH_VARARGS, "..."}, {"Thinning", DemNets_Thinning, METH_VARARGS, "..."}, {"FacetUpstreamNetwork", DemNets_FacetUpstreamNetwork, METH_VARARGS, "..."}, {"FacetFlowNetwork", DemNets_FacetFlowNetwork, METH_VARARGS, "..."}, {"FacetFlowThroughput", DemNets_FacetFlowThroughput, METH_VARARGS, "..."}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef ModDef = { PyModuleDef_HEAD_INIT, "DemNets", NULL, -1, DemNets_Methods }; PyMODINIT_FUNC PyInit_DemNets(void) { PyObject *mod; mod = PyModule_Create(&ModDef); PyModule_AddStringConstant(mod, "__author__", "Aljoscha Rheinwalt <aljoscha.rheinwalt@uni-potsdam.de>"); PyModule_AddStringConstant(mod, "__version__", VERSION); import_array(); return mod; } int main(int argc, char **argv) { wchar_t pname[255]; PyImport_AppendInittab("DemNets", PyInit_DemNets); mbstowcs(pname, argv[0], strlen(argv[0])+1); Py_SetProgramName(pname); Py_Initialize(); PyImport_ImportModule("DemNets"); PyMem_RawFree(argv[0]); return 0; }
command_reverse.c
// Copyright 2019 Huiguang Yi. All Rights Reservered. // // 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 "command_reverse.h" #include "global_basic.h" #include "command_shuffle.h" #include "command_dist.h" #include <assert.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <argp.h> #include <argz.h> #include <err.h> #include <errno.h> #include <math.h> struct arg_reverse { struct arg_global* global; char* name; }; static struct argp_option opt_reverse[] = { {"shufFile",'L',"<path>",0,"provide .shuf file.\v"}, {"outdir",'o',"<path>",0,"path for recovered k-mer files.\v"}, {"threads",'p',"INT",0,"threads num.\v"}, {"byreads",'b',0,0,"recover k-mer from sketched reads .\v"}, { 0 } }; static char doc_reverse[] = "\n" "The reverse doc prefix." "\v" "The reverse doc suffix." ; reverse_opt_val_t reverse_opt_val = { "", ".", 1, false, }; static error_t parse_reverse(int key, char* arg, struct argp_state* state) { struct arg_reverse* reverse = state->input; assert( reverse ); assert( reverse->global ); switch(key) { case 'L': { struct stat path_stat; if( stat(arg,&path_stat) >=0 && S_ISREG(path_stat.st_mode)){ if(strlen(arg) < PATHLEN ) strcpy(reverse_opt_val.shufile,arg); else err(errno,"-L argument path should not longer than %d",PATHLEN); } break; } case 'o': { if(strlen(arg) > PATHLEN) { err(errno,"the outdir path should not longer than %d", PATHLEN); exit(EXIT_FAILURE); }; strcpy(reverse_opt_val.outdir,arg); break; } case 'p': { #ifdef _OPENMP reverse_opt_val.p = atoi(arg) ; #else warnx("This version of kssd was built without OpenMP and " "thus does not support multi threading. Ignoring -p %d",atoi(arg)); break; #endif } break; case 'b': { reverse_opt_val.byreads = true; } case ARGP_KEY_ARGS: { reverse_opt_val.num_remaining_args = state->argc - state->next; reverse_opt_val.remaining_args = state->argv + state->next; break; } case ARGP_KEY_NO_ARGS: { if(state->argc < 2) { printf("\v"); argp_state_help(state,stdout,ARGP_HELP_SHORT_USAGE); printf("\v"); argp_state_help(state,stdout,ARGP_HELP_LONG); printf("\v"); exit(0); }; return EINVAL; } break; default: return ARGP_ERR_UNKNOWN; } return 0; }; static struct argp argp_reverse = { opt_reverse, parse_reverse, "<co dir>", doc_reverse }; int cmd_reverse(struct argp_state* state) { int argc = state->argc - state->next + 1; char** argv = &state->argv[state->next - 1]; char* argv0 = argv[0]; argv[0] = malloc(strlen(state->name) + strlen(" reverse") + 1); if(!argv[0]) argp_failure(state, 1, ENOMEM, 0); sprintf(argv[0], "%s reverse", state->name); argp_parse(&argp_reverse, argc, argv, ARGP_IN_ORDER, &argc, &shuffle); free(argv[0]); argv[0] = argv0; state->next += argc - 1; if(reverse_opt_val.byreads) return co_rvs2kmer_byreads(&reverse_opt_val ); else return co_reverse2kmer(&reverse_opt_val); } int co_rvs2kmer_byreads( reverse_opt_val_t *opt_val ){ dim_shuffle_t* shuf_arr = read_dim_shuffle_file(opt_val->shufile); int shuf_arr_len = 1LLU << (4 * shuf_arr->dim_shuffle_stat.subk) ; unsigned int rev_shuf_arr[MIN_SUBCTX_DIM_SMP_SZ]; int count = 0; for(unsigned int i=0; i< shuf_arr_len; i++) { if( shuf_arr->shuffled_dim[i] < MIN_SUBCTX_DIM_SMP_SZ ){ rev_shuf_arr[shuf_arr->shuffled_dim[i]] = i ; count++; } } if(count != MIN_SUBCTX_DIM_SMP_SZ) err(errno,"count %d not match MIN_SUBCTX_DIM_SMP_SZ %d",count,MIN_SUBCTX_DIM_SMP_SZ); int comp_code_bits = shuf_arr->dim_shuffle_stat.k - shuf_arr->dim_shuffle_stat.drlevel > COMPONENT_SZ ? 4*(shuf_arr->dim_shuffle_stat.k - shuf_arr->dim_shuffle_stat.drlevel - COMPONENT_SZ ) : 0 ; int inner_ctx_bits = shuf_arr->dim_shuffle_stat.subk * 4; int half_outer_ctx_bits = (shuf_arr->dim_shuffle_stat.k - shuf_arr->dim_shuffle_stat.subk) *2 ; int pf_bits = ( shuf_arr->dim_shuffle_stat.subk - shuf_arr->dim_shuffle_stat.drlevel ) * 4; int TL = shuf_arr->dim_shuffle_stat.k * 2; if (!(opt_val->num_remaining_args == 1 )) err(errno,"need speficy one query path"); const char *qryco_dstat_fpath = NULL; qryco_dstat_fpath = test_get_fullpath(opt_val->remaining_args[0],co_dstat); if( qryco_dstat_fpath == NULL ) err(errno,"%s is not a valid query folder",opt_val->remaining_args[0]); FILE *qry_co_stat_fp; if (( qry_co_stat_fp = fopen(qryco_dstat_fpath,"rb")) == NULL) err(errno,"qry co stat file:%s",qryco_dstat_fpath); char *qryco_dname = opt_val->remaining_args[0]; co_dstat_t co_qry_dstat; fread( &co_qry_dstat, sizeof(co_dstat_t), 1, qry_co_stat_fp); FILE *cbd_fcode_comp_index_fp; char co_cbd_fcode[PATHLEN];char co_cbd_index_fcode[PATHLEN]; struct stat fstat; sprintf(co_cbd_index_fcode,"%s/combco.index.0",qryco_dname); stat(co_cbd_index_fcode, &fstat); llong readn = fstat.st_size/sizeof(size_t) - 1 ; size_t **cbd_fcode_index_mem = (size_t **) malloc( co_qry_dstat.comp_num * sizeof(size_t *)); FILE **cbd_fcode_comp_fp = (FILE **) malloc(co_qry_dstat.comp_num * sizeof(FILE *)) ; for ( int j = 0; j < co_qry_dstat.comp_num; j++ ){ cbd_fcode_index_mem[j] = (size_t *) malloc( (readn+1)* sizeof(size_t)); sprintf(co_cbd_index_fcode,"%s/combco.index.%d",qryco_dname,j); if( (cbd_fcode_comp_index_fp = fopen(co_cbd_index_fcode,"rb"))==NULL) err(errno,"co_rvs2kmer_btreads()::%s",co_cbd_index_fcode); fread(cbd_fcode_index_mem[j],sizeof(size_t),readn+1,cbd_fcode_comp_index_fp); fclose(cbd_fcode_comp_index_fp); sprintf(co_cbd_fcode,"%s/combco.%d",qryco_dname,j); if( (cbd_fcode_comp_fp[j] = fopen(co_cbd_fcode,"rb"))==NULL) err(errno,"co_rvs2kmer_btreads()::%s[%d]",co_cbd_fcode,j); } char *kstring = malloc(TL + 1); kstring[TL] = '\0'; unsigned int ind; for(llong n=0; n< readn;n++){ printf(">read %llu\n", n+1); for ( int j = 0; j < co_qry_dstat.comp_num; j++ ){ for ( llong k=0; k< cbd_fcode_index_mem[j][n+1]-cbd_fcode_index_mem[j][n]; k++){ fread(&ind,sizeof(unsigned int),1,cbd_fcode_comp_fp[j]); llong unituple = core_reverse2unituple(ind,j,comp_code_bits,pf_bits,inner_ctx_bits,half_outer_ctx_bits,rev_shuf_arr); for(int i=0; i<TL;i++){ kstring[TL-i-1] = Mapbase[unituple % 4] ; unituple >>= 2 ; } printf("%s\n",kstring); } } } for ( int j = 0; j < co_qry_dstat.comp_num; j++ ){ fclose(cbd_fcode_comp_fp[j]); free(cbd_fcode_index_mem[j]); } free(cbd_fcode_index_mem); free(cbd_fcode_comp_fp); return 1; } typedef unsigned int ctx_obj_ct_t; int co_reverse2kmer(reverse_opt_val_t *opt_val) { dim_shuffle_t* shuf_arr = read_dim_shuffle_file(opt_val->shufile); int shuf_arr_len = 1LLU << (4 * shuf_arr->dim_shuffle_stat.subk) ; unsigned int rev_shuf_arr[MIN_SUBCTX_DIM_SMP_SZ]; int count = 0; for(unsigned int i=0; i< shuf_arr_len; i++) { if( shuf_arr->shuffled_dim[i] < MIN_SUBCTX_DIM_SMP_SZ ){ rev_shuf_arr[shuf_arr->shuffled_dim[i]] = i ; count++; } } if(count != MIN_SUBCTX_DIM_SMP_SZ) err(errno,"count %d not match MIN_SUBCTX_DIM_SMP_SZ %d",count,MIN_SUBCTX_DIM_SMP_SZ); int comp_code_bits = shuf_arr->dim_shuffle_stat.k - shuf_arr->dim_shuffle_stat.drlevel > COMPONENT_SZ ? 4*(shuf_arr->dim_shuffle_stat.k - shuf_arr->dim_shuffle_stat.drlevel - COMPONENT_SZ ) : 0 ; int inner_ctx_bits = shuf_arr->dim_shuffle_stat.subk * 4; int half_outer_ctx_bits = (shuf_arr->dim_shuffle_stat.k - shuf_arr->dim_shuffle_stat.subk) *2 ; int pf_bits = ( shuf_arr->dim_shuffle_stat.subk - shuf_arr->dim_shuffle_stat.drlevel ) * 4; int TL = shuf_arr->dim_shuffle_stat.k * 2; if (!(opt_val->num_remaining_args >0 )) err(errno,"need speficy the query path"); const char *qryco_dstat_fpath = NULL; qryco_dstat_fpath = test_get_fullpath(opt_val->remaining_args[0],co_dstat); if( qryco_dstat_fpath == NULL ) err(errno,"%s is not a valid query folder",opt_val->remaining_args[0]); FILE *qry_co_stat_fp; if (( qry_co_stat_fp = fopen(qryco_dstat_fpath,"rb")) == NULL) err(errno,"qry co stat file:%s",qryco_dstat_fpath); char *qryco_dname = opt_val->remaining_args[0]; co_dstat_t co_qry_dstat; fread( &co_qry_dstat, sizeof(co_dstat_t), 1, qry_co_stat_fp); ctx_obj_ct_t * qry_ctx_ct_list = malloc(co_qry_dstat.infile_num * sizeof(ctx_obj_ct_t)); fread(qry_ctx_ct_list,sizeof(ctx_obj_ct_t),co_qry_dstat.infile_num,qry_co_stat_fp); char (*cofname)[PATHLEN] = malloc(co_qry_dstat.infile_num * PATHLEN); fread(cofname,PATHLEN,co_qry_dstat.infile_num,qry_co_stat_fp); fclose(qry_co_stat_fp); FILE *cbd_fcode_comp_fp,*cbd_fcode_comp_index_fp; struct stat cbd_fcode_stat; size_t *fco_pos = malloc(sizeof(size_t) * (co_qry_dstat.infile_num + 1) ); char co_cbd_fcode[PATHLEN];char co_cbd_index_fcode[PATHLEN]; llong **kmer = malloc( co_qry_dstat.infile_num * sizeof(llong*) ); int *filled_len = calloc( co_qry_dstat.infile_num, sizeof(int)); for(int k = 0; k < co_qry_dstat.infile_num; k++){ kmer[k] = malloc( sizeof(llong) * qry_ctx_ct_list[k] ); } int p_fit_mem = opt_val->p ; for ( int j = 0; j < co_qry_dstat.comp_num; j++ ) { sprintf(co_cbd_fcode,"%s/combco.%d",qryco_dname,j); if( (cbd_fcode_comp_fp = fopen(co_cbd_fcode,"rb"))==NULL) err(errno,"co_reverse2kmer()::%s",co_cbd_fcode); stat(co_cbd_fcode, &cbd_fcode_stat); unsigned int *cbd_fcode_mem = malloc(cbd_fcode_stat.st_size); fread(cbd_fcode_mem,sizeof(unsigned int),cbd_fcode_stat.st_size/sizeof(unsigned int),cbd_fcode_comp_fp); fclose(cbd_fcode_comp_fp); sprintf(co_cbd_index_fcode,"%s/combco.index.%d",qryco_dname,j); if( (cbd_fcode_comp_index_fp = fopen(co_cbd_index_fcode,"rb"))==NULL) err(errno,"co_reverse2kmer()::%s",co_cbd_index_fcode); fread(fco_pos,sizeof(size_t),co_qry_dstat.infile_num + 1 ,cbd_fcode_comp_index_fp); fclose(cbd_fcode_comp_index_fp); #pragma omp parallel for num_threads(p_fit_mem) schedule(guided) for(int k = 0; k < co_qry_dstat.infile_num; k++){ if(qry_ctx_ct_list[k]==0) continue; char *kstring = malloc(TL + 1); kstring[TL] = '\0'; for(int n = 0; n < fco_pos[k+1] - fco_pos[k]; n++){ unsigned int ind = cbd_fcode_mem[ fco_pos[k] + n ]; kmer[k][filled_len[k] + n] = core_reverse2unituple(ind,j,comp_code_bits,pf_bits,inner_ctx_bits,half_outer_ctx_bits,rev_shuf_arr); } filled_len[k] += (fco_pos[k+1] - fco_pos[k]) ; } } #pragma omp parallel for num_threads(p_fit_mem) schedule(guided) for(int k = 0; k < co_qry_dstat.infile_num; k++) { if(qry_ctx_ct_list[k]==0) continue; char *kstring = malloc(TL + 1); kstring[TL] = '\0'; char *filename; (filename = strrchr(cofname[k],'/') ) ? ++filename : (filename = cofname[k]); char fullname[PATHLEN]; sprintf(fullname,"%s/%s",opt_val->outdir,filename); FILE *kmerf; if ( ( kmerf = fopen(fullname,"w")) == NULL ) err(errno,"%s",filename); for (int n =0 ; n< qry_ctx_ct_list[k]; n++){ llong unituple = kmer[k][n]; for(int i=0; i<TL;i++){ kstring[TL-i-1] = Mapbase[unituple % 4] ; unituple >>= 2 ; } fprintf(kmerf,"%s\n",kstring); } fclose(kmerf); } return co_qry_dstat.infile_num; } llong core_reverse2unituple(unsigned int kid, int compid, int compbit, int pf_bits, int inner_ctx_bits, int half_outer_ctx_bits, unsigned int *rev_shuf_arr) { llong drtuple = ( ((llong)kid) << compbit ) + compid ; unsigned int ind = rev_shuf_arr[drtuple % MIN_SUBCTX_DIM_SMP_SZ]; llong tuple = ((drtuple >> pf_bits) << inner_ctx_bits) + (llong)ind; llong half_outer_ctx_mask = ( (1LLU << half_outer_ctx_bits) - 1 ) << inner_ctx_bits ; llong unituple = (tuple & (half_outer_ctx_mask << half_outer_ctx_bits)) + ((tuple & half_outer_ctx_mask) >> inner_ctx_bits ) + ( (tuple & ( (1LLU << inner_ctx_bits) - 1 )) << half_outer_ctx_bits ); return unituple; }
3d7pt.c
/* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 32; tile_size[1] = 32; tile_size[2] = 16; tile_size[3] = 512; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k]) + beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] + A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
pr25989.c
/* PR middle-end/25989 */ /* { dg-do compile } */ /* { dg-options "-O2 -fopenmp" } */ int main (void) { int i, j; float a, b = 1.0; #pragma omp parallel for schedule(guided,1) private(j) for (i = 1; i <= 9; i++) for (j = 1; j <= 9; j++) a = b; return 0; }
target_enter_data_map_messages.c
// RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify -fopenmp -ferror-limit 100 -o - %s // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify -fopenmp -ferror-limit 100 -o - -x c++ %s // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify -fopenmp-simd -ferror-limit 100 -o - %s // RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify -fopenmp-simd -ferror-limit 100 -o - -x c++ %s int main(int argc, char **argv) { int r; #pragma omp target enter data // expected-error {{expected at least one 'map' clause for '#pragma omp target enter data'}} #pragma omp target enter data map(r) // expected-error {{map type must be specified for '#pragma omp target enter data'}} #pragma omp target enter data map(tofrom: r) // expected-error {{map type 'tofrom' is not allowed for '#pragma omp target enter data'}} #pragma omp target enter data map(always, to: r) #pragma omp target enter data map(always, alloc: r) #pragma omp target enter data map(always, from: r) // expected-error {{map type 'from' is not allowed for '#pragma omp target enter data'}} #pragma omp target enter data map(release: r) // expected-error {{map type 'release' is not allowed for '#pragma omp target enter data'}} #pragma omp target enter data map(delete: r) // expected-error {{map type 'delete' is not allowed for '#pragma omp target enter data'}} return 0; }
image_pyramid.h
/* * * This file is part of the open-source SeetaFace engine, which includes three modules: * SeetaFace Detection, SeetaFace Alignment, and SeetaFace Identification. * * This file is part of the SeetaFace Detection module, containing codes implementing the * face detection method described in the following paper: * * * Funnel-structured cascade for multi-view face detection with alignment awareness, * Shuzhe Wu, Meina Kan, Zhenliang He, Shiguang Shan, Xilin Chen. * In Neurocomputing (under review) * * * Copyright (C) 2016, Visual Information Processing and Learning (VIPL) group, * Institute of Computing Technology, Chinese Academy of Sciences, Beijing, China. * * The codes are mainly developed by Shuzhe Wu (a Ph.D supervised by Prof. Shiguang Shan) * * As an open-source face recognition engine: you can redistribute SeetaFace source codes * and/or modify it under the terms of the BSD 2-Clause License. * * You should have received a copy of the BSD 2-Clause License along with the software. * If not, see < https://opensource.org/licenses/BSD-2-Clause>. * * Contact Info: you can send an email to SeetaFace@vipl.ict.ac.cn for any problems. * * Note: the above information must be kept whenever or wherever the codes are used. * */ #ifndef SEETA_FD_UTIL_IMAGE_PYRAMID_H_ #define SEETA_FD_UTIL_IMAGE_PYRAMID_H_ #include <cstdint> #include <string> #include "common.h" namespace seeta { namespace fd { static void ResizeImage(const seeta::ImageData & src, seeta::ImageData* dest) { int32_t src_width = src.width; int32_t src_height = src.height; int32_t dest_width = dest->width; int32_t dest_height = dest->height; if (src_width == dest_width && src_height == dest_height) { memcpy(dest->data, src.data, src_width * src_height * sizeof(uint8_t)); return; } double lf_x_scl = static_cast<double>(src_width) / dest_width; double lf_y_Scl = static_cast<double>(src_height) / dest_height; const uint8_t* src_data = src.data; uint8_t* dest_data = dest->data; #pragma omp parallel num_threads(SEETA_NUM_THREADS) { #pragma omp for nowait for (int32_t y = 0; y < dest_height; y++) { for (int32_t x = 0; x < dest_width; x++) { double lf_x_s = lf_x_scl * x; double lf_y_s = lf_y_Scl * y; int32_t n_x_s = static_cast<int>(lf_x_s); n_x_s = (n_x_s <= (src_width - 2) ? n_x_s : (src_width - 2)); int32_t n_y_s = static_cast<int>(lf_y_s); n_y_s = (n_y_s <= (src_height - 2) ? n_y_s : (src_height - 2)); double lf_weight_x = lf_x_s - n_x_s; double lf_weight_y = lf_y_s - n_y_s; double dest_val = (1 - lf_weight_y) * ((1 - lf_weight_x) * src_data[n_y_s * src_width + n_x_s] + lf_weight_x * src_data[n_y_s * src_width + n_x_s + 1]) + lf_weight_y * ((1 - lf_weight_x) * src_data[(n_y_s + 1) * src_width + n_x_s] + lf_weight_x * src_data[(n_y_s + 1) * src_width + n_x_s + 1]); dest_data[y * dest_width + x] = static_cast<uint8_t>(dest_val); } } } } class ImagePyramid { public: ImagePyramid() : max_scale_(1.0f), min_scale_(1.0f), scale_factor_(1.0f), scale_step_(0.8f), width1x_(0), height1x_(0), width_scaled_(0), height_scaled_(0), buf_img_width_(2), buf_img_height_(2), buf_scaled_width_(2), buf_scaled_height_(2) { buf_img_ = new uint8_t[buf_img_width_ * buf_img_height_]; buf_img_scaled_ = new uint8_t[buf_scaled_width_ * buf_scaled_height_]; } ~ImagePyramid() { delete[] buf_img_; buf_img_ = nullptr; buf_img_width_ = 0; buf_img_height_ = 0; delete[] buf_img_scaled_; buf_img_scaled_ = nullptr; buf_scaled_width_ = 0; buf_scaled_height_ = 0; img_scaled_.data = nullptr; img_scaled_.width = 0; img_scaled_.height = 0; } inline void SetScaleStep(float step) { if (step > 0.0f && step <= 1.0f) scale_step_ = step; } inline void SetMinScale(float min_scale) { min_scale_ = min_scale; } inline void SetMaxScale(float max_scale) { max_scale_ = max_scale; scale_factor_ = max_scale; UpdateBufScaled(); } void SetImage1x(const uint8_t* img_data, int32_t width, int32_t height); inline float min_scale() const { return min_scale_; } inline float max_scale() const { return max_scale_; } inline seeta::ImageData image1x() { seeta::ImageData img(width1x_, height1x_, 1); img.data = buf_img_; return img; } const seeta::ImageData* GetNextScaleImage(float* scale_factor = nullptr); private: void UpdateBufScaled(); float max_scale_; float min_scale_; float scale_factor_; float scale_step_; int32_t width1x_; int32_t height1x_; int32_t width_scaled_; int32_t height_scaled_; uint8_t* buf_img_; int32_t buf_img_width_; int32_t buf_img_height_; uint8_t* buf_img_scaled_; int32_t buf_scaled_width_; int32_t buf_scaled_height_; seeta::ImageData img_scaled_; }; } // namespace fd } // namespace seeta #endif // SEETA_FD_UTIL_IMAGE_PYRAMID_H_
declare_variant_clauses_ast_print.c
//RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fopenmp -fopenmp-version=51 \ //RUN: -Wno-source-uses-openmp -Wno-openmp-clauses \ //RUN: -ast-print -o - %s | FileCheck %s --check-prefix=PRINT //RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fopenmp -fopenmp-version=51 \ //RUN: -Wno-source-uses-openmp -Wno-openmp-clauses -DWIN -fms-compatibility \ //RUN: -ast-print -o - %s | FileCheck %s --check-prefixes=PRINT,PRINTW //RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fopenmp -fopenmp-version=51 \ //RUN: -Wno-source-uses-openmp -Wno-openmp-clauses \ //RUN: -ast-dump -o - %s | FileCheck %s --check-prefix=DUMP //RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fopenmp -fopenmp-version=51 \ //RUN: -Wno-source-uses-openmp -Wno-openmp-clauses -DWIN -fms-compatibility \ //RUN: -ast-dump -o - %s | FileCheck %s --check-prefixes=DUMP,DUMPW typedef void *omp_interop_t; #ifdef WIN //DUMPW: FunctionDecl{{.*}}win_foov //PRINTW: void win_foov(int n, double *y, void *interop_obj); void win_foov(int n, double *y, void *interop_obj); //DUMPW: FunctionDecl{{.*}}win_foo //DUMPW: OMPDeclareVariantAttr //DUMPW-NEXT: DeclRefExpr{{.*}}win_foov //PRINTW: #pragma omp declare variant(win_foov) match(construct={dispatch}, device={arch(x86_64)}) append_args(interop(targetsync)) //PRINTW: void win_foo(int n, double *y); #pragma omp declare variant (win_foov) \ match(construct={dispatch}, device={arch(x86_64)}) \ append_args(interop(targetsync)) void _cdecl win_foo(int n, double *y); #endif // WIN //DUMP: FunctionDecl{{.*}}c_foov //PRINT: void c_foov(int n, double *y, void *interop_obj); void c_foov(int n, double *y, void *interop_obj); //DUMP: FunctionDecl{{.*}}c_foo //DUMP: OMPDeclareVariantAttr //DUMP-NEXT: DeclRefExpr{{.*}}c_foov //PRINT: #pragma omp declare variant(c_foov) match(construct={dispatch}, device={arch(x86_64)}) append_args(interop(targetsync)) //PRINT: void c_foo(int n, double *y); #pragma omp declare variant (c_foov) \ match(construct={dispatch}, device={arch(x86_64)}) \ append_args(interop(targetsync)) void c_foo(int n, double *y);
hist_util.h
/*! * Copyright 2017-2020 by Contributors * \file hist_util.h * \brief Utility for fast histogram aggregation * \author Philip Cho, Tianqi Chen */ #ifndef XGBOOST_COMMON_HIST_UTIL_H_ #define XGBOOST_COMMON_HIST_UTIL_H_ #include <xgboost/data.h> #include <xgboost/generic_parameters.h> #include <limits> #include <vector> #include <algorithm> #include <memory> #include <utility> #include <map> #include "row_set.h" #include "common.h" #include "threading_utils.h" #include "../tree/param.h" #include "./quantile.h" #include "./timer.h" #include "../include/rabit/rabit.h" namespace xgboost { namespace common { /*! * \brief A single row in global histogram index. * Directly represent the global index in the histogram entry. */ using GHistIndexRow = Span<uint32_t const>; // A CSC matrix representing histogram cuts, used in CPU quantile hist. // The cut values represent upper bounds of bins containing approximately equal numbers of elements class HistogramCuts { protected: using BinIdx = uint32_t; public: HostDeviceVector<bst_float> cut_values_; // NOLINT HostDeviceVector<uint32_t> cut_ptrs_; // NOLINT // storing minimum value in a sketch set. HostDeviceVector<float> min_vals_; // NOLINT HistogramCuts(); HistogramCuts(HistogramCuts const& that) { cut_values_.Resize(that.cut_values_.Size()); cut_ptrs_.Resize(that.cut_ptrs_.Size()); min_vals_.Resize(that.min_vals_.Size()); cut_values_.Copy(that.cut_values_); cut_ptrs_.Copy(that.cut_ptrs_); min_vals_.Copy(that.min_vals_); } HistogramCuts(HistogramCuts&& that) noexcept(true) { *this = std::forward<HistogramCuts&&>(that); } HistogramCuts& operator=(HistogramCuts const& that) { cut_values_.Resize(that.cut_values_.Size()); cut_ptrs_.Resize(that.cut_ptrs_.Size()); min_vals_.Resize(that.min_vals_.Size()); cut_values_.Copy(that.cut_values_); cut_ptrs_.Copy(that.cut_ptrs_); min_vals_.Copy(that.min_vals_); return *this; } HistogramCuts& operator=(HistogramCuts&& that) noexcept(true) { cut_ptrs_ = std::move(that.cut_ptrs_); cut_values_ = std::move(that.cut_values_); min_vals_ = std::move(that.min_vals_); return *this; } uint32_t FeatureBins(uint32_t feature) const { return cut_ptrs_.ConstHostVector().at(feature + 1) - cut_ptrs_.ConstHostVector()[feature]; } // Getters. Cuts should be of no use after building histogram indices, but currently // it's deeply linked with quantile_hist, gpu sketcher and gpu_hist. So we preserve // these for now. std::vector<uint32_t> const& Ptrs() const { return cut_ptrs_.ConstHostVector(); } std::vector<float> const& Values() const { return cut_values_.ConstHostVector(); } std::vector<float> const& MinValues() const { return min_vals_.ConstHostVector(); } size_t TotalBins() const { return cut_ptrs_.ConstHostVector().back(); } // Return the index of a cut point that is strictly greater than the input // value, or the last available index if none exists BinIdx SearchBin(float value, uint32_t column_id) const { auto beg = cut_ptrs_.ConstHostVector().at(column_id); auto end = cut_ptrs_.ConstHostVector().at(column_id + 1); const auto &values = cut_values_.ConstHostVector(); auto it = std::upper_bound(values.cbegin() + beg, values.cbegin() + end, value); BinIdx idx = it - values.cbegin(); if (idx == end) { idx -= 1; } return idx; } BinIdx SearchBin(Entry const& e) const { return SearchBin(e.fvalue, e.index); } }; inline HistogramCuts SketchOnDMatrix(DMatrix *m, int32_t max_bins) { HistogramCuts out; auto const& info = m->Info(); const auto threads = omp_get_max_threads(); std::vector<std::vector<bst_row_t>> column_sizes(threads); for (auto& column : column_sizes) { column.resize(info.num_col_, 0); } std::vector<bst_row_t> reduced(info.num_col_, 0); for (auto const& page : m->GetBatches<SparsePage>()) { auto const &entries_per_column = HostSketchContainer::CalcColumnSize(page, info.num_col_, threads); for (size_t i = 0; i < entries_per_column.size(); ++i) { reduced[i] += entries_per_column[i]; } } HostSketchContainer container(reduced, max_bins, HostSketchContainer::UseGroup(info)); for (auto const &page : m->GetBatches<SparsePage>()) { container.PushRowPage(page, info); } container.MakeCuts(&out); return out; } enum BinTypeSize { kUint8BinsTypeSize = 1, kUint16BinsTypeSize = 2, kUint32BinsTypeSize = 4 }; struct Index { Index() { SetBinTypeSize(binTypeSize_); } Index(const Index& i) = delete; Index& operator=(Index i) = delete; Index(Index&& i) = delete; Index& operator=(Index&& i) = delete; uint32_t operator[](size_t i) const { if (offset_ptr_ != nullptr) { return func_(data_ptr_, i) + offset_ptr_[i%p_]; } else { return func_(data_ptr_, i); } } void SetBinTypeSize(BinTypeSize binTypeSize) { binTypeSize_ = binTypeSize; switch (binTypeSize) { case kUint8BinsTypeSize: func_ = &GetValueFromUint8; break; case kUint16BinsTypeSize: func_ = &GetValueFromUint16; break; case kUint32BinsTypeSize: func_ = &GetValueFromUint32; break; default: CHECK(binTypeSize == kUint8BinsTypeSize || binTypeSize == kUint16BinsTypeSize || binTypeSize == kUint32BinsTypeSize); } } BinTypeSize GetBinTypeSize() const { return binTypeSize_; } template<typename T> T* data() const { // NOLINT return static_cast<T*>(data_ptr_); } uint32_t* Offset() const { return offset_ptr_; } size_t OffsetSize() const { return offset_.size(); } size_t Size() const { return data_.size() / (binTypeSize_); } void Resize(const size_t nBytesData) { data_.resize(nBytesData); data_ptr_ = reinterpret_cast<void*>(data_.data()); } void ResizeOffset(const size_t nDisps) { offset_.resize(nDisps); offset_ptr_ = offset_.data(); p_ = nDisps; } std::vector<uint8_t>::const_iterator begin() const { // NOLINT return data_.begin(); } std::vector<uint8_t>::const_iterator end() const { // NOLINT return data_.end(); } private: static uint32_t GetValueFromUint8(void *t, size_t i) { return reinterpret_cast<uint8_t*>(t)[i]; } static uint32_t GetValueFromUint16(void* t, size_t i) { return reinterpret_cast<uint16_t*>(t)[i]; } static uint32_t GetValueFromUint32(void* t, size_t i) { return reinterpret_cast<uint32_t*>(t)[i]; } using Func = uint32_t (*)(void*, size_t); std::vector<uint8_t> data_; std::vector<uint32_t> offset_; // size of this field is equal to number of features void* data_ptr_; BinTypeSize binTypeSize_ {kUint8BinsTypeSize}; size_t p_ {1}; uint32_t* offset_ptr_ {nullptr}; Func func_; }; /*! * \brief preprocessed global index matrix, in CSR format * * Transform floating values to integer index in histogram This is a global histogram * index for CPU histogram. On GPU ellpack page is used. */ struct GHistIndexMatrix { /*! \brief row pointer to rows by element position */ std::vector<size_t> row_ptr; /*! \brief The index data */ Index index; /*! \brief hit count of each index */ std::vector<size_t> hit_count; /*! \brief The corresponding cuts */ HistogramCuts cut; DMatrix* p_fmat; size_t max_num_bins; // Create a global histogram matrix, given cut void Init(DMatrix* p_fmat, int max_num_bins); // specific method for sparse data as no posibility to reduce allocated memory template <typename BinIdxType, typename GetOffset> void SetIndexData(common::Span<BinIdxType> index_data_span, size_t batch_threads, const SparsePage &batch, size_t rbegin, size_t nbins, GetOffset get_offset) { const xgboost::Entry *data_ptr = batch.data.HostVector().data(); const std::vector<bst_row_t> &offset_vec = batch.offset.HostVector(); const size_t batch_size = batch.Size(); CHECK_LT(batch_size, offset_vec.size()); BinIdxType* index_data = index_data_span.data(); #pragma omp parallel for num_threads(batch_threads) schedule(static) for (omp_ulong i = 0; i < batch_size; ++i) { const int tid = omp_get_thread_num(); size_t ibegin = row_ptr[rbegin + i]; size_t iend = row_ptr[rbegin + i + 1]; const size_t size = offset_vec[i + 1] - offset_vec[i]; SparsePage::Inst inst = {data_ptr + offset_vec[i], size}; CHECK_EQ(ibegin + inst.size(), iend); for (bst_uint j = 0; j < inst.size(); ++j) { uint32_t idx = cut.SearchBin(inst[j]); index_data[ibegin + j] = get_offset(idx, j); ++hit_count_tloc_[tid * nbins + idx]; } } } void ResizeIndex(const size_t n_index, const bool isDense); inline void GetFeatureCounts(size_t* counts) const { auto nfeature = cut.Ptrs().size() - 1; for (unsigned fid = 0; fid < nfeature; ++fid) { auto ibegin = cut.Ptrs()[fid]; auto iend = cut.Ptrs()[fid + 1]; for (auto i = ibegin; i < iend; ++i) { counts[fid] += hit_count[i]; } } } inline bool IsDense() const { return isDense_; } private: std::vector<size_t> hit_count_tloc_; bool isDense_; }; template <typename GradientIndex> int32_t XGBOOST_HOST_DEV_INLINE BinarySearchBin(bst_uint begin, bst_uint end, GradientIndex const &data, uint32_t const fidx_begin, uint32_t const fidx_end) { uint32_t previous_middle = std::numeric_limits<uint32_t>::max(); while (end != begin) { auto middle = begin + (end - begin) / 2; if (middle == previous_middle) { break; } previous_middle = middle; auto gidx = data[middle]; if (gidx >= fidx_begin && gidx < fidx_end) { return static_cast<int32_t>(gidx); } else if (gidx < fidx_begin) { begin = middle; } else { end = middle; } } // Value is missing return -1; } struct GHistIndexBlock { const size_t* row_ptr; const uint32_t* index; inline GHistIndexBlock(const size_t* row_ptr, const uint32_t* index) : row_ptr(row_ptr), index(index) {} // get i-th row inline GHistIndexRow operator[](size_t i) const { return {&index[0] + row_ptr[i], row_ptr[i + 1] - row_ptr[i]}; } }; class ColumnMatrix; class GHistIndexBlockMatrix { public: void Init(const GHistIndexMatrix& gmat, const ColumnMatrix& colmat, const tree::TrainParam& param); inline GHistIndexBlock operator[](size_t i) const { return {blocks_[i].row_ptr_begin, blocks_[i].index_begin}; } inline size_t GetNumBlock() const { return blocks_.size(); } private: std::vector<size_t> row_ptr_; std::vector<uint32_t> index_; const HistogramCuts* cut_; struct Block { const size_t* row_ptr_begin; const size_t* row_ptr_end; const uint32_t* index_begin; const uint32_t* index_end; }; std::vector<Block> blocks_; }; template<typename GradientSumT> using GHistRow = Span<xgboost::detail::GradientPairInternal<GradientSumT> >; /*! * \brief fill a histogram by zeros */ template<typename GradientSumT> void InitilizeHistByZeroes(GHistRow<GradientSumT> hist, size_t begin, size_t end); /*! * \brief Increment hist as dst += add in range [begin, end) */ template<typename GradientSumT> void IncrementHist(GHistRow<GradientSumT> dst, const GHistRow<GradientSumT> add, size_t begin, size_t end); /*! * \brief Copy hist from src to dst in range [begin, end) */ template<typename GradientSumT> void CopyHist(GHistRow<GradientSumT> dst, const GHistRow<GradientSumT> src, size_t begin, size_t end); /*! * \brief Compute Subtraction: dst = src1 - src2 in range [begin, end) */ template<typename GradientSumT> void SubtractionHist(GHistRow<GradientSumT> dst, const GHistRow<GradientSumT> src1, const GHistRow<GradientSumT> src2, size_t begin, size_t end); /*! * \brief histogram of gradient statistics for multiple nodes */ template<typename GradientSumT> class HistCollection { public: using GHistRowT = GHistRow<GradientSumT>; using GradientPairT = xgboost::detail::GradientPairInternal<GradientSumT>; // access histogram for i-th node GHistRowT operator[](bst_uint nid) const { constexpr uint32_t kMax = std::numeric_limits<uint32_t>::max(); const size_t id = row_ptr_[nid]; CHECK_NE(id, kMax); GradientPairT* ptr = nullptr; if (contiguous_allocation_) { ptr = const_cast<GradientPairT*>(data_[0].data() + nbins_*id); } else { ptr = const_cast<GradientPairT*>(data_[id].data()); } return {ptr, nbins_}; } // have we computed a histogram for i-th node? bool RowExists(bst_uint nid) const { const uint32_t k_max = std::numeric_limits<uint32_t>::max(); return (nid < row_ptr_.size() && row_ptr_[nid] != k_max); } // initialize histogram collection void Init(uint32_t nbins) { if (nbins_ != nbins) { nbins_ = nbins; // quite expensive operation, so let's do this only once data_.clear(); } row_ptr_.clear(); n_nodes_added_ = 0; } // create an empty histogram for i-th node void AddHistRow(bst_uint nid) { constexpr uint32_t kMax = std::numeric_limits<uint32_t>::max(); if (nid >= row_ptr_.size()) { row_ptr_.resize(nid + 1, kMax); } CHECK_EQ(row_ptr_[nid], kMax); if (data_.size() < (nid + 1)) { data_.resize((nid + 1)); } row_ptr_[nid] = n_nodes_added_; n_nodes_added_++; } // allocate thread local memory i-th node void AllocateData(bst_uint nid) { if (data_[row_ptr_[nid]].size() == 0) { data_[row_ptr_[nid]].resize(nbins_, {0, 0}); } } // allocate common buffer contiguously for all nodes, need for single Allreduce call void AllocateAllData() { const size_t new_size = nbins_*data_.size(); contiguous_allocation_ = true; if (data_[0].size() != new_size) { data_[0].resize(new_size); } } private: /*! \brief number of all bins over all features */ uint32_t nbins_ = 0; /*! \brief amount of active nodes in hist collection */ uint32_t n_nodes_added_ = 0; /*! \brief flag to identify contiguous memory allocation */ bool contiguous_allocation_ = false; std::vector<std::vector<GradientPairT>> data_; /*! \brief row_ptr_[nid] locates bin for histogram of node nid */ std::vector<size_t> row_ptr_; }; /*! * \brief Stores temporary histograms to compute them in parallel * Supports processing multiple tree-nodes for nested parallelism * Able to reduce histograms across threads in efficient way */ template<typename GradientSumT> class ParallelGHistBuilder { public: using GHistRowT = GHistRow<GradientSumT>; void Init(size_t nbins) { if (nbins != nbins_) { hist_buffer_.Init(nbins); nbins_ = nbins; } } // Add new elements if needed, mark all hists as unused // targeted_hists - already allocated hists which should contain final results after Reduce() call void Reset(size_t nthreads, size_t nodes, const BlockedSpace2d& space, const std::vector<GHistRowT>& targeted_hists) { hist_buffer_.Init(nbins_); tid_nid_to_hist_.clear(); threads_to_nids_map_.clear(); targeted_hists_ = targeted_hists; CHECK_EQ(nodes, targeted_hists.size()); nodes_ = nodes; nthreads_ = nthreads; MatchThreadsToNodes(space); AllocateAdditionalHistograms(); MatchNodeNidPairToHist(); hist_was_used_.resize(nthreads * nodes_); std::fill(hist_was_used_.begin(), hist_was_used_.end(), static_cast<int>(false)); } // Get specified hist, initialize hist by zeros if it wasn't used before GHistRowT GetInitializedHist(size_t tid, size_t nid) { CHECK_LT(nid, nodes_); CHECK_LT(tid, nthreads_); int idx = tid_nid_to_hist_.at({tid, nid}); if (idx >= 0) { hist_buffer_.AllocateData(idx); } GHistRowT hist = idx == -1 ? targeted_hists_[nid] : hist_buffer_[idx]; if (!hist_was_used_[tid * nodes_ + nid]) { InitilizeHistByZeroes(hist, 0, hist.size()); hist_was_used_[tid * nodes_ + nid] = static_cast<int>(true); } return hist; } // Reduce following bins (begin, end] for nid-node in dst across threads void ReduceHist(size_t nid, size_t begin, size_t end) { CHECK_GT(end, begin); CHECK_LT(nid, nodes_); GHistRowT dst = targeted_hists_[nid]; bool is_updated = false; for (size_t tid = 0; tid < nthreads_; ++tid) { if (hist_was_used_[tid * nodes_ + nid]) { is_updated = true; int idx = tid_nid_to_hist_.at({tid, nid}); GHistRowT src = idx == -1 ? targeted_hists_[nid] : hist_buffer_[idx]; if (dst.data() != src.data()) { IncrementHist(dst, src, begin, end); } } } if (!is_updated) { // In distributed mode - some tree nodes can be empty on local machines, // So we need just set local hist by zeros in this case InitilizeHistByZeroes(dst, begin, end); } } protected: void MatchThreadsToNodes(const BlockedSpace2d& space) { const size_t space_size = space.Size(); const size_t chunck_size = space_size / nthreads_ + !!(space_size % nthreads_); threads_to_nids_map_.resize(nthreads_ * nodes_, false); for (size_t tid = 0; tid < nthreads_; ++tid) { size_t begin = chunck_size * tid; size_t end = std::min(begin + chunck_size, space_size); if (begin < space_size) { size_t nid_begin = space.GetFirstDimension(begin); size_t nid_end = space.GetFirstDimension(end-1); for (size_t nid = nid_begin; nid <= nid_end; ++nid) { // true - means thread 'tid' will work to compute partial hist for node 'nid' threads_to_nids_map_[tid * nodes_ + nid] = true; } } } } void AllocateAdditionalHistograms() { size_t hist_allocated_additionally = 0; for (size_t nid = 0; nid < nodes_; ++nid) { int nthreads_for_nid = 0; for (size_t tid = 0; tid < nthreads_; ++tid) { if (threads_to_nids_map_[tid * nodes_ + nid]) { nthreads_for_nid++; } } // In distributed mode - some tree nodes can be empty on local machines, // set nthreads_for_nid to 0 in this case. // In another case - allocate additional (nthreads_for_nid - 1) histograms, // because one is already allocated externally (will store final result for the node). hist_allocated_additionally += std::max<int>(0, nthreads_for_nid - 1); } for (size_t i = 0; i < hist_allocated_additionally; ++i) { hist_buffer_.AddHistRow(i); } } void MatchNodeNidPairToHist() { size_t hist_allocated_additionally = 0; for (size_t nid = 0; nid < nodes_; ++nid) { bool first_hist = true; for (size_t tid = 0; tid < nthreads_; ++tid) { if (threads_to_nids_map_[tid * nodes_ + nid]) { if (first_hist) { tid_nid_to_hist_[{tid, nid}] = -1; first_hist = false; } else { tid_nid_to_hist_[{tid, nid}] = hist_allocated_additionally++; } } } } } /*! \brief number of bins in each histogram */ size_t nbins_ = 0; /*! \brief number of threads for parallel computation */ size_t nthreads_ = 0; /*! \brief number of nodes which will be processed in parallel */ size_t nodes_ = 0; /*! \brief Buffer for additional histograms for Parallel processing */ HistCollection<GradientSumT> hist_buffer_; /*! * \brief Marks which hists were used, it means that they should be merged. * Contains only {true or false} values * but 'int' is used instead of 'bool', because std::vector<bool> isn't thread safe */ std::vector<int> hist_was_used_; /*! \brief Buffer for additional histograms for Parallel processing */ std::vector<bool> threads_to_nids_map_; /*! \brief Contains histograms for final results */ std::vector<GHistRowT> targeted_hists_; /*! * \brief map pair {tid, nid} to index of allocated histogram from hist_buffer_ and targeted_hists_, * -1 is reserved for targeted_hists_ */ std::map<std::pair<size_t, size_t>, int> tid_nid_to_hist_; }; /*! * \brief builder for histograms of gradient statistics */ template<typename GradientSumT> class GHistBuilder { public: using GHistRowT = GHistRow<GradientSumT>; GHistBuilder() = default; GHistBuilder(size_t nthread, uint32_t nbins) : nthread_{nthread}, nbins_{nbins} {} // construct a histogram via histogram aggregation void BuildHist(const std::vector<GradientPair>& gpair, const RowSetCollection::Elem row_indices, const GHistIndexMatrix& gmat, GHistRowT hist, bool isDense); // same, with feature grouping void BuildBlockHist(const std::vector<GradientPair>& gpair, const RowSetCollection::Elem row_indices, const GHistIndexBlockMatrix& gmatb, GHistRowT hist); // construct a histogram via subtraction trick void SubtractionTrick(GHistRowT self, GHistRowT sibling, GHistRowT parent); uint32_t GetNumBins() const { return nbins_; } private: /*! \brief number of threads for parallel computation */ size_t nthread_ { 0 }; /*! \brief number of all bins over all features */ uint32_t nbins_ { 0 }; }; } // namespace common } // namespace xgboost #endif // XGBOOST_COMMON_HIST_UTIL_H_
kmp_doacross_check.c
// RUN: %libomp-compile-and-run // UNSUPPORTED: gcc // This test is incompatible with gcc because of the explicit call to // __kmpc_doacross_fini(). gcc relies on an implicit call to this function // when the last iteration is executed inside the GOMP_loop_*_next() functions. // Hence, in gcc, having the explicit call leads to __kmpc_doacross_fini() // being called twice. #include <stdio.h> #define N 1000 struct dim { long long lo; // lower long long up; // upper long long st; // stride }; extern void __kmpc_doacross_init(void*, int, int, struct dim *); extern void __kmpc_doacross_wait(void*, int, long long*); extern void __kmpc_doacross_post(void*, int, long long*); extern void __kmpc_doacross_fini(void*, int); extern int __kmpc_global_thread_num(void*); int main() { int i; int iter[N]; struct dim dims; for( i = 0; i < N; ++i ) iter[i] = 1; dims.lo = 1; dims.up = N-1; dims.st = 1; #pragma omp parallel num_threads(4) { int i, gtid; long long vec; gtid = __kmpc_global_thread_num(NULL); __kmpc_doacross_init(NULL,gtid,1,&dims); // thread starts the loop #pragma omp for nowait schedule(dynamic) for( i = 1; i < N; ++i ) { // runtime call corresponding to #pragma omp ordered depend(sink:i-1) vec=i-1; __kmpc_doacross_wait(NULL,gtid,&vec); // user's code iter[i] = iter[i-1] + 1; // runtime call corresponding to #pragma omp ordered depend(source) vec=i; __kmpc_doacross_post(NULL,gtid,&vec); } // thread finishes the loop (should be before the loop barrier) __kmpc_doacross_fini(NULL,gtid); } if( iter[N-1] == N ) { printf("passed\n"); } else { printf("failed %d != %d\n", iter[N-1], N); return 1; } return 0; }
adagrad_op.h
#pragma once #include "caffe2/core/operator.h" namespace caffe2 { template <typename Context> void adagrad_update( int N, const float* g, const float* h, float* ng, float* nh, float epsilon, const float* lr, Context* context) { // TODO(cxj): use OMP when it is reliable // #pragma omp parallel for for (auto i = 0; i < N; ++i) { float gi = g[i]; float hi = nh[i] = h[i] + gi * gi; ng[i] = lr[0] * gi / (std::sqrt(hi) + epsilon); } } template <typename Context> void adagrad_compute( int N, const float* w, const float* g, const float* h, float* nw, float* nh, float epsilon, float lr, Context* context) { for (auto i = 0; i < N; ++i) { float gi = g[i]; float hi = nh[i] = h[i] + gi * gi; nw[i] = w[i] + lr * gi / (std::sqrt(hi) + epsilon); } } template <typename T, class Context> class AdagradOp final : public Operator<Context> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; AdagradOp(const OperatorDef& operator_def, Workspace* ws) : Operator<Context>(operator_def, ws), epsilon_(OperatorBase::GetSingleArgument<float>("epsilon", 1e-5)) {} bool RunOnDevice() override { CAFFE_ENFORCE(Input(GRAD).size() == Input(MOMENT_1).size()); CAFFE_ENFORCE(Input(GRAD).size() == Input(PARAM).size()); Output(OUTPUT_PARAM)->ResizeLike(Input(PARAM)); Output(OUTPUT_MOMENT_1)->ResizeLike(Input(MOMENT_1)); adagrad_compute<Context>( Input(GRAD).size(), Input(PARAM).template data<T>(), Input(GRAD).template data<T>(), Input(MOMENT_1).template data<T>(), Output(OUTPUT_PARAM)->template mutable_data<T>(), Output(OUTPUT_MOMENT_1)->template mutable_data<T>(), epsilon_, Input(LR).template data<T>()[0], &context_); return true; } protected: T epsilon_; INPUT_TAGS(PARAM, MOMENT_1, GRAD, LR); OUTPUT_TAGS(OUTPUT_PARAM, OUTPUT_MOMENT_1); }; template <typename T, class Context> class SparseAdagradOp final : public Operator<Context> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; SparseAdagradOp(const OperatorDef& operator_def, Workspace* ws) : Operator<Context>(operator_def, ws), epsilon_(OperatorBase::GetSingleArgument<float>("epsilon", 1e-5)) {} bool RunOnDevice() override { return DispatchHelper<TensorTypes<int32_t, int64_t>>::call( this, Input(INDICES)); } template <typename SIndex> bool DoRunWithType() { const auto* lr = Input(LR).template data<T>(); Output(OUTPUT_PARAM)->ResizeLike(Input(PARAM)); Output(OUTPUT_MOMENT_1)->ResizeLike(Input(MOMENT_1)); auto n = Input(GRAD).dim(0); const auto* indices = Input(INDICES).template data<SIndex>(); const auto* gradIn = Input(GRAD).template data<T>(); const auto* paramIn = Input(PARAM).template data<T>(); const auto* momentIn = Input(MOMENT_1).template data<T>(); auto* paramOut = Output(OUTPUT_PARAM)->template mutable_data<T>(); auto* momentOut = Output(OUTPUT_MOMENT_1)->template mutable_data<T>(); if (n == 0) { return true; } auto block_size = Input(GRAD).size_from_dim(1); for (auto i = 0; i < n; ++i) { auto idx = indices[i]; if (block_size == 1) { float gi = gradIn[i]; float hi = momentOut[idx] = momentIn[idx] + gi * gi; paramOut[idx] = paramIn[idx] + lr[0] * gi / (std::sqrt(hi) + epsilon_); } else { auto offsetI = i * block_size; auto offsetIdx = idx * block_size; adagrad_compute( block_size, paramIn + offsetIdx, gradIn + offsetI, momentIn + offsetIdx, paramOut + offsetIdx, momentOut + offsetIdx, epsilon_, lr[0], &context_); } } return true; } protected: T epsilon_; INPUT_TAGS(PARAM, MOMENT_1, INDICES, GRAD, LR); OUTPUT_TAGS(OUTPUT_PARAM, OUTPUT_MOMENT_1); }; }
GB_binop__plus_uint32.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__plus_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__plus_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__plus_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__plus_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__plus_uint32) // A*D function (colscale): GB (_AxD__plus_uint32) // D*A function (rowscale): GB (_DxB__plus_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__plus_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__plus_uint32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__plus_uint32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__plus_uint32) // C=scalar+B GB (_bind1st__plus_uint32) // C=scalar+B' GB (_bind1st_tran__plus_uint32) // C=A+scalar GB (_bind2nd__plus_uint32) // C=A'+scalar GB (_bind2nd_tran__plus_uint32) // C type: uint32_t // A type: uint32_t // A pattern? 0 // B type: uint32_t // B pattern? 0 // 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) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint32_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) \ 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_PLUS || GxB_NO_UINT32 || GxB_NO_PLUS_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__plus_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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__plus_uint32) ( 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__plus_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__plus_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__plus_uint32) ( 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 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__plus_uint32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, 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, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__plus_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 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) ; uint32_t alpha_scalar ; uint32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ; beta_scalar = (*((uint32_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__plus_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_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__plus_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_04__plus_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_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__plus_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__plus_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__plus_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__plus_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__plus_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
hello.c
#include <stdio.h> #include <omp.h> int main() { #pragma omp parallel { int ID = omp_get_thread_num(); printf("hello(%d)", ID); printf(" world(%d)\n", ID); } }
GB_unop__sqrt_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__sqrt_fc64_fc64) // op(A') function: GB (_unop_tran__sqrt_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = csqrt (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = csqrt (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = csqrt (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_SQRT || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__sqrt_fc64_fc64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = csqrt (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = csqrt (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__sqrt_fc64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
red_kernel.h
#pragma omp target teams distribute parallel for collapse(2) thread_limit(BLOCK_SIZE) for (int col = 1; col < NUM+1; col++) { for (int row = 1; row < NUM/2+1; row++) { int NUM_2 = NUM >> 1; Real p_ij = pres_red(col, row); Real p_im1j = pres_black(col - 1, row); Real p_ip1j = pres_black(col + 1, row); Real p_ijm1 = pres_black(col, row - (col & 1)); Real p_ijp1 = pres_black(col, row + ((col + 1) & 1)); // right-hand side Real rhs = (((F(col, (2 * row) - (col & 1)) - F(col - 1, (2 * row) - (col & 1))) / dx) + ((G(col, (2 * row) - (col & 1)) - G(col, (2 * row) - (col & 1) - 1)) / dy)) / dt; pres_red(col, row) = p_ij * (ONE - omega) + omega * (((p_ip1j + p_im1j) / (dx * dx)) + ((p_ijp1 + p_ijm1) / (dy * dy)) - rhs) / ((TWO / (dx * dx)) + (TWO / (dy * dy))); } }
if-2.c
/* { dg-do compile } */ /* { dg-options "-fopenmp" } */ void foo (int a, int b, int *p, int *q, int task) { int i; #pragma omp parallel if (a) if (b) /* { dg-error "too many .if. clauses without modifier" } */ ; #pragma omp parallel if (a) if (parallel: b) /* { dg-error "if any .if. clause has modifier, then all .if. clauses have to use modifier" } */ ; #pragma omp parallel if (parallel: a) if (b) /* { dg-error "if any .if. clause has modifier, then all .if. clauses have to use modifier" } */ ; #pragma omp parallel if (parallel:a) if (parallel:a) /* { dg-error "too many .if. clauses with .parallel. modifier" } */ ; #pragma omp parallel if (task:a) /* { dg-error "expected .parallel. .if. clause modifier rather than .task." } */ \ if (taskloop: b) /* { dg-error "expected .parallel. .if. clause modifier rather than .taskloop." } */ ; #pragma omp parallel if (target update:a) /* { dg-error "expected .parallel. .if. clause modifier rather than .target update." } */ ; #pragma omp parallel for simd if (target update: a) /* { dg-error "expected .parallel. .if. clause modifier rather than .target update." } */ for (i = 0; i < 16; i++) ; #pragma omp task if (task) ; #pragma omp task if (task: task) ; #pragma omp task if (parallel: a) /* { dg-error "expected .task. .if. clause modifier rather than .parallel." } */ ; #pragma omp taskloop if (task : a) /* { dg-error "expected .taskloop. .if. clause modifier rather than .task." } */ for (i = 0; i < 16; i++) ; #pragma omp target if (taskloop: a) /* { dg-error "expected .target. .if. clause modifier rather than .taskloop." } */ ; #pragma omp target teams distribute parallel for simd if (target exit data : a) /* { dg-error "expected .parallel. or .target. .if. clause modifier" } */ for (i = 0; i < 16; i++) ; #pragma omp target data if (target: a) map (p[0:2]) /* { dg-error "expected .target data. .if. clause modifier rather than .target." } */ ; #pragma omp target enter data if (target data: a) map (to: p[0:2]) /* { dg-error "expected .target enter data. .if. clause modifier rather than .target data." } */ #pragma omp target exit data if (target enter data: a) map (from: p[0:2]) /* { dg-error "expected .target exit data. .if. clause modifier rather than .target enter data." } */ #pragma omp target update if (target exit data:a) to (q[0:3]) /* { dg-error "expected .target update. .if. clause modifier rather than .target exit data." } */ }
mpiCodeGenerator.h
/* * * * V 0.2 using real frontend parser and dedicated OpenMP-like AST nodes for program representation * This is necessary to parse complex extended map clause with dist_data info. * The previous version's MPI_PragmaAttribute is no longer used. * * Liao 12/11/2015 * * V 0.1 * Parsing pragmas and generating MPI code from input sequential code * Pragma is OpenMP style, reusing OmpAttribute to store information * As a experiments, a lightweight recursive descendent parser is used to parse the pragmas * Liao 9/22/2015 * */ #ifndef MPI_Code_Generator_h #define MPI_Code_Generator_h #include <vector> #include <string> namespace MPI_Code_Generator { //------------ v 0.2 interface, expecting the extended ROSE frontend to parse and create OpenMP AST nodes // using -rose:openmp:ast_only command line option to active the frontend support void lower_xomp (SgSourceFile* file); //! Translate target device(mpi:master) begin ... void transMPIDeviceMaster (SgOmpTargetStatement * t_stmt); void transOmpTargetParallelLoop (SgOmpForStatement* loop); //! Translate mapped scalars and arrays, return a reference distributed local array portion size, used for loop bound later. SgVariableDeclaration* transOmpMapVariables (SgOmpTargetStatement* ); //! Translate a loop affected void transForLoop (SgForStatement* for_stmt, SgVariableDeclaration* local_size_decl); // convert a C data type into MPI type name std::string C2MPITypeName (SgType*); //! Create MPI_Bcast() function call for a single variable SgExprStatement* buildMPI_Bcast(SgVariableSymbol* var_sym, int source_rank_id, SgScopeStatement* insertion_scope); //! Create MPI_Barrier (); SgExprStatement* buildMPI_Barrier(SgScopeStatement* insertion_scope); //--------------- v 0.1 interface, no longer being used. class MPI_PragmaAttribute; //int generateMPI (SgSourceFile* sfile); //! A prototype parser for directives guiding MPI code generation void parsePragmas(SgSourceFile* sfile, std::vector <MPI_PragmaAttribute*>& MPI_Pragma_Attribute_List); //! Translate generated Pragma Attributes void translatePragmas (std::vector <MPI_PragmaAttribute*>& MPI_Pragma_Attribute_List); //! Setup MPI initialization void setupMPIInit(SgSourceFile* sfile); //! Setup MPI finalize void setupMPIFinalize(SgSourceFile* sfile); // pragma enum values. // For quick prototyping, we use AstAttributes instead of dedicated AST nodes for storing parsed results. enum mpi_pragma_enum { // for main function, what is the default semantics for code if no directives are present ? // run by all processes (spmd) vs. run only by master process, or must be explicitly declared ( device (mpi:all)) // #pragma omp mpi_device_default(mpi:all|mpi:master|explicit) e_mpi_all, e_mpi_master, e_semantics_explicit, //#pragma omp mpi_device_default(mpi:all|mpi:master|explicit) pragma_mpi_device_default, //#pragma omp target device(mpi:all) begin pragma_mpi_device_all_begin, //#pragma omp target device(mpi:all) end pragma_mpi_device_all_end, // #pragma omp target device(mpi:master) begin pragma_mpi_device_master_begin, // #pragma omp target device(mpi:master) end pragma_mpi_device_master_end, // pragma omp target device(mpi:all) map ( dist_data) pragma_mpi_device_all_map_dist, //#pragma omp parallel for pragma_parallel_for, pragma_last }; // Global settings for the code generation extern mpi_pragma_enum mpi_device_default_choice; class MPI_PragmaAttribute: public AstAttribute { public: SgPragmaDeclaration* pragma_node; // the associated AST node for pragma enum mpi_pragma_enum pragma_type; enum mpi_pragma_enum default_semantics; MPI_PragmaAttribute (SgPragmaDeclaration* n , mpi_pragma_enum p_type): pragma_node(n), pragma_type(p_type) { default_semantics = e_semantics_explicit; } // convert the attribute back to string format std::string toString(); }; // end class // parse a single pragma declaration, internal use only extern AstAttribute* parse_MPI_Pragma (SgPragmaDeclaration* pragmaDecl); // parse pragmas in an input file void parsePragmas(SgSourceFile* sfile); } // end namespace #endif //MPI_Code_Generator_h
blas.c
#include "blas.h" #include "utils.h" #include <math.h> #include <assert.h> #include <float.h> #include <stdio.h> #include <stdlib.h> #include <string.h> void reorg_cpu(float *x, int out_w, int out_h, int out_c, int batch, int stride, int forward, float *out) { int b,i,j,k; int in_c = out_c/(stride*stride); //printf("\n out_c = %d, out_w = %d, out_h = %d, stride = %d, forward = %d \n", out_c, out_w, out_h, stride, forward); //printf(" in_c = %d, in_w = %d, in_h = %d \n", in_c, out_w*stride, out_h*stride); for(b = 0; b < batch; ++b){ for(k = 0; k < out_c; ++k){ for(j = 0; j < out_h; ++j){ for(i = 0; i < out_w; ++i){ int in_index = i + out_w*(j + out_h*(k + out_c*b)); int c2 = k % in_c; int offset = k / in_c; int w2 = i*stride + offset % stride; int h2 = j*stride + offset / stride; int out_index = w2 + out_w*stride*(h2 + out_h*stride*(c2 + in_c*b)); if(forward) out[out_index] = x[in_index]; // used by default for forward (i.e. forward = 0) else out[in_index] = x[out_index]; } } } } } void flatten(float *x, int size, int layers, int batch, int forward) { float* swap = (float*)xcalloc(size * layers * batch, sizeof(float)); int i,c,b; for(b = 0; b < batch; ++b){ for(c = 0; c < layers; ++c){ for(i = 0; i < size; ++i){ int i1 = b*layers*size + c*size + i; int i2 = b*layers*size + i*layers + c; if (forward) swap[i2] = x[i1]; else swap[i1] = x[i2]; } } } memcpy(x, swap, size*layers*batch*sizeof(float)); free(swap); } void weighted_sum_cpu(float *a, float *b, float *s, int n, float *c) { int i; for(i = 0; i < n; ++i){ c[i] = s[i]*a[i] + (1-s[i])*(b ? b[i] : 0); } } void weighted_delta_cpu(float *a, float *b, float *s, float *da, float *db, float *ds, int n, float *dc) { int i; for(i = 0; i < n; ++i){ if(da) da[i] += dc[i] * s[i]; if(db) db[i] += dc[i] * (1-s[i]); ds[i] += dc[i] * (a[i] - b[i]); } } static float relu(float src) { if (src > 0) return src; return 0; } void shortcut_multilayer_cpu(int size, int src_outputs, int batch, int n, int *outputs_of_layers, float **layers_output, float *out, float *in, float *weights, int nweights, WEIGHTS_NORMALIZATION_T weights_normalization) { // nweights - l.n or l.n*l.c or (l.n*l.c*l.h*l.w) const int layer_step = nweights / (n + 1); // 1 or l.c or (l.c * l.h * l.w) int step = 0; if (nweights > 0) step = src_outputs / layer_step; // (l.c * l.h * l.w) or (l.w*l.h) or 1 int id; #pragma omp parallel for for (id = 0; id < size; ++id) { int src_id = id; const int src_i = src_id % src_outputs; src_id /= src_outputs; int src_b = src_id; float sum = 1, max_val = -FLT_MAX; int i; if (weights && weights_normalization) { if (weights_normalization == SOFTMAX_NORMALIZATION) { for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] float w = weights[weights_index]; if (max_val < w) max_val = w; } } const float eps = 0.0001; sum = eps; for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] const float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) sum += relu(w); else if (weights_normalization == SOFTMAX_NORMALIZATION) sum += expf(w - max_val); } } if (weights) { float w = weights[src_i / step]; if (weights_normalization == RELU_NORMALIZATION) w = relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) w = expf(w - max_val) / sum; out[id] = in[id] * w; // [0 or c or (c, h ,w)] } else out[id] = in[id]; // layers for (i = 0; i < n; ++i) { int add_outputs = outputs_of_layers[i]; if (src_i < add_outputs) { int add_index = add_outputs*src_b + src_i; int out_index = id; float *add = layers_output[i]; if (weights) { const int weights_index = src_i / step + (i + 1)*layer_step; // [0 or c or (c, h ,w)] float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) w = relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) w = expf(w - max_val) / sum; out[out_index] += add[add_index] * w; // [0 or c or (c, h ,w)] } else out[out_index] += add[add_index]; } } } } void backward_shortcut_multilayer_cpu(int size, int src_outputs, int batch, int n, int *outputs_of_layers, float **layers_delta, float *delta_out, float *delta_in, float *weights, float *weight_updates, int nweights, float *in, float **layers_output, WEIGHTS_NORMALIZATION_T weights_normalization) { // nweights - l.n or l.n*l.c or (l.n*l.c*l.h*l.w) const int layer_step = nweights / (n + 1); // 1 or l.c or (l.c * l.h * l.w) int step = 0; if (nweights > 0) step = src_outputs / layer_step; // (l.c * l.h * l.w) or (l.w*l.h) or 1 int id; #pragma omp parallel for for (id = 0; id < size; ++id) { int src_id = id; int src_i = src_id % src_outputs; src_id /= src_outputs; int src_b = src_id; float grad = 1, sum = 1, max_val = -FLT_MAX;; int i; if (weights && weights_normalization) { if (weights_normalization == SOFTMAX_NORMALIZATION) { for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] float w = weights[weights_index]; if (max_val < w) max_val = w; } } const float eps = 0.0001; sum = eps; for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] const float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) sum += relu(w); else if (weights_normalization == SOFTMAX_NORMALIZATION) sum += expf(w - max_val); } /* grad = 0; for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] const float delta_w = delta_in[id] * in[id]; const float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) grad += delta_w * relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) grad += delta_w * expf(w - max_val) / sum; } */ } if (weights) { float w = weights[src_i / step]; if (weights_normalization == RELU_NORMALIZATION) w = relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) w = expf(w - max_val) / sum; delta_out[id] += delta_in[id] * w; // [0 or c or (c, h ,w)] weight_updates[src_i / step] += delta_in[id] * in[id] * grad; } else delta_out[id] += delta_in[id]; // layers for (i = 0; i < n; ++i) { int add_outputs = outputs_of_layers[i]; if (src_i < add_outputs) { int add_index = add_outputs*src_b + src_i; int out_index = id; float *layer_delta = layers_delta[i]; if (weights) { float *add = layers_output[i]; const int weights_index = src_i / step + (i + 1)*layer_step; // [0 or c or (c, h ,w)] float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) w = relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) w = expf(w - max_val) / sum; layer_delta[add_index] += delta_in[id] * w; // [0 or c or (c, h ,w)] weight_updates[weights_index] += delta_in[id] * add[add_index] * grad; } else layer_delta[add_index] += delta_in[id]; } } } } void shortcut_cpu(int batch, int w1, int h1, int c1, float *add, int w2, int h2, int c2, float *out) { int stride = w1/w2; int sample = w2/w1; assert(stride == h1/h2); assert(sample == h2/h1); if(stride < 1) stride = 1; if(sample < 1) sample = 1; int minw = (w1 < w2) ? w1 : w2; int minh = (h1 < h2) ? h1 : h2; int minc = (c1 < c2) ? c1 : c2; int i,j,k,b; for(b = 0; b < batch; ++b){ for(k = 0; k < minc; ++k){ for(j = 0; j < minh; ++j){ for(i = 0; i < minw; ++i){ int out_index = i*sample + w2*(j*sample + h2*(k + c2*b)); int add_index = i*stride + w1*(j*stride + h1*(k + c1*b)); out[out_index] += add[add_index]; } } } } } void mean_cpu(float *x, int batch, int filters, int spatial, float *mean) { float scale = 1./(batch * spatial); int i,j,k; for(i = 0; i < filters; ++i){ mean[i] = 0; for(j = 0; j < batch; ++j){ for(k = 0; k < spatial; ++k){ int index = j*filters*spatial + i*spatial + k; mean[i] += x[index]; } } mean[i] *= scale; } } void variance_cpu(float *x, float *mean, int batch, int filters, int spatial, float *variance) { float scale = 1./(batch * spatial - 1); int i,j,k; for(i = 0; i < filters; ++i){ variance[i] = 0; for(j = 0; j < batch; ++j){ for(k = 0; k < spatial; ++k){ int index = j*filters*spatial + i*spatial + k; variance[i] += pow((x[index] - mean[i]), 2); } } variance[i] *= scale; } } void normalize_cpu(float *x, float *mean, float *variance, int batch, int filters, int spatial) { int b, f, i; for(b = 0; b < batch; ++b){ for(f = 0; f < filters; ++f){ for(i = 0; i < spatial; ++i){ int index = b*filters*spatial + f*spatial + i; x[index] = (x[index] - mean[f])/(sqrt(variance[f] + .000001f)); } } } } void const_cpu(int N, float ALPHA, float *X, int INCX) { int i; for(i = 0; i < N; ++i) X[i*INCX] = ALPHA; } void mul_cpu(int N, float *X, int INCX, float *Y, int INCY) { int i; for(i = 0; i < N; ++i) Y[i*INCY] *= X[i*INCX]; } void pow_cpu(int N, float ALPHA, float *X, int INCX, float *Y, int INCY) { int i; for(i = 0; i < N; ++i) Y[i*INCY] = pow(X[i*INCX], ALPHA); } void axpy_cpu(int N, float ALPHA, float *X, int INCX, float *Y, int INCY) { int i; for(i = 0; i < N; ++i) Y[i*INCY] += ALPHA*X[i*INCX]; } void scal_cpu(int N, float ALPHA, float *X, int INCX) { int i; for(i = 0; i < N; ++i) X[i*INCX] *= ALPHA; } void scal_add_cpu(int N, float ALPHA, float BETA, float *X, int INCX) { int i; for (i = 0; i < N; ++i) X[i*INCX] = X[i*INCX] * ALPHA + BETA; } void fill_cpu(int N, float ALPHA, float *X, int INCX) { int i; if (INCX == 1 && ALPHA == 0) { memset(X, 0, N * sizeof(float)); } else { for (i = 0; i < N; ++i) X[i*INCX] = ALPHA; } } void deinter_cpu(int NX, float *X, int NY, float *Y, int B, float *OUT) { int i, j; int index = 0; for(j = 0; j < B; ++j) { for(i = 0; i < NX; ++i){ if(X) X[j*NX + i] += OUT[index]; ++index; } for(i = 0; i < NY; ++i){ if(Y) Y[j*NY + i] += OUT[index]; ++index; } } } void inter_cpu(int NX, float *X, int NY, float *Y, int B, float *OUT) { int i, j; int index = 0; for(j = 0; j < B; ++j) { for(i = 0; i < NX; ++i){ OUT[index++] = X[j*NX + i]; } for(i = 0; i < NY; ++i){ OUT[index++] = Y[j*NY + i]; } } } void copy_cpu(int N, float *X, int INCX, float *Y, int INCY) { int i; for(i = 0; i < N; ++i) Y[i*INCY] = X[i*INCX]; } void mult_add_into_cpu(int N, float *X, float *Y, float *Z) { int i; for(i = 0; i < N; ++i) Z[i] += X[i]*Y[i]; } void smooth_l1_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float diff = truth[i] - pred[i]; float abs_val = fabs(diff); if(abs_val < 1) { error[i] = diff * diff; delta[i] = diff; } else { error[i] = 2*abs_val - 1; delta[i] = (diff > 0) ? 1 : -1; } } } void l1_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float diff = truth[i] - pred[i]; error[i] = fabs(diff); delta[i] = diff > 0 ? 1 : -1; } } void softmax_x_ent_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float t = truth[i]; float p = pred[i]; error[i] = (t) ? -log(p) : 0; delta[i] = t-p; } } void logistic_x_ent_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float t = truth[i]; float p = pred[i]; error[i] = -t*log(p) - (1-t)*log(1-p); delta[i] = t-p; } } void l2_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float diff = truth[i] - pred[i]; error[i] = diff * diff; delta[i] = diff; } } float dot_cpu(int N, float *X, int INCX, float *Y, int INCY) { int i; float dot = 0; for(i = 0; i < N; ++i) dot += X[i*INCX] * Y[i*INCY]; return dot; } void softmax(float *input, int n, float temp, float *output, int stride) { int i; float sum = 0; float largest = -FLT_MAX; for(i = 0; i < n; ++i){ if(input[i*stride] > largest) largest = input[i*stride]; } for(i = 0; i < n; ++i){ float e = exp(input[i*stride]/temp - largest/temp); sum += e; output[i*stride] = e; } for(i = 0; i < n; ++i){ output[i*stride] /= sum; } } void softmax_cpu(float *input, int n, int batch, int batch_offset, int groups, int group_offset, int stride, float temp, float *output) { int g, b; for(b = 0; b < batch; ++b){ for(g = 0; g < groups; ++g){ softmax(input + b*batch_offset + g*group_offset, n, temp, output + b*batch_offset + g*group_offset, stride); } } } void upsample_cpu(float *in, int w, int h, int c, int batch, int stride, int forward, float scale, float *out) { int i, j, k, b; for (b = 0; b < batch; ++b) { for (k = 0; k < c; ++k) { for (j = 0; j < h*stride; ++j) { for (i = 0; i < w*stride; ++i) { int in_index = b*w*h*c + k*w*h + (j / stride)*w + i / stride; int out_index = b*w*h*c*stride*stride + k*w*h*stride*stride + j*w*stride + i; if (forward) out[out_index] = scale*in[in_index]; else in[in_index] += scale*out[out_index]; } } } } } void constrain_cpu(int size, float ALPHA, float *X) { int i; for (i = 0; i < size; ++i) { X[i] = fminf(ALPHA, fmaxf(-ALPHA, X[i])); } } void fix_nan_and_inf_cpu(float *input, size_t size) { int i; for (i = 0; i < size; ++i) { float val = input[i]; if (isnan(val) || isinf(val)) input[i] = 1.0f / i; // pseudo random value } } // Euclidean_norm float math_vector_length(float *A, unsigned int feature_size) { float sum = 0; int i; for (i = 0; i < feature_size; ++i) { sum += A[i] * A[i]; } float vector_length = sqrtf(sum); return vector_length; } float cosine_similarity(float *A, float *B, unsigned int feature_size) { float mul = 0.0, d_a = 0.0, d_b = 0.0; int i; for(i = 0; i < feature_size; ++i) { mul += A[i] * B[i]; d_a += A[i] * A[i]; d_b += B[i] * B[i]; } float similarity; float divider = sqrtf(d_a) * sqrtf(d_b); if (divider > 0) similarity = mul / divider; else similarity = 0; return similarity; } // num_of_samples = 2 * loaded_images = mini_batch_size float P_constrastive(int i, int l, int *labels, int num_of_samples, float **z, unsigned int feature_size, float temperature, float *cos_sim) { if (i == l) { fprintf(stderr, " Error: in P_constrastive must be i != l, while i = %d, l = %d \n", i, l); getchar(); } const float sim = cos_sim[i*num_of_samples + l]; // cosine_similarity(z[i], z[l], feature_size); const float numerator = expf(sim / temperature); float denominator = 0; int k; for (k = 0; k < num_of_samples; ++k) { //if (k != i && labels[k] != labels[i]) { if (k != i) { const float sim_den = cos_sim[k*num_of_samples + l]; // cosine_similarity(z[k], z[l], feature_size); denominator += expf(sim_den / temperature); } } float result = numerator / denominator; return result; } // i - id of the current sample in mini_batch // labels[num_of_samples] - array with class_id for each sample in the current mini_batch // z[feature_size][num_of_samples] - array of arrays with contrastive features (output of conv-layer, f.e. 128 floats for each sample) // delta[feature_size] - array with deltas for backpropagation // temperature - scalar temperature param (temperature > 0), f.e. temperature = 0.07: Supervised Contrastive Learning void grad_contrastive_loss_positive(int i, int *labels, int num_of_samples, float **z, unsigned int feature_size, float temperature, float *cos_sim, float *p_constrastive, float *delta) { const float vec_len = math_vector_length(z[i], feature_size); int j; int N = 0; for (j = 0; j < num_of_samples; ++j) { if (labels[i] == labels[j]) N++; } if (N == 0 || temperature == 0 || vec_len == 0) { fprintf(stderr, " Error: N == 0 || temperature == 0 || vec_len == 0. N=%f, temperature=%f, vec_len=%f \n", N, temperature, vec_len); getchar(); } const float mult = 1 / ((N - 1) * temperature * vec_len); for (j = 0; j < num_of_samples; ++j) { //if (i != j && (i/2) == (j/2)) { if (i != j && labels[i] == labels[j]) { const float sim = cos_sim[i*num_of_samples + j]; // cosine_similarity(z[i], z[j], feature_size); const float P = p_constrastive[i*num_of_samples + j]; // P_constrastive(i, j, labels, num_of_samples, z, feature_size, temperature, cos_sim); //const float custom_pos_mult = 1 - sim; int m; for (m = 0; m < feature_size; ++m) { const float d = mult*(sim * z[i][m] - z[j][m]) * (1 - P); // good //const float d = mult*(sim * z[j][m] - z[j][m]) * (1 - P); // bad // printf(" pos: z[j][m] = %f, z[i][m] = %f, d = %f, sim = %f \n", z[j][m], z[i][m], d, sim); delta[m] -= d; } } } } // i - id of the current sample in mini_batch // labels[num_of_samples] - array with class_id for each sample in the current mini_batch // z[feature_size][num_of_samples] - array of arrays with contrastive features (output of conv-layer, f.e. 128 floats for each sample) // delta[feature_size] - array with deltas for backpropagation // temperature - scalar temperature param (temperature > 0), f.e. temperature = 0.07: Supervised Contrastive Learning void grad_contrastive_loss_negative(int i, int *labels, int num_of_samples, float **z, unsigned int feature_size, float temperature, float *cos_sim, float *p_constrastive, float *delta) { const float vec_len = math_vector_length(z[i], feature_size); int j; int N = 0; for (j = 0; j < num_of_samples; ++j) { if (labels[i] == labels[j]) N++; } if (N == 0 || temperature == 0 || vec_len == 0) { fprintf(stderr, " Error: N == 0 || temperature == 0 || vec_len == 0. N=%f, temperature=%f, vec_len=%f \n", N, temperature, vec_len); getchar(); } const float mult = 1 / ((N - 1) * temperature * vec_len); for (j = 0; j < num_of_samples; ++j) { //if (i != j && (i/2) == (j/2)) { if (i != j && labels[i] == labels[j]) { int k; for (k = 0; k < num_of_samples; ++k) { //if (k != i && k != j && labels[k] != labels[i]) { if (k != i && k != j) { const float sim = cos_sim[i*num_of_samples + k]; // cosine_similarity(z[i], z[k], feature_size); const float P = p_constrastive[i*num_of_samples + k]; // P_constrastive(i, k, labels, num_of_samples, z, feature_size, temperature, cos_sim); //const float custom_pos_mult = 1 + sim; int m; for (m = 0; m < feature_size; ++m) { const float d = mult*(z[k][m] - sim * z[i][m]) * P; // good //const float d = mult*(z[k][m] - sim * z[k][m]) * P; // bad //printf(" neg: z[k][m] = %f, z[i][m] = %f, d = %f, sim = %f \n", z[k][m], z[i][m], d, sim); delta[m] -= d; } } } } } }
TBBHashmap.h
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ---------------------------------------------------------------------------- #pragma once #include <tbb/concurrent_unordered_map.h> #include <limits> #include <unordered_map> #include "open3d/core/hashmap/CPU/CPUHashmapBufferAccessor.hpp" #include "open3d/core/hashmap/DeviceHashmap.h" #include "open3d/utility/Parallel.h" namespace open3d { namespace core { template <typename Key, typename Hash> class TBBHashmap : public DeviceHashmap { public: TBBHashmap(int64_t init_capacity, int64_t dsize_key, int64_t dsize_value, const Device& device); ~TBBHashmap(); void Rehash(int64_t buckets) override; void Insert(const void* input_keys, const void* input_values, addr_t* output_addrs, bool* output_masks, int64_t count) override; void Activate(const void* input_keys, addr_t* output_addrs, bool* output_masks, int64_t count) override; void Find(const void* input_keys, addr_t* output_addrs, bool* output_masks, int64_t count) override; void Erase(const void* input_keys, bool* output_masks, int64_t count) override; int64_t GetActiveIndices(addr_t* output_indices) override; void Clear() override; int64_t Size() const override; int64_t GetBucketCount() const override; std::vector<int64_t> BucketSizes() const override; float LoadFactor() const override; std::shared_ptr<tbb::concurrent_unordered_map<Key, addr_t, Hash>> GetImpl() const { return impl_; } protected: std::shared_ptr<tbb::concurrent_unordered_map<Key, addr_t, Hash>> impl_; std::shared_ptr<CPUHashmapBufferAccessor> buffer_ctx_; void InsertImpl(const void* input_keys, const void* input_values, addr_t* output_addrs, bool* output_masks, int64_t count); void Allocate(int64_t capacity); }; template <typename Key, typename Hash> TBBHashmap<Key, Hash>::TBBHashmap(int64_t init_capacity, int64_t dsize_key, int64_t dsize_value, const Device& device) : DeviceHashmap(init_capacity, dsize_key, dsize_value, device) { Allocate(init_capacity); } template <typename Key, typename Hash> TBBHashmap<Key, Hash>::~TBBHashmap() {} template <typename Key, typename Hash> int64_t TBBHashmap<Key, Hash>::Size() const { return impl_->size(); } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Insert(const void* input_keys, const void* input_values, addr_t* output_addrs, bool* output_masks, int64_t count) { int64_t new_size = Size() + count; if (new_size > this->capacity_) { int64_t bucket_count = GetBucketCount(); float avg_capacity_per_bucket = float(this->capacity_) / float(bucket_count); int64_t expected_buckets = std::max( bucket_count * 2, int64_t(std::ceil(new_size / avg_capacity_per_bucket))); Rehash(expected_buckets); } InsertImpl(input_keys, input_values, output_addrs, output_masks, count); } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Activate(const void* input_keys, addr_t* output_addrs, bool* output_masks, int64_t count) { Insert(input_keys, nullptr, output_addrs, output_masks, count); } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Find(const void* input_keys, addr_t* output_addrs, bool* output_masks, int64_t count) { const Key* input_keys_templated = static_cast<const Key*>(input_keys); #pragma omp parallel for num_threads(utility::EstimateMaxThreads()) for (int64_t i = 0; i < count; ++i) { const Key& key = input_keys_templated[i]; auto iter = impl_->find(key); bool flag = (iter != impl_->end()); output_masks[i] = flag; output_addrs[i] = flag ? iter->second : 0; } } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Erase(const void* input_keys, bool* output_masks, int64_t count) { const Key* input_keys_templated = static_cast<const Key*>(input_keys); for (int64_t i = 0; i < count; ++i) { const Key& key = input_keys_templated[i]; auto iter = impl_->find(key); bool flag = (iter != impl_->end()); output_masks[i] = flag; if (flag) { buffer_ctx_->DeviceFree(iter->second); impl_->unsafe_erase(iter); } } } template <typename Key, typename Hash> int64_t TBBHashmap<Key, Hash>::GetActiveIndices(addr_t* output_indices) { int64_t count = impl_->size(); int64_t i = 0; for (auto iter = impl_->begin(); iter != impl_->end(); ++iter, ++i) { output_indices[i] = static_cast<int64_t>(iter->second); } return count; } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Clear() { impl_->clear(); buffer_ctx_->Reset(); } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Rehash(int64_t buckets) { int64_t iterator_count = Size(); Tensor active_keys; Tensor active_values; if (iterator_count > 0) { Tensor active_addrs({iterator_count}, Dtype::Int32, this->device_); GetActiveIndices(static_cast<addr_t*>(active_addrs.GetDataPtr())); Tensor active_indices = active_addrs.To(Dtype::Int64); active_keys = this->GetKeyBuffer().IndexGet({active_indices}); active_values = this->GetValueBuffer().IndexGet({active_indices}); } float avg_capacity_per_bucket = float(this->capacity_) / float(GetBucketCount()); int64_t new_capacity = int64_t(std::ceil(buckets * avg_capacity_per_bucket)); Allocate(new_capacity); if (iterator_count > 0) { Tensor output_addrs({iterator_count}, Dtype::Int32, this->device_); Tensor output_masks({iterator_count}, Dtype::Bool, this->device_); InsertImpl(active_keys.GetDataPtr(), active_values.GetDataPtr(), static_cast<addr_t*>(output_addrs.GetDataPtr()), output_masks.GetDataPtr<bool>(), iterator_count); } impl_->rehash(buckets); } template <typename Key, typename Hash> int64_t TBBHashmap<Key, Hash>::GetBucketCount() const { return impl_->unsafe_bucket_count(); } template <typename Key, typename Hash> std::vector<int64_t> TBBHashmap<Key, Hash>::BucketSizes() const { int64_t bucket_count = impl_->unsafe_bucket_count(); std::vector<int64_t> ret; for (int64_t i = 0; i < bucket_count; ++i) { ret.push_back(impl_->unsafe_bucket_size(i)); } return ret; } template <typename Key, typename Hash> float TBBHashmap<Key, Hash>::LoadFactor() const { return impl_->load_factor(); } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::InsertImpl(const void* input_keys, const void* input_values, addr_t* output_addrs, bool* output_masks, int64_t count) { const Key* input_keys_templated = static_cast<const Key*>(input_keys); #pragma omp parallel for num_threads(utility::EstimateMaxThreads()) for (int64_t i = 0; i < count; ++i) { output_addrs[i] = 0; output_masks[i] = false; const Key& key = input_keys_templated[i]; // Try to insert a dummy address. auto res = impl_->insert({key, 0}); // Lazy copy key value pair to buffer only if succeeded if (res.second) { addr_t dst_kv_addr = buffer_ctx_->DeviceAllocate(); auto dst_kv_iter = buffer_ctx_->ExtractIterator(dst_kv_addr); // Copy templated key to buffer *static_cast<Key*>(dst_kv_iter.first) = key; // Copy/reset non-templated value in buffer uint8_t* dst_value = static_cast<uint8_t*>(dst_kv_iter.second); if (input_values != nullptr) { const uint8_t* src_value = static_cast<const uint8_t*>(input_values) + this->dsize_value_ * i; std::memcpy(dst_value, src_value, this->dsize_value_); } else { std::memset(dst_value, 0, this->dsize_value_); } // Update from dummy 0 res.first->second = dst_kv_addr; // Write to return variables output_addrs[i] = dst_kv_addr; output_masks[i] = true; } } } template <typename Key, typename Hash> void TBBHashmap<Key, Hash>::Allocate(int64_t capacity) { this->capacity_ = capacity; this->buffer_ = std::make_shared<HashmapBuffer>(this->capacity_, this->dsize_key_, this->dsize_value_, this->device_); buffer_ctx_ = std::make_shared<CPUHashmapBufferAccessor>( this->capacity_, this->dsize_key_, this->dsize_value_, this->buffer_->GetKeyBuffer(), this->buffer_->GetValueBuffer(), this->buffer_->GetHeap()); buffer_ctx_->Reset(); impl_ = std::make_shared<tbb::concurrent_unordered_map<Key, addr_t, Hash>>( capacity, Hash()); } } // namespace core } // namespace open3d
opi.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> int main(int argc, char **argv) { double begin = omp_get_wtime(); //seed random number generator // Q2b: get the number of threads to run with from agrv and // add OpenMP API code to set number of threads here int Nthreads = atol(argv[1]); omp_set_num_threads(Nthreads); struct drand48_data *drandData; drandData = (struct drand48_data*) malloc(Nthreads*sizeof(struct drand48_data)); // Q2c: add an OpenMP parallel region here, wherein each thread initializes // one entry in drandData using srand48_r and seed based on thread number #pragma omp parallel { int rank = omp_get_thread_num(); int size = omp_get_num_threads(); long int seed = rank; srand48_r(seed, drandData+rank); } long long int Ntrials = 10000000; //need running tallies long long int Ntotal=0; long long int Ncircle=0; #pragma omp parallel for \ reduction(+:Ncircle) for (long long int n=0; n<Ntrials; n++) { double rand1; double rand2; int rank = omp_get_thread_num(); //gererate two random numbers (use the thread id to offset drandData) drand48_r(drandData+rank, &rand1); drand48_r(drandData+rank, &rand2); double x = -1 + 2*rand1; //shift to [-1,1] double y = -1 + 2*rand2; //check if its in the circle if (sqrt(x*x+y*y)<=1) Ncircle++; Ntotal++; if (n%100 ==0) { double pi = 4.0*Ncircle/ (double) (n); printf("Our estimate of pi is %g \n", pi); } } double pi = 4.0*Ncircle/ (double) (Ntotal); printf("Our final estimate of pi is %g \n", pi); printf("Time: \t %f \n", omp_get_wtime()-begin); free(drandData); return 0; }
pubkeylp.h
/** * @file pubkeylp.h -- Public key type for lattice crypto operations. * @author TPOC: contact@palisade-crypto.org * * @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT) * 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. * 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. * */ #ifndef LBCRYPTO_CRYPTO_PUBKEYLP_H #define LBCRYPTO_CRYPTO_PUBKEYLP_H //Includes Section #include <vector> #include <iomanip> #include "lattice/elemparams.h" #include "lattice/ilparams.h" #include "lattice/ildcrtparams.h" #include "lattice/ilelement.h" #include "utils/inttypes.h" #include "utils/hashutil.h" #include "math/distrgen.h" #include "encoding/encodingparams.h" /** * @namespace lbcrypto * The namespace of lbcrypto */ namespace lbcrypto { /* This struct holds the different options for * key switching algorithms that are supported * by the library. * */ enum KeySwitchTechnique { BV, GHS, HYBRID }; //forward declarations, used to resolve circular header dependencies template<typename Element> class CiphertextImpl; template<typename Element> class RationalCiphertext; template<typename Element> class LPCryptoParameters; template<typename Element> class LPCryptoParametersBGV; template<typename Element> class LPCryptoParametersBFV; template<typename Element> class LPCryptoParametersStehleSteinfeld; template<typename Element> class CryptoObject; struct EncryptResult { explicit EncryptResult() : isValid(false), numBytesEncrypted(0) {} explicit EncryptResult(size_t len) : isValid(true), numBytesEncrypted(len) {} bool isValid; /**< whether the encryption was successful */ usint numBytesEncrypted; /**< count of the number of plaintext bytes that were encrypted */ }; /** * @brief Decryption result. This represents whether the decryption of a cipheretext was performed correctly. * * This is intended to eventually incorporate information about the amount of padding in a decoded ciphertext, * to ensure that the correct amount of padding is stripped away. * It is intended to provided a very simple kind of checksum eventually. * This notion of a decoding output is inherited from the crypto++ library. * It is also intended to be used in a recover and restart robust functionality if not all ciphertext is recieved over a lossy channel, so that if all information is eventually recieved, decoding/decryption can be performed eventually. * This is intended to be returned with the output of a decryption operation. */ struct DecryptResult { /** * Constructor that initializes all message lengths to 0. */ explicit DecryptResult() : isValid(false), messageLength(0) {} /** * Constructor that initializes all message lengths. * @param len the new length. */ explicit DecryptResult(size_t len) : isValid(true), messageLength(len) {} bool isValid; /**< whether the decryption was successful */ usint messageLength; /**< the length of the decrypted plaintext message */ }; /** * @brief Abstract interface class for LP Keys * * @tparam Element a ring element. */ template <class Element> class LPKey : public CryptoObject<Element>, public Serializable { public: LPKey(CryptoContext<Element> cc, const string& id = "") : CryptoObject<Element>(cc, id) {} LPKey(shared_ptr<CryptoObject<Element>> co) : CryptoObject<Element>(co) {} virtual ~LPKey() {} template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::base_class<CryptoObject<Element>>( this ) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { ar( ::cereal::base_class<CryptoObject<Element>>( this ) ); } }; template<typename Element> class LPPublicKeyImpl; template<typename Element> using LPPublicKey = shared_ptr<LPPublicKeyImpl<Element>>; /** * @brief Class for LP public keys * @tparam Element a ring element. */ template <typename Element> class LPPublicKeyImpl : public LPKey<Element> { public: /** * Basic constructor * * @param cc - CryptoContext * @param id - key identifier */ LPPublicKeyImpl(CryptoContext<Element> cc = 0, const string& id = "") : LPKey<Element>(cc, id) {} /** * Copy constructor * *@param &rhs LPPublicKeyImpl to copy from */ explicit LPPublicKeyImpl(const LPPublicKeyImpl<Element> &rhs) : LPKey<Element>(rhs.GetCryptoContext(), rhs.GetKeyTag()) { m_h = rhs.m_h; } /** * Move constructor * *@param &rhs LPPublicKeyImpl to move from */ explicit LPPublicKeyImpl(LPPublicKeyImpl<Element> &&rhs) : LPKey<Element>(rhs.GetCryptoContext(), rhs.GetKeyTag()) { m_h = std::move(rhs.m_h); } operator bool() const { return bool(this->context) && m_h.size() != 0; } /** * Assignment Operator. * * @param &rhs LPPublicKeyImpl to copy from */ const LPPublicKeyImpl<Element>& operator=(const LPPublicKeyImpl<Element> &rhs) { CryptoObject<Element>::operator=(rhs); this->m_h = rhs.m_h; return *this; } /** * Move Assignment Operator. * * @param &rhs LPPublicKeyImpl to copy from */ const LPPublicKeyImpl<Element>& operator=(LPPublicKeyImpl<Element> &&rhs) { CryptoObject<Element>::operator=(rhs); m_h = std::move(rhs.m_h); return *this; } //@Get Properties /** * Gets the computed public key * @return the public key element. */ const std::vector<Element> &GetPublicElements() const { return this->m_h; } //@Set Properties /** * Sets the public key vector of Element. * @param &element is the public key Element vector to be copied. */ void SetPublicElements(const std::vector<Element> &element) { m_h = element; } /** * Sets the public key vector of Element. * @param &&element is the public key Element vector to be moved. */ void SetPublicElements(std::vector<Element> &&element) { m_h = std::move(element); } /** * Sets the public key Element at index idx. * @param &element is the public key Element to be copied. */ void SetPublicElementAtIndex(usint idx, const Element &element) { m_h.insert(m_h.begin() + idx, element); } /** * Sets the public key Element at index idx. * @param &&element is the public key Element to be moved. */ void SetPublicElementAtIndex(usint idx, Element &&element) { m_h.insert(m_h.begin() + idx, std::move(element)); } bool operator==(const LPPublicKeyImpl& other) const { if( !CryptoObject<Element>::operator ==(other) ) { return false; } if( m_h.size() != other.m_h.size() ) { return false; } for( size_t i = 0; i < m_h.size(); i++ ) { if( m_h[i] != other.m_h[i] ) { return false; } } return true; } bool operator!=(const LPPublicKeyImpl& other) const { return ! (*this == other); } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::base_class<LPKey<Element>>( this ) ); ar( ::cereal::make_nvp("h",m_h) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { if( version > SerializedVersion() ) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } ar( ::cereal::base_class<LPKey<Element>>( this ) ); ar( ::cereal::make_nvp("h",m_h) ); } std::string SerializedObjectName() const { return "PublicKey"; } static uint32_t SerializedVersion() { return 1; } private: std::vector<Element> m_h; }; template<typename Element> class LPEvalKeyImpl; template<typename Element> using LPEvalKey = shared_ptr<LPEvalKeyImpl<Element>>; /** * @brief Abstract interface for LP evaluation/proxy keys * @tparam Element a ring element. */ template <class Element> class LPEvalKeyImpl : public LPKey<Element> { public: /** * Basic constructor for setting crypto params * * @param &cryptoParams is the reference to cryptoParams */ LPEvalKeyImpl(CryptoContext<Element> cc = 0) : LPKey<Element>(cc) {} virtual ~LPEvalKeyImpl() {} /** * Setter function to store Relinearization Element Vector A. * Throws exception, to be overridden by derived class. * * @param &a is the Element vector to be copied. */ virtual void SetAVector(const std::vector<Element> &a) { throw std::runtime_error("SetAVector copy operation not supported"); } /** * Setter function to store Relinearization Element Vector A. * Throws exception, to be overridden by derived class. * * @param &&a is the Element vector to be moved. */ virtual void SetAVector(std::vector<Element> &&a) { throw std::runtime_error("SetAVector move operation not supported"); } /** * Getter function to access Relinearization Element Vector A. * Throws exception, to be overridden by derived class. * * @return Element vector A. */ virtual const std::vector<Element> &GetAVector() const { throw std::runtime_error("GetAVector operation not supported"); } /** * Setter function to store Relinearization Element Vector B. * Throws exception, to be overridden by derived class. * * @param &b is the Element vector to be copied. */ virtual void SetBVector(const std::vector<Element> &b) { throw std::runtime_error("SetBVector copy operation not supported"); } /** * Setter function to store Relinearization Element Vector B. * Throws exception, to be overridden by derived class. * * @param &&b is the Element vector to be moved. */ virtual void SetBVector(std::vector<Element> &&b) { throw std::runtime_error("SetBVector move operation not supported"); } /** * Getter function to access Relinearization Element Vector B. * Throws exception, to be overridden by derived class. * * @return Element vector B. */ virtual const std::vector<Element> &GetBVector() const { throw std::runtime_error("GetBVector operation not supported"); } /** * Setter function to store key switch Element. * Throws exception, to be overridden by derived class. * * @param &a is the Element to be copied. */ virtual void SetA(const Element &a) { throw std::runtime_error("SetA copy operation not supported"); } /** * Setter function to store key switch Element. * Throws exception, to be overridden by derived class. * * @param &&a is the Element to be moved. */ virtual void SetA(Element &&a) { throw std::runtime_error("SetA move operation not supported"); } /** * Getter function to access key switch Element. * Throws exception, to be overridden by derived class. * * @return Element. */ virtual const Element &GetA() const { throw std::runtime_error("GetA operation not supported"); } /** * Setter function to store key switch Element. * Throws exception, to be overridden by derived class. * * @param &a is the Element to be copied. */ virtual void SetAinDCRT(const DCRTPoly &a) { throw std::runtime_error("SetAinDCRT copy operation not supported"); } /** * Setter function to store key switch Element. * Throws exception, to be overridden by derived class. * * @param &&a is the Element to be moved. */ virtual void SetAinDCRT(DCRTPoly &&a) { throw std::runtime_error("SetAinDCRT move operation not supported"); } /** * Getter function to access key switch Element. * Throws exception, to be overridden by derived class. * * @return Element. */ virtual const DCRTPoly &GetAinDCRT() const { throw std::runtime_error("GetAinDCRT operation not supported"); } /** * Setter function to store key switch Element. * Throws exception, to be overridden by derived class. * * @param &b is the Element to be copied. */ virtual void SetBinDCRT(const DCRTPoly &b) { throw std::runtime_error("SetAinDCRT copy operation not supported"); } /** * Setter function to store key switch Element. * Throws exception, to be overridden by derived class. * * @param &&b is the Element to be moved. */ virtual void SetBinDCRT(DCRTPoly &&b) { throw std::runtime_error("SetAinDCRT move operation not supported"); } /** * Getter function to access key switch Element. * Throws exception, to be overridden by derived class. * * @return Element. */ virtual const DCRTPoly &GetBinDCRT() const { throw std::runtime_error("GetAinDCRT operation not supported"); } virtual void ClearKeys() { throw std::runtime_error("ClearKeys operation is not supported"); } friend bool operator==(const LPEvalKeyImpl& a, const LPEvalKeyImpl& b) { return a.key_compare(b); } friend bool operator!=(const LPEvalKeyImpl& a, LPEvalKeyImpl& b) { return ! (a == b); } virtual bool key_compare(const LPEvalKeyImpl& other) const { return false; } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::base_class<LPKey<Element>>( this ) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { ar( ::cereal::base_class<LPKey<Element>>( this ) ); } std::string SerializedObjectName() const { return "EvalKey"; } }; template<typename Element> class LPEvalKeyRelinImpl; template<typename Element> using LPEvalKeyRelin = shared_ptr<LPEvalKeyRelinImpl<Element>>; /** * @brief Concrete class for Relinearization keys of RLWE scheme * @tparam Element a ring element. */ template <class Element> class LPEvalKeyRelinImpl : public LPEvalKeyImpl<Element> { public: /** * Basic constructor for setting crypto params * * @param &cryptoParams is the reference to cryptoParams */ LPEvalKeyRelinImpl(CryptoContext<Element> cc = 0) : LPEvalKeyImpl<Element>(cc) {} virtual ~LPEvalKeyRelinImpl() {} /** * Copy constructor * *@param &rhs key to copy from */ explicit LPEvalKeyRelinImpl(const LPEvalKeyRelinImpl<Element> &rhs) : LPEvalKeyImpl<Element>(rhs.GetCryptoContext()) { m_rKey = rhs.m_rKey; } /** * Move constructor * *@param &rhs key to move from */ explicit LPEvalKeyRelinImpl(LPEvalKeyRelinImpl<Element> &&rhs) : LPEvalKeyImpl<Element>(rhs.GetCryptoContext()) { m_rKey = std::move(rhs.m_rKey); } operator bool() const { return bool(this->context) && m_rKey.size() != 0; } /** * Assignment Operator. * * @param &rhs key to copy from */ const LPEvalKeyRelinImpl<Element>& operator=(const LPEvalKeyRelinImpl<Element> &rhs) { this->context = rhs.context; this->m_rKey = rhs.m_rKey; return *this; } /** * Move Assignment Operator. * * @param &rhs key to move from */ const LPEvalKeyRelinImpl<Element>& operator=(LPEvalKeyRelinImpl<Element> &&rhs) { this->context = rhs.context; rhs.context = 0; m_rKey = std::move(rhs.m_rKey); return *this; } /** * Setter function to store Relinearization Element Vector A. * Overrides base class implementation. * * @param &a is the Element vector to be copied. */ virtual void SetAVector(const std::vector<Element> &a) { m_rKey.insert(m_rKey.begin() + 0, a); } /** * Setter function to store Relinearization Element Vector A. * Overrides base class implementation. * * @param &&a is the Element vector to be moved. */ virtual void SetAVector(std::vector<Element> &&a) { m_rKey.insert(m_rKey.begin() + 0, std::move(a)); } /** * Getter function to access Relinearization Element Vector A. * Overrides base class implementation. * * @return Element vector A. */ virtual const std::vector<Element> &GetAVector() const { return m_rKey.at(0); } /** * Setter function to store Relinearization Element Vector B. * Overrides base class implementation. * * @param &b is the Element vector to be copied. */ virtual void SetBVector(const std::vector<Element> &b) { m_rKey.insert(m_rKey.begin() + 1, b); } /** * Setter function to store Relinearization Element Vector B. * Overrides base class implementation. * * @param &&b is the Element vector to be moved. */ virtual void SetBVector(std::vector<Element> &&b) { m_rKey.insert(m_rKey.begin() + 1, std::move(b)); } /** * Getter function to access Relinearization Element Vector B. * Overrides base class implementation. * * @return Element vector B. */ virtual const std::vector<Element> &GetBVector() const { return m_rKey.at(1); } /** * Setter function to store key switch Element. * Throws exception, to be overridden by derived class. * * @param &a is the Element to be copied. */ virtual void SetAinDCRT(const DCRTPoly &a) { m_dcrtKeys.insert(m_dcrtKeys.begin() + 0, a); } /** * Setter function to store key switch Element. * Throws exception, to be overridden by derived class. * * @param &&a is the Element to be moved. */ virtual void SetAinDCRT(DCRTPoly &&a) { m_dcrtKeys.insert(m_dcrtKeys.begin() + 0, std::move(a)); } /** * Getter function to access key switch Element. * Throws exception, to be overridden by derived class. * * @return Element. */ virtual const DCRTPoly &GetAinDCRT() const { return m_dcrtKeys.at(0); } /** * Setter function to store key switch Element. * Throws exception, to be overridden by derived class. * * @param &b is the Element to be copied. */ virtual void SetBinDCRT(const DCRTPoly &b) { m_dcrtKeys.insert(m_dcrtKeys.begin() + 1, b); } /** * Setter function to store key switch Element. * Throws exception, to be overridden by derived class. * * @param &&b is the Element to be moved. */ virtual void SetBinDCRT(DCRTPoly &&b) { m_dcrtKeys.insert(m_dcrtKeys.begin() + 1, std::move(b)); } /** * Getter function to access key switch Element. * Throws exception, to be overridden by derived class. * * @return Element. */ virtual const DCRTPoly &GetBinDCRT() const { return m_dcrtKeys.at(1); } virtual void ClearKeys() { m_rKey.clear(); m_dcrtKeys.clear(); } /** * Serialize the object into a Serialized * @param *serObj is used to store the serialized result. It MUST be a rapidjson Object (SetObject()); * @return true if successfully serialized */ bool Serialize(Serialized *serObj) const; /** * SerializeWithoutContext - serializes the object into a Serialized, withut the cryptocontext * @param *serObj is used to store the serialized result. It MUST be a rapidjson Object (SetObject()); * @return true if successfully serialized */ bool SerializeWithoutContext(Serialized *serObj) const; /** * Deserialize from the serialization * @param serObj - contains the serialization * @return true on success */ bool Deserialize(const Serialized &serObj); bool key_compare(const LPEvalKeyImpl<Element>& other) const { const LPEvalKeyRelinImpl<Element> &oth = dynamic_cast<const LPEvalKeyRelinImpl<Element> &>(other); if( !CryptoObject<Element>::operator==(other) ) return false; if( this->m_rKey.size() != oth.m_rKey.size() ) return false; for( size_t i=0; i<this->m_rKey.size(); i++ ) { if( this->m_rKey[i].size() != oth.m_rKey[i].size() ) return false; for( size_t j=0; j<this->m_rKey[i].size(); j++ ) { if( this->m_rKey[i][j] != oth.m_rKey[i][j] ) return false; } } return true; } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::base_class<LPEvalKeyImpl<Element>>( this ) ); ar( ::cereal::make_nvp("k", m_rKey) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { if( version > SerializedVersion() ) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } ar( ::cereal::base_class<LPEvalKeyImpl<Element>>( this ) ); ar( ::cereal::make_nvp("k", m_rKey) ); } std::string SerializedObjectName() const { return "EvalKeyRelin"; } static uint32_t SerializedVersion() { return 1; } private: //private member to store vector of vector of Element. std::vector< std::vector<Element> > m_rKey; // Used for GHS key switching std::vector<DCRTPoly> m_dcrtKeys; }; template<typename Element> class LPEvalKeyNTRURelinImpl; template<typename Element> using LPEvalKeyNTRURelin = shared_ptr<LPEvalKeyNTRURelinImpl<Element>>; /** * @brief Evaluation Relinearization keys for NTRU scheme. * @tparam Element a ring element. */ template <class Element> class LPEvalKeyNTRURelinImpl : public LPEvalKeyImpl<Element> { public: /** * Basic constructor for setting crypto params * * @param &cryptoParams is the reference to cryptoParams */ LPEvalKeyNTRURelinImpl(CryptoContext<Element> cc = 0) : LPEvalKeyImpl<Element>(cc) {} virtual ~LPEvalKeyNTRURelinImpl() {} /** * Copy constructor * *@param &rhs key to copy from */ explicit LPEvalKeyNTRURelinImpl(const LPEvalKeyNTRURelinImpl<Element> &rhs) : LPEvalKeyImpl<Element>(rhs.GetCryptoContext()) { m_rKey = rhs.m_rKey; } /** * Move constructor * *@param &rhs key to move from */ explicit LPEvalKeyNTRURelinImpl(LPEvalKeyNTRURelinImpl<Element> &&rhs) : LPEvalKeyImpl<Element>(rhs.GetCryptoContext()) { m_rKey = std::move(rhs.m_rKey); } /** * Assignment Operator. * * @param &rhs key to copy from */ const LPEvalKeyNTRURelinImpl<Element>& operator=(const LPEvalKeyNTRURelinImpl<Element> &rhs) { this->context = rhs.context; this->m_rKey = rhs.m_rKey; return *this; } /** * Move Assignment Operator. * * @param &rhs key to move from */ const LPEvalKeyNTRURelinImpl<Element>& operator=(LPEvalKeyNTRURelinImpl<Element> &&rhs) { this->context = rhs.context; rhs.context = 0; m_rKey = std::move(rhs.m_rKey); return *this; } /** * Setter function to store Relinearization Element Vector A. * Overrides base class implementation. * * @param &a is the Element vector to be copied. */ virtual void SetAVector(const std::vector<Element> &a) { for (usint i = 0; i < a.size(); i++) { m_rKey.insert(m_rKey.begin() + i, a.at(i)); } } /** * Setter function to store Relinearization Element Vector A. * Overrides base class implementation. * * @param &&a is the Element vector to be moved. */ virtual void SetAVector(std::vector<Element> &&a) { m_rKey = std::move(a); } /** * Getter function to access Relinearization Element Vector A. * Overrides base class implementation. * * @return Element vector A. */ virtual const std::vector<Element> &GetAVector() const { return m_rKey; } bool key_compare(const LPEvalKeyImpl<Element>& other) const { const LPEvalKeyNTRURelinImpl<Element> &oth = dynamic_cast<const LPEvalKeyNTRURelinImpl<Element> &>(other); if( !CryptoObject<Element>::operator ==(other) ) return false; if( this->m_rKey.size() != oth.m_rKey.size() ) return false; for( size_t i=0; i<this->m_rKey.size(); i++ ) { if( this->m_rKey[i] != oth.m_rKey[i] ) return false; } return true; } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::base_class<LPEvalKeyImpl<Element>>( this ) ); ar( ::cereal::make_nvp("k", m_rKey) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { if( version > SerializedVersion() ) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } ar( ::cereal::base_class<LPEvalKeyImpl<Element>>( this ) ); ar( ::cereal::make_nvp("k", m_rKey) ); } std::string SerializedObjectName() const { return "EvalKeyNTRURelin"; } static uint32_t SerializedVersion() { return 1; } private: //private member to store vector of Element. std::vector<Element> m_rKey; }; template<typename Element> class LPEvalKeyNTRUImpl; template<typename Element> using LPEvalKeyNTRU = shared_ptr<LPEvalKeyNTRUImpl<Element>>; /** * @brief Concrete class for facilitating NTRU key switch. * @tparam Element a ring element. */ template <class Element> class LPEvalKeyNTRUImpl : public LPEvalKeyImpl<Element> { public: /** * Basic constructor for setting crypto params * * @param &cryptoParams is the reference to cryptoParams */ LPEvalKeyNTRUImpl(CryptoContext<Element> cc = 0) : LPEvalKeyImpl<Element>(cc) {} virtual ~LPEvalKeyNTRUImpl() {} /** * Copy constructor * *@param &rhs key to copy from */ explicit LPEvalKeyNTRUImpl(const LPEvalKeyNTRUImpl<Element> &rhs) : LPEvalKeyImpl<Element>(rhs.GetCryptoContext()) { m_Key = rhs.m_Key; } /** * Move constructor * *@param &rhs key to move from */ explicit LPEvalKeyNTRUImpl(LPEvalKeyNTRUImpl<Element> &&rhs) : LPEvalKeyImpl<Element>(rhs.GetCryptoContext()) { m_Key = std::move(rhs.m_Key); } /** * Assignment Operator. * * @param &rhs key to copy from */ const LPEvalKeyNTRUImpl<Element>& operator=(const LPEvalKeyNTRUImpl<Element> &rhs) { this->context = rhs.context; this->m_Key = rhs.m_Key; return *this; } /** * Move Assignment Operator. * * @param &rhs key to move from */ const LPEvalKeyNTRUImpl<Element>& operator=(LPEvalKeyNTRUImpl<Element> &&rhs) { this->context = rhs.context; rhs.context = 0; m_Key = std::move(rhs.m_Key); return *this; } /** * Setter function to store NTRU key switch element. * Function copies the key. * Overrides the virtual function from base class LPEvalKeyImpl. * * @param &a is the key switch element to be copied. */ virtual void SetA(const Element &a) { m_Key = a; } /** * Setter function to store NTRU key switch Element. * Function moves the key. * Overrides the virtual function from base class LPEvalKeyImpl. * * @param &&a is the key switch Element to be moved. */ virtual void SetA(Element &&a) { m_Key = std::move(a); } /** * Getter function to access NTRU key switch Element. * Overrides the virtual function from base class LPEvalKeyImpl. * * @return NTRU key switch Element. */ virtual const Element& GetA() const { return m_Key; } bool key_compare(const LPEvalKeyImpl<Element>& other) const { const LPEvalKeyNTRUImpl<Element> &oth = dynamic_cast<const LPEvalKeyNTRUImpl<Element> &>(other); if( !CryptoObject<Element>::operator ==(other) ) return false; if( this->m_Key != oth.m_Key ) return false; return true; } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::base_class<LPEvalKeyImpl<Element>>( this ) ); ar( ::cereal::make_nvp("k", m_Key) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { if( version > SerializedVersion() ) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } ar( ::cereal::base_class<LPEvalKeyImpl<Element>>( this ) ); ar( ::cereal::make_nvp("k", m_Key) ); } std::string SerializedObjectName() const { return "EvalKeyNTRU"; } static uint32_t SerializedVersion() { return 1; } private: /** * private member Element to store key. */ Element m_Key; }; template<typename Element> class LPPrivateKeyImpl; template<typename Element> using LPPrivateKey = shared_ptr<LPPrivateKeyImpl<Element>>; /** * @brief Class fpr LP Private keys * @tparam Element a ring element. */ template <class Element> class LPPrivateKeyImpl : public LPKey<Element> { public: /** * Construct in context */ LPPrivateKeyImpl(CryptoContext<Element> cc = 0) : LPKey<Element>(cc, GenerateUniqueKeyID()) {} /** * Copy constructor *@param &rhs the LPPrivateKeyImpl to copy from */ explicit LPPrivateKeyImpl(const LPPrivateKeyImpl<Element> &rhs) : LPKey<Element>(rhs.GetCryptoContext(), rhs.GetKeyTag()) { this->m_sk = rhs.m_sk; } /** * Move constructor *@param &rhs the LPPrivateKeyImpl to move from */ explicit LPPrivateKeyImpl(LPPrivateKeyImpl<Element> &&rhs) : LPKey<Element>(rhs.GetCryptoContext(), rhs.GetKeyTag()) { this->m_sk = std::move(rhs.m_sk); } operator bool() const { return bool(this->context); } /** * Assignment Operator. * * @param &rhs LPPrivateKeyto assign from. * @return the resulting LPPrivateKeyImpl */ const LPPrivateKeyImpl<Element>& operator=(const LPPrivateKeyImpl<Element> &rhs) { CryptoObject<Element>::operator=(rhs); this->m_sk = rhs.m_sk; return *this; } /** * Move Assignment Operator. * * @param &rhs LPPrivateKeyImpl to assign from. * @return the resulting LPPrivateKeyImpl */ const LPPrivateKeyImpl<Element>& operator=(LPPrivateKeyImpl<Element> &&rhs) { CryptoObject<Element>::operator=(rhs); this->m_sk = std::move(rhs.m_sk); return *this; } /** * Implementation of the Get accessor for private element. * @return the private element. */ const Element & GetPrivateElement() const { return m_sk; } /** * Set accessor for private element. * @private &x private element to set to. */ void SetPrivateElement(const Element &x) { m_sk = x; } /** * Set accessor for private element. * @private &x private element to set to. */ void SetPrivateElement(Element &&x) { m_sk = std::move(x); } bool operator==(const LPPrivateKeyImpl& other) const { return CryptoObject<Element>::operator ==(other) && m_sk == other.m_sk; } bool operator!=(const LPPrivateKeyImpl& other) const { return ! (*this == other); } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::base_class<LPKey<Element>>( this ) ); ar( ::cereal::make_nvp("s",m_sk) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { if( version > SerializedVersion() ) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } ar( ::cereal::base_class<LPKey<Element>>( this ) ); ar( ::cereal::make_nvp("s",m_sk) ); } std::string SerializedObjectName() const { return "PrivateKey"; } static uint32_t SerializedVersion() { return 1; } private: static const size_t intsInID = 128 / (sizeof(uint32_t) * 8); static string GenerateUniqueKeyID() { std::uniform_int_distribution<uint32_t> distribution(0, std::numeric_limits<uint32_t>::max()); std::stringstream s; s.fill('0'); s << std::hex; for( size_t i = 0; i < intsInID; i++ ) s << std::setw(8) << distribution(PseudoRandomNumberGenerator::GetPRNG()); return s.str(); } Element m_sk; }; template <class Element> class LPKeyPair { public: LPPublicKey<Element> publicKey; LPPrivateKey<Element> secretKey; LPKeyPair(LPPublicKeyImpl<Element>* a=0, LPPrivateKeyImpl<Element>* b=0): publicKey(a), secretKey(b) {} bool good() { return publicKey && secretKey; } }; /** * @brief Abstract interface for parameter generation algorithm * @tparam Element a ring element. */ template <class Element> class LPParameterGenerationAlgorithm { public: virtual ~LPParameterGenerationAlgorithm() {} /** * Method for computing all derived parameters based on chosen primitive parameters * * @param *cryptoParams the crypto parameters object to be populated with parameters. * @param evalAddCount number of EvalAdds assuming no EvalMult and KeySwitch operations are performed. * @param evalMultCount number of EvalMults assuming no EvalAdd and KeySwitch operations are performed. * @param keySwitchCount number of KeySwitch operations assuming no EvalAdd and EvalMult operations are performed. * @param dcrtBits number of bits in each CRT modulus* * @param n ring dimension in case the user wants to use a custom ring dimension */ virtual bool ParamsGen(shared_ptr<LPCryptoParameters<Element>> cryptoParams, int32_t evalAddCount = 0, int32_t evalMultCount = 0, int32_t keySwitchCount = 0, size_t dcrtBits = 0, uint32_t n = 0) const = 0; /** * Method for computing all derived parameters based on chosen primitive parameters. * This is intended for CKKS and DCRTPoly. * * @param *cryptoParams the crypto parameters object to be populated with parameters. * @param cyclOrder the cyclotomic order. * @param numPrimes number of modulus towers to support. * @param scaleExp the bit-width for plaintexts and DCRTPoly's. * @param relinWindow the relinearization window * @param mode * @param ksTech the key switching technique used (e.g., BV or GHS) * @param firstModSize the bit-size of the first modulus * @param rsTech the rescaling technique used (e.g., APPROXRESCALE or EXACTRESCALE) */ virtual bool ParamsGen(shared_ptr<LPCryptoParameters<Element>> cryptoParams, usint cyclOrder, usint numPrimes, usint scaleExp, usint relinWindow, MODE mode, KeySwitchTechnique ksTech, usint firstModSize, RescalingTechnique) const { throw std::logic_error("This signature for ParamsGen is not supported for this scheme."); } /** * Method for computing all derived parameters based on chosen primitive parameters. * * @param *cryptoParams the crypto parameters object to be populated with parameters. * @param cyclOrder the cyclotomic order. * @param numPrimes number of modulus towers to support. * @param scaleExp the bit-width for plaintexts and DCRTPoly's. * @param relinWindow the relinearization window * @param mode * @param ksTech the key switching technique used (e.g., BV or GHS) * @param firstModSize the bit-size of the first modulus * @param rsTech the rescaling technique used (e.g., APPROXRESCALE or EXACTRESCALE) */ virtual bool ParamsGen(shared_ptr<LPCryptoParameters<Element>> cryptoParams, usint cyclOrder, usint numPrimes, usint scaleExp, usint relinWindow, MODE mode, KeySwitchTechnique ksTech = BV, usint firstModSize = 60, RescalingTechnique = APPROXRESCALE, uint32_t numLargeDigits = 4) const { throw std::logic_error("This signature for ParamsGen is not supported for this scheme."); } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const {} template <class Archive> void load( Archive & ar, std::uint32_t const version ) {} std::string SerializedObjectName() const { return "ParamsGen"; } }; /** * @brief Abstract interface for encryption algorithm * @tparam Element a ring element. */ template <class Element> class LPEncryptionAlgorithm { public: virtual ~LPEncryptionAlgorithm() {} /** * Method for encrypting plaintext using LBC * * @param&publicKey public key used for encryption. * @param plaintext copy of the plaintext element. NOTE a copy is passed! That is NOT an error! * @param doEncryption encrypts if true, embeds (encodes) the plaintext into cryptocontext if false * @param *ciphertext ciphertext which results from encryption. */ virtual Ciphertext<Element> Encrypt(const LPPublicKey<Element> publicKey, Element plaintext) const = 0; /** * Method for encrypting plaintex using LBC * * @param privateKey private key used for encryption. * @param plaintext copy of the plaintext input. NOTE a copy is passed! That is NOT an error! * @param doEncryption encrypts if true, embeds (encodes) the plaintext into cryptocontext if false * @param *ciphertext ciphertext which results from encryption. */ virtual Ciphertext<Element> Encrypt(const LPPrivateKey<Element> privateKey, Element plaintext) const = 0; /** * Method for decrypting plaintext using LBC * * @param &privateKey private key used for decryption. * @param &ciphertext ciphertext id decrypted. * @param *plaintext the plaintext output. * @return the decoding result. */ virtual DecryptResult Decrypt(const LPPrivateKey<Element> privateKey, ConstCiphertext<Element> ciphertext, NativePoly *plaintext) const = 0; /** * Method for decrypting plaintext using LBC * * @param &privateKey private key used for decryption. * @param &ciphertext ciphertext id decrypted. * @param *plaintext the plaintext output. * @return the decoding result. */ virtual DecryptResult Decrypt(const LPPrivateKey<Element> privateKey, ConstCiphertext<Element> ciphertext, Poly *plaintext) const { throw std::logic_error("Decryption to Poly is not supported"); } /** * Function to generate public and private keys * * @param &publicKey private key used for decryption. * @param &privateKey private key used for decryption. * @return function ran correctly. */ virtual LPKeyPair<Element> KeyGen(CryptoContext<Element> cc, bool makeSparse=false) = 0; }; /** * @brief Abstract interface for Leveled SHE operations * @tparam Element a ring element. */ template <class Element> class LPLeveledSHEAlgorithm { public: virtual ~LPLeveledSHEAlgorithm() {} /** * Method for Modulus Reduction. * * @param &cipherText Ciphertext to perform mod reduce on. */ virtual Ciphertext<Element> ModReduce(ConstCiphertext<Element> cipherText) const = 0; /** * Method for rescaling. * * @param cipherText is the ciphertext to perform modreduce on. * @return ciphertext after the modulus reduction performed. */ virtual Ciphertext<Element> ModReduceInternal(ConstCiphertext<Element> cipherText) const { throw std::logic_error("ModReduceInternal is not supported for this scheme"); } /** * Method for Composed EvalMult * * @param &cipherText1 ciphertext1, first input ciphertext to perform multiplication on. * @param &cipherText2 cipherText2, second input ciphertext to perform multiplication on. * @param &quadKeySwitchHint is for resultant quadratic secret key after multiplication to the secret key of the particular level. * @param &cipherTextResult is the resulting ciphertext that can be decrypted with the secret key of the particular level. */ virtual Ciphertext<Element> ComposedEvalMult( ConstCiphertext<Element> cipherText1, ConstCiphertext<Element> cipherText2, const LPEvalKey<Element> quadKeySwitchHint) const = 0; /** * Method for Level Reduction from sk -> sk1. This method peforms a keyswitch on the ciphertext and then performs a modulus reduction. * * @param &cipherText1 is the original ciphertext to be key switched and mod reduced. * @param &linearKeySwitchHint is the linear key switch hint to perform the key switch operation. * @param &cipherTextResult is the resulting ciphertext. */ virtual Ciphertext<Element> LevelReduce(ConstCiphertext<Element> cipherText1, const LPEvalKey<Element> linearKeySwitchHint, size_t levels) const = 0; /** * Method for Level Reduction in the CKKS scheme. It just drops "levels" number of the towers * of the ciphertext without changing the underlying plaintext. * * @param cipherText1 is the original ciphertext to be level reduced. * @param linearKeySwitchHint not used in the CKKS scheme. * @param levels the number of towers to drop. * @return resulting ciphertext. */ virtual Ciphertext<Element> LevelReduceInternal(ConstCiphertext<Element> cipherText1, const LPEvalKey<Element> linearKeySwitchHint, size_t levels) const { throw std::logic_error("LevelReduceInternal is not supported for this scheme"); } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const {} template <class Archive> void load( Archive & ar, std::uint32_t const version ) {} std::string SerializedObjectName() const { return "LeveledSHE"; } }; /** * @brief Abstract interface class for LBC PRE algorithms * @tparam Element a ring element. */ template <class Element> class LPPREAlgorithm { public: virtual ~LPPREAlgorithm() {} /** * Virtual function to generate 1..log(q) encryptions for each bit of the original private key * Variant that uses the public key for the new secret key. * * @param &newKey public key for the new secret key. * @param &origPrivateKey original private key used for decryption. * @param *evalKey the evaluation key. * @return the re-encryption key. */ virtual LPEvalKey<Element> ReKeyGen(const LPPublicKey<Element> newKey, const LPPrivateKey<Element> origPrivateKey) const = 0; /** * Virtual function to define the interface for re-encypting ciphertext using the array generated by ProxyGen * * @param &evalKey proxy re-encryption key. * @param &ciphertext the input ciphertext. * @param publicKey the public key of the recipient of the re-encrypted ciphertext. * @param *newCiphertext the new ciphertext. */ virtual Ciphertext<Element> ReEncrypt(const LPEvalKey<Element> evalKey, ConstCiphertext<Element> ciphertext, const LPPublicKey<Element> publicKey = nullptr) const = 0; }; /** * @brief Abstract interface class for LBC Multiparty algorithms. A version of this multiparty scheme built on the BGV scheme is seen here: * - Asharov G., Jain A., López-Alt A., Tromer E., Vaikuntanathan V., Wichs D. (2012) Multiparty Computation with Low Communication, Computation and Interaction via Threshold FHE. In: Pointcheval D., Johansson T. (eds) Advances in Cryptology – EUROCRYPT 2012. EUROCRYPT 2012. Lecture Notes in Computer Science, vol 7237. Springer, Berlin, Heidelberg * * During offline key generation, this multiparty scheme relies on the clients coordinating their public key generation. To do this, a single client generates a public-secret key pair. * This public key is shared with other keys which use an element in the public key to generate their own public keys. * The clients generate a shared key pair using a scheme-specific approach, then generate re-encryption keys. Re-encryption keys are uploaded to the server. * Clients encrypt data with their public keys and send the encrypted data server. * The data is re-encrypted. Computations are then run on the data. * The result is sent to each of the clients. * One client runs a "Leader" multiparty decryption operation with its own secret key. All other clients run a regular "Main" multiparty decryption with their own secret key. * The resulting partially decrypted ciphertext are then fully decrypted with the decryption fusion algorithms. * * @tparam Element a ring element. */ template <class Element> class LPMultipartyAlgorithm { public: virtual ~LPMultipartyAlgorithm() {} /** * Function to generate public and private keys for multiparty homomrophic encryption in coordination with a leading client that generated a first public key. * * @param cc cryptocontext for the keys to be generated. * @param pk1 private key used for decryption to be fused. * @param makeSparse set to true if ring reduce by a factor of 2 is to be used. * @param pre set to true if proxy re-encryption is used in multi-party protocol * @return key pair including the private and public key */ virtual LPKeyPair<Element> MultipartyKeyGen(CryptoContext<Element> cc, const LPPublicKey<Element> pk1, bool makeSparse=false, bool pre=false) = 0; /** * Function to generate public and private keys for multiparty homomrophic encryption server key pair in coordination with secret keys of clients. * * @param cc cryptocontext for the keys to be generated. * @param secretkeys private keys used for decryption to be fused. * @param makeSparse set to true if ring reduce by a factor of 2 is to be used. * @return key pair including the private and public key */ virtual LPKeyPair<Element> MultipartyKeyGen(CryptoContext<Element> cc, const vector<LPPrivateKey<Element>>& secretKeys, bool makeSparse=false) = 0; /** * Method for main decryption operation run by most decryption clients for multiparty homomorphic encryption * * @param privateKey private key used for decryption. * @param ciphertext ciphertext id decrypted. */ virtual Ciphertext<Element> MultipartyDecryptMain(const LPPrivateKey<Element> privateKey, ConstCiphertext<Element> ciphertext) const = 0; /** * Method for decryption operation run by the lead decryption client for multiparty homomorphic encryption * * @param privateKey private key used for decryption. * @param ciphertext ciphertext id decrypted. */ virtual Ciphertext<Element> MultipartyDecryptLead(const LPPrivateKey<Element> privateKey, ConstCiphertext<Element> ciphertext) const = 0; /** * Method for fusing the partially decrypted ciphertext. * * @param &ciphertextVec ciphertext id decrypted. * @param *plaintext the plaintext output. * @return the decoding result. */ virtual DecryptResult MultipartyDecryptFusion(const vector<Ciphertext<Element>>& ciphertextVec, NativePoly *plaintext) const = 0; /** * Method for fusing the partially decrypted ciphertext. * * @param &ciphertextVec ciphertext id decrypted. * @param *plaintext the plaintext output. * @return the decoding result. */ virtual DecryptResult MultipartyDecryptFusion(const vector<Ciphertext<Element>>& ciphertextVec, Poly *plaintext) const { throw std::logic_error("Decryption to Poly is not supported"); } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const {} template <class Archive> void load( Archive & ar, std::uint32_t const version ) {} std::string SerializedObjectName() const { return "MultiParty"; } }; /** * @brief Abstract interface class for LBC SHE algorithms * @tparam Element a ring element. */ template <class Element> class LPSHEAlgorithm { public: virtual ~LPSHEAlgorithm() {} /** * Virtual function to define the interface for homomorphic addition of ciphertexts. * * @param ciphertext1 the input ciphertext. * @param ciphertext2 the input ciphertext. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalAdd(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2) const = 0; /** * Virtual function to define the interface for homomorphic addition of ciphertexts. * This is the mutable version - input ciphertexts may change (automatically * rescaled, or towers dropped). * * @param ciphertext1 the input ciphertext. * @param ciphertext2 the input ciphertext. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalAddMutable(Ciphertext<Element> &ciphertext1, Ciphertext<Element> &ciphertext2) const { throw std::logic_error("EvalAddMutable is not implemented for this scheme"); } /** * Virtual function to define the interface for homomorphic addition of ciphertexts. * * @param ciphertext the input ciphertext. * @param plaintext the input plaintext. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalAdd(ConstCiphertext<Element> ciphertext, ConstPlaintext plaintext) const = 0; /** * Virtual function to define the interface for homomorphic addition of ciphertexts. * This is the mutable version - input ciphertext may change (automatically * rescaled, or towers dropped). * * @param ciphertext the input ciphertext. * @param plaintext the input plaintext. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalAddMutable(Ciphertext<Element> &ciphertext, Plaintext plaintext) const { throw std::logic_error("EvalAddMutable is not implemented for this scheme"); } /** * Virtual function to define the adding of a scalar to a ciphertext * * @param ciphertext the input ciphertext. * @param constant the input constant. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalAdd(ConstCiphertext<Element> ciphertext, double constant) const { throw std::logic_error("Scalar addition is not implemented for this scheme"); } /** * Virtual function for computing the linear weighted sum of a * vector of ciphertexts. * * @param ciphertexts vector of input ciphertexts. * @param constants vector containing double weights. * @return A ciphertext containing the linear weighted sum. */ virtual Ciphertext<Element> EvalLinearWSum( vector<Ciphertext<Element>> ciphertexts, vector<double> constants) const { std::string errMsg = "EvalLinearWSum is not implemented for this scheme."; throw std::runtime_error(errMsg); } /** * Function for computing the linear weighted sum of a * vector of ciphertexts. This is a mutable method, * meaning that the level/depth of input ciphertexts may change. * * @param ciphertexts vector of input ciphertexts. * @param constants vector containing double weights. * @return A ciphertext containing the linear weighted sum. */ virtual Ciphertext<Element> EvalLinearWSumMutable( vector<Ciphertext<Element>> ciphertexts, vector<double> constants) const { std::string errMsg = "EvalLinearWSumMutable is not implemented for this scheme."; throw std::runtime_error(errMsg); } /** * Virtual function to define the interface for homomorphic subtraction of ciphertexts. * * @param ciphertext1 the input ciphertext. * @param ciphertext2 the input ciphertext. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalSub(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2) const = 0; /** * Virtual function to define the interface for homomorphic subtraction of ciphertexts. * This is the mutable version - input ciphertext may change (automatically * rescaled, or towers dropped). * * @param ciphertext1 the input ciphertext. * @param ciphertext2 the input ciphertext. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalSubMutable(Ciphertext<Element> &ciphertext1, Ciphertext<Element> &ciphertext2) const { throw std::logic_error("EvalSubMutable is not implemented for this scheme"); } /** * Virtual function to define the interface for homomorphic subtraction of ciphertexts. * * @param ciphertext the input ciphertext. * @param plaintext the input plaintext. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalSub(ConstCiphertext<Element> ciphertext, ConstPlaintext plaintext) const = 0; /** * Virtual function to define the interface for homomorphic subtraction of ciphertexts. * This is the mutable version - input ciphertext may change (automatically * rescaled, or towers dropped). * * @param ciphertext the input ciphertext. * @param plaintext the input plaintext. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalSubMutable(Ciphertext<Element> &ciphertext, Plaintext plaintext) const { throw std::logic_error("EvalSubMutable is not implemented for this scheme"); } /** * Virtual function to define the subtraction of a scalar from a ciphertext * * @param ciphertext the input ciphertext. * @param constant the input constant. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalSub(ConstCiphertext<Element> ciphertext, double constant) const { throw std::logic_error("Scalar subtraction is not implemented for this scheme"); } /** * Virtual function to define the interface for multiplicative homomorphic evaluation of ciphertext. * * @param ciphertext1 the input ciphertext. * @param ciphertext2 the input ciphertext. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalMult(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2) const = 0; /** * Virtual function to define the interface for multiplicative homomorphic evaluation of ciphertext. * This is the mutable version - input ciphertexts may change (automatically * rescaled, or towers dropped). * * @param ciphertext1 the input ciphertext. * @param ciphertext2 the input ciphertext. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalMultMutable(Ciphertext<Element> &ciphertext1, Ciphertext<Element> &ciphertext2) const { throw std::logic_error("EvalMultMutable is not implemented for this scheme"); } /** * Virtual function to define the interface for multiplication of ciphertext by plaintext. * * @param ciphertext the input ciphertext. * @param plaintext the input plaintext. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalMult(ConstCiphertext<Element> ciphertext, ConstPlaintext plaintext) const = 0; /** * Virtual function to define the interface for multiplication of ciphertext by plaintext. * This is the mutable version - input ciphertext may change (automatically * rescaled, or towers dropped). * * @param ciphertext the input ciphertext. * @param plaintext the input plaintext. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalMultMutable(Ciphertext<Element> &ciphertext, ConstPlaintext plaintext) const { throw std::logic_error("EvalMultMutable is not implemented for this scheme"); } /** * Virtual function to define the multiplication of a ciphertext by a constant * * @param ciphertext the input ciphertext. * @param constant the input constant. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalMult(ConstCiphertext<Element> ciphertext, double constant) const { throw std::logic_error("Scalar multiplication is not implemented for this scheme"); } /** * Virtual function to define the multiplication of a ciphertext by a constant. * This is the mutable version - input ciphertext may change (automatically * rescaled, or towers dropped). * * @param ciphertext the input ciphertext. * @param constant the input constant. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalMultMutable(Ciphertext<Element> &ciphertext, double constant) const { throw std::logic_error("EvalMultMutable is not implemented for this scheme"); } /** * Virtual function to define the interface for multiplicative homomorphic evaluation of ciphertext using the evaluation key. * * @param &ciphertext1 first input ciphertext. * @param &ciphertext2 second input ciphertext. * @param &ek is the evaluation key to make the newCiphertext decryptable by the same secret key as that of ciphertext1 and ciphertext2. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalMult(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2, const LPEvalKey<Element> ek) const = 0; /** * Virtual function to define the interface for multiplicative homomorphic evaluation of ciphertext using the evaluation key. * This is the mutable version - input ciphertext may change (automatically * rescaled, or towers dropped). * * @param &ciphertext1 first input ciphertext. * @param &ciphertext2 second input ciphertext. * @param &ek is the evaluation key to make the newCiphertext decryptable by the same secret key as that of ciphertext1 and ciphertext2. * @return the new ciphertext. */ virtual Ciphertext<Element> EvalMultMutable(Ciphertext<Element> &ciphertext1, Ciphertext<Element> &ciphertext2, const LPEvalKey<Element> ek) const { throw std::logic_error("EvalMultMutable is not implemented for this scheme"); } /** * Virtual function for evaluating multiplication of a ciphertext list which each multiplication is followed by relinearization operation. * * @param cipherTextList is the ciphertext list. * @param evalKeys is the evaluation key to make the newCiphertext * decryptable by the same secret key as that of ciphertext list. * @param *newCiphertext the new resulting ciphertext. */ virtual Ciphertext<Element> EvalMultMany(const vector<Ciphertext<Element>>& cipherTextList, const vector<LPEvalKey<Element>> &evalKeys) const { // default implementation if you don't have one in your scheme const size_t inSize = cipherTextList.size(); const size_t lim = inSize * 2 - 2; vector<Ciphertext<Element>> cipherTextResults; cipherTextResults.resize(inSize - 1); size_t ctrIndex = 0; for(size_t i=0; i < lim; i = i + 2) { cipherTextResults[ctrIndex++] = this->EvalMult( i < inSize ? cipherTextList[i] : cipherTextResults[i - inSize], i+1 < inSize ? cipherTextList[i+1] : cipherTextResults[i + 1 - inSize]); } return cipherTextResults.back(); } /** * Virtual function for evaluating addition of a list of ciphertexts. * * @param ctList is the ciphertext list. * @param *newCiphertext the new resulting ciphertext. */ virtual Ciphertext<Element> EvalAddMany(const vector<Ciphertext<Element>>& ctList) const { // default implementation if you don't have one in your scheme const size_t inSize = ctList.size(); const size_t lim = inSize * 2 - 2; vector<Ciphertext<Element>> cipherTextResults; cipherTextResults.resize(inSize - 1); size_t ctrIndex = 0; for(size_t i=0; i < lim; i = i + 2) { cipherTextResults[ctrIndex++] = this->EvalAdd( i < inSize ? ctList[i] : cipherTextResults[i - inSize], i+1 < inSize ? ctList[i+1] : cipherTextResults[i + 1 - inSize]); } return cipherTextResults.back(); } /** * Virtual function for evaluating addition of a list of ciphertexts. * This version uses no additional space, other than the vector provided. * * @param ctList is the ciphertext list. * @param *newCiphertext the new resulting ciphertext. */ virtual Ciphertext<Element> EvalAddManyInPlace(vector<Ciphertext<Element>>& ctList) const { // default implementation if you don't have one in your scheme for(size_t j = 1; j < ctList.size(); j=j*2) { for(size_t i = 0; i<ctList.size(); i = i + 2*j) { if ((i+j)<ctList.size()) { if (ctList[i] != nullptr && ctList[i+j] != nullptr) { ctList[i] = EvalAdd(ctList[i],ctList[i+j]); } else if (ctList[i] == nullptr && ctList[i+j] != nullptr) { ctList[i] = ctList[i+j]; } // In all remaining cases (ctList[i+j]), ctList[i] needs to remain unchanged. } } } Ciphertext<Element> result(new CiphertextImpl<Element>(*(ctList[0]))); return result; } /** * Virtual function to define the interface for multiplicative homomorphic evaluation of ciphertext using the evaluation key. * * @param ct1 first input ciphertext. * @param ct2 second input ciphertext. * @param ek is the evaluation key to make the newCiphertext * decryptable by the same secret key as that of ciphertext1 and ciphertext2. * @param *newCiphertext the new resulting ciphertext. */ virtual Ciphertext<Element> EvalMultAndRelinearize(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2, const vector<LPEvalKey<Element>> &ek) const = 0; virtual Ciphertext<Element> Relinearize(ConstCiphertext<Element> ciphertext, const vector<LPEvalKey<Element>> &ek) const { throw std::runtime_error("Relinearize operation not supported"); } /** * EvalLinRegression - Computes the parameter vector for linear regression using the least squares method * @param x - matrix of regressors * @param y - vector of dependent variables * @return the parameter vector using (x^T x)^{-1} x^T y (using least squares method) */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalLinRegression(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y) const { // multiplication is done in reverse order to minimize the number of inner products Matrix<RationalCiphertext<Element>> xTransposed = x->Transpose(); shared_ptr<Matrix<RationalCiphertext<Element>>> result(new Matrix<RationalCiphertext<Element>>(xTransposed * (*y))); Matrix<RationalCiphertext<Element>> xCovariance = xTransposed * (*x); Matrix<RationalCiphertext<Element>> cofactorMatrix = xCovariance.CofactorMatrix(); Matrix<RationalCiphertext<Element>> adjugateMatrix = cofactorMatrix.Transpose(); *result = adjugateMatrix * (*result); RationalCiphertext<Element> determinant; xCovariance.Determinant(&determinant); for (size_t row = 0; row < result->GetRows(); row++) for (size_t col = 0; col < result->GetCols(); col++) (*result)(row, col).SetDenominator(determinant.GetNumerator()); return result; } /** * Virtual function to define the interface for homomorphic negation of ciphertext. * * @param &ciphertext the input ciphertext. * @param *newCiphertext the new ciphertext. */ virtual Ciphertext<Element> EvalNegate(ConstCiphertext<Element> ciphertext) const = 0; /** * Function to add random noise to all plaintext slots except for the first one; used in EvalInnerProduct * * @param &ciphertext the input ciphertext. * @return modified ciphertext */ Ciphertext<Element> AddRandomNoise(ConstCiphertext<Element> ciphertext) const { std::uniform_real_distribution<double> distribution(0.0, 1.0); string kID = ciphertext->GetKeyTag(); const auto cryptoParams = ciphertext->GetCryptoParameters(); const auto encodingParams = cryptoParams->GetEncodingParams(); const auto elementParams = cryptoParams->GetElementParams(); usint n = elementParams->GetRingDimension(); auto cc = ciphertext->GetCryptoContext(); Plaintext plaintext; if (ciphertext->GetEncodingType() == CKKSPacked) { std::vector<std::complex<double>> randomIntVector(n); //first plaintext slot does not need to change randomIntVector[0].real(0); for (usint i = 0; i < n - 1; i++) { randomIntVector[i + 1].real(distribution(PseudoRandomNumberGenerator::GetPRNG())); } plaintext = cc->MakeCKKSPackedPlaintext(randomIntVector,ciphertext->GetDepth()); } else { DiscreteUniformGenerator dug; dug.SetModulus(encodingParams->GetPlaintextModulus()); BigVector randomVector = dug.GenerateVector(n - 1); std::vector<int64_t> randomIntVector(n); //first plaintext slot does not need to change randomIntVector[0] = 0; for (usint i = 0; i < n - 1; i++) { randomIntVector[i + 1] = randomVector[i].ConvertToInt(); } plaintext = cc->MakePackedPlaintext(randomIntVector); } plaintext->Encode(); plaintext->GetElement<Element>().SetFormat(EVALUATION); auto ans = EvalAdd(ciphertext, plaintext); return ans; }; /** * Method for KeySwitchGen * * @param &originalPrivateKey Original private key used for encryption. * @param &newPrivateKey New private key to generate the keyswitch hint. * @param *KeySwitchHint is where the resulting keySwitchHint will be placed. */ virtual LPEvalKey<Element> KeySwitchGen( const LPPrivateKey<Element> originalPrivateKey, const LPPrivateKey<Element> newPrivateKey) const = 0; /** * Method for KeySwitch * * @param &keySwitchHint Hint required to perform the ciphertext switching. * @param &cipherText Original ciphertext to perform switching on. */ virtual Ciphertext<Element> KeySwitch( const LPEvalKey<Element> keySwitchHint, ConstCiphertext<Element> cipherText) const = 0; /** * Method for KeySwitching based on RLWE relinearization (used only for the StSt scheme). * Function to generate 1..log(q) encryptions for each bit of the original private key * * @param &newPublicKey encryption key for the new ciphertext. * @param origPrivateKey original private key used for decryption. */ virtual LPEvalKey<Element> KeySwitchRelinGen(const LPPublicKey<Element> newPublicKey, const LPPrivateKey<Element> origPrivateKey) const = 0; /** * Method for KeySwitching based on RLWE relinearization (used only for the StSt scheme). * * @param evalKey the evaluation key. * @param ciphertext the input ciphertext. * @return the resulting Ciphertext */ virtual Ciphertext<Element> KeySwitchRelin(const LPEvalKey<Element> evalKey, ConstCiphertext<Element> ciphertext) const = 0; /** * Virtual function to define the interface for generating a evaluation key which is used after each multiplication. * * @param &ciphertext1 first input ciphertext. * @param &ciphertext2 second input ciphertext. * @param &ek is the evaluation key to make the newCiphertext decryptable by the same secret key as that of ciphertext1 and ciphertext2. * @param *newCiphertext the new resulting ciphertext. */ virtual LPEvalKey<Element> EvalMultKeyGen( const LPPrivateKey<Element> originalPrivateKey) const = 0; /** * Virtual function to define the interface for generating a evaluation key which is used after each multiplication for depth more than 2. * * @param &originalPrivateKey Original private key used for encryption. * @param *evalMultKeys the resulting evalution key vector list. */ virtual vector<LPEvalKey<Element>> EvalMultKeysGen( const LPPrivateKey<Element> originalPrivateKey) const = 0; /** * Virtual function to generate all isomorphism keys for a given private key * * @param publicKey encryption key for the new ciphertext. * @param origPrivateKey original private key used for decryption. * @param indexList list of automorphism indices to be computed * @return returns the evaluation keys */ virtual shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalAutomorphismKeyGen(const LPPublicKey<Element> publicKey, const LPPrivateKey<Element> origPrivateKey, const std::vector<usint> &indexList) const = 0; /** * Virtual function for the precomputation step of hoisted * automorphisms. * * @param ct the input ciphertext on which to do the precomputation (digit decomposition) */ virtual shared_ptr<vector<Element>> EvalFastRotationPrecompute( ConstCiphertext<Element> cipherText ) const { std::string errMsg = "LPSHEAlgorithm::EvalFastRotationPrecompute is not implemented for this Scheme."; throw std::runtime_error(errMsg); } /** * Virtual function for the automorphism and key switching step of * hoisted automorphisms. * * @param ct the input ciphertext to perform the automorphism on * @param index the index of the rotation. Positive indices correspond to left rotations * and negative indices correspond to right rotations. * @param m is the cyclotomic order * @param digits the digit decomposition created by EvalFastRotationPrecompute at * the precomputation step. */ virtual Ciphertext<Element> EvalFastRotation( ConstCiphertext<Element> cipherText, const usint index, const usint m, const shared_ptr<vector<Element>> digits ) const { std::string errMsg = "LPSHEAlgorithm::EvalFastRotation is not implemented for this Scheme."; throw std::runtime_error(errMsg); } /** * Generates evaluation keys for a list of indices * Currently works only for power-of-two and cyclic-group cyclotomics * * @param publicKey encryption key for the new ciphertext. * @param origPrivateKey original private key used for decryption. * @param indexList list of indices to be computed * @return returns the evaluation keys */ shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalAtIndexKeyGen(const LPPublicKey<Element> publicKey, const LPPrivateKey<Element> origPrivateKey, const std::vector<int32_t> &indexList) const { const auto cryptoParams = origPrivateKey->GetCryptoParameters(); const auto encodingParams = cryptoParams->GetEncodingParams(); const auto elementParams = cryptoParams->GetElementParams(); uint32_t m = elementParams->GetCyclotomicOrder(); std::vector<uint32_t> autoIndices(indexList.size()); if (!(m & (m-1))) { // power-of-two cyclotomics for (size_t i=0; i < indexList.size(); i++) { auto ccInst = origPrivateKey->GetCryptoContext(); // CKKS Packing // if (string(typeid(*this).name()).find("CKKS")!=std::string::npos) if (ccInst->getSchemeId() == "CKKS") autoIndices[i] = FindAutomorphismIndex2nComplex(indexList[i],m); else autoIndices[i] = FindAutomorphismIndex2n(indexList[i],m); } } else // cyclic groups { for (size_t i=0; i < indexList.size(); i++) autoIndices[i] = FindAutomorphismIndexCyclic(indexList[i],m,encodingParams->GetPlaintextGenerator()); } if (publicKey) // NTRU-based scheme return EvalAutomorphismKeyGen(publicKey,origPrivateKey,autoIndices); else // RLWE-based scheme return EvalAutomorphismKeyGen(origPrivateKey,autoIndices); } /** * Virtual function for evaluating automorphism of ciphertext at index i * * @param ciphertext the input ciphertext. * @param i automorphism index * @param &evalKeys - reference to the vector of evaluation keys generated by EvalAutomorphismKeyGen. * @return resulting ciphertext */ virtual Ciphertext<Element> EvalAutomorphism(ConstCiphertext<Element> ciphertext, usint i, const std::map<usint, LPEvalKey<Element>> &evalKeys) const = 0; /** * Moves i-th slot to slot 0 * * @param ciphertext. * @param i the index. * @param &evalAtIndexKeys - reference to the map of evaluation keys generated by EvalAtIndexKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalAtIndex(ConstCiphertext<Element> ciphertext, int32_t index, const std::map<usint, LPEvalKey<Element>> &evalAtIndexKeys) const { const auto cryptoParams = ciphertext->GetCryptoParameters(); const auto encodingParams = cryptoParams->GetEncodingParams(); const auto elementParams = cryptoParams->GetElementParams(); uint32_t m = elementParams->GetCyclotomicOrder(); uint32_t autoIndex; // power-of-two cyclotomics if (!(m & (m-1))) { if (ciphertext->GetEncodingType() == CKKSPacked) autoIndex = FindAutomorphismIndex2nComplex(index,m); else autoIndex = FindAutomorphismIndex2n(index,m); } else // cyclyc-group cyclotomics autoIndex = FindAutomorphismIndexCyclic(index,m,encodingParams->GetPlaintextGenerator()); return EvalAutomorphism(ciphertext,autoIndex,evalAtIndexKeys); } /** * Virtual function to generate automophism keys for a given private key; Uses the private key for encryption * * @param privateKey private key. * @param indexList list of automorphism indices to be computed * @return returns the evaluation keys */ virtual shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalAutomorphismKeyGen(const LPPrivateKey<Element> privateKey, const std::vector<usint> &indexList) const = 0; /** * Virtual function to generate the automorphism keys for EvalSum; works only for packed encoding * * @param privateKey private key. * @return returns the evaluation keys */ shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalSumKeyGen(const LPPrivateKey<Element> privateKey, const LPPublicKey<Element> publicKey) const { const auto cryptoParams = privateKey->GetCryptoParameters(); const auto encodingParams = cryptoParams->GetEncodingParams(); const auto elementParams = cryptoParams->GetElementParams(); usint batchSize = encodingParams->GetBatchSize(); usint m = elementParams->GetCyclotomicOrder(); // stores automorphism indices needed for EvalSum std::vector<usint> indices; if (!(m & (m-1))){ // Check if m is a power of 2 auto ccInst = privateKey->GetCryptoContext(); // CKKS Packing // if (string(typeid(*this).name()).find("CKKS")!=std::string::npos) if (ccInst->getSchemeId() == "CKKS") indices = GenerateIndices2nComplex(batchSize, m); else indices = GenerateIndices_2n(batchSize, m); } else { // Arbitray cyclotomics usint g = encodingParams->GetPlaintextGenerator(); for (int i = 0; i < floor(log2(batchSize)); i++) { indices.push_back(g); g = (g * g) % m; } } if (publicKey) // NTRU-based scheme return EvalAutomorphismKeyGen(publicKey, privateKey, indices); else // Regular RLWE scheme return EvalAutomorphismKeyGen(privateKey, indices); } /** * Virtual function to generate the automorphism keys for EvalSumRows; works only for packed encoding * * @param privateKey private key. * @param publicKey public key. * @param rowSize size of rows in the matrix * @param colSize size of columns in the matrix * @return returns the evaluation keys */ shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalSumRowsKeyGen(const LPPrivateKey<Element> privateKey, const LPPublicKey<Element> publicKey, usint rowSize) const { const auto cryptoParams = privateKey->GetCryptoParameters(); const auto encodingParams = cryptoParams->GetEncodingParams(); const auto elementParams = cryptoParams->GetElementParams(); usint m = elementParams->GetCyclotomicOrder(); // stores automorphism indices needed for EvalSum std::vector<usint> indices; if (!(m & (m-1))){ // Check if m is a power of 2 auto ccInst = privateKey->GetCryptoContext(); // CKKS Packing // if (string(typeid(*this).name()).find("CKKS")!=std::string::npos) if (ccInst->getSchemeId() == "CKKS") indices = GenerateIndices2nComplexRows(rowSize, m); else throw std::runtime_error("Matrix summation of row-vectors is only supported for CKKSPackedEncoding."); } else { // Arbitray cyclotomics throw std::runtime_error("Matrix summation of row-vectors is not supported for arbitrary cyclotomics."); } if (publicKey) // NTRU-based scheme return EvalAutomorphismKeyGen(publicKey, privateKey, indices); else // Regular RLWE scheme return EvalAutomorphismKeyGen(privateKey, indices); } /** * Virtual function to generate the automorphism keys for EvalSumCols; works only for packed encoding * * @param privateKey private key. * @param publicKey public key. * @param rowSize size of rows in the matrix * @param colSize size of columns in the matrix * @return returns the evaluation keys */ shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalSumColsKeyGen(const LPPrivateKey<Element> privateKey, const LPPublicKey<Element> publicKey) const { const auto cryptoParams = privateKey->GetCryptoParameters(); const auto encodingParams = cryptoParams->GetEncodingParams(); const auto elementParams = cryptoParams->GetElementParams(); usint batchSize = encodingParams->GetBatchSize(); usint m = elementParams->GetCyclotomicOrder(); auto ccInst = privateKey->GetCryptoContext(); // CKKS Packing // if (string(typeid(*this).name()).find("CKKS")!=std::string::npos) if (ccInst->getSchemeId() == "CKKS") { // stores automorphism indices needed for EvalSum std::vector<usint> indices; if (!(m & (m-1))){ // Check if m is a power of 2 indices = GenerateIndices2nComplexCols(batchSize, m); } else { // Arbitray cyclotomics throw std::runtime_error("Matrix summation of column-vectors is not supported for arbitrary cyclotomics."); } if (publicKey) // NTRU-based scheme return EvalAutomorphismKeyGen(publicKey, privateKey, indices); else // Regular RLWE scheme return EvalAutomorphismKeyGen(privateKey, indices); } else throw std::runtime_error("Matrix summation of column-vectors is only supported for CKKSPackedEncoding."); } /** * Sums all elements in log (batch size) time - works only with packed encoding * * @param ciphertext the input ciphertext. * @param batchSize size of the batch to be summed up * @param &evalKeys - reference to the map of evaluation keys generated by EvalAutomorphismKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalSum(ConstCiphertext<Element> ciphertext, usint batchSize, const std::map<usint, LPEvalKey<Element>> &evalKeys) const { const shared_ptr<LPCryptoParameters<Element>> cryptoParams = ciphertext->GetCryptoParameters(); Ciphertext<Element> newCiphertext(new CiphertextImpl<Element>(*ciphertext)); const auto encodingParams = cryptoParams->GetEncodingParams(); const auto elementParams = cryptoParams->GetElementParams(); usint m = elementParams->GetCyclotomicOrder(); if ((encodingParams->GetBatchSize() == 0)) throw std::runtime_error("EvalSum: Packed encoding parameters 'batch size' is not set; Please check the EncodingParams passed to the crypto context."); else { if (!(m & (m-1))){ // Check if m is a power of 2 if (ciphertext->GetEncodingType() == CKKSPacked) newCiphertext = EvalSum2nComplex(batchSize, m, evalKeys,newCiphertext); else newCiphertext = EvalSum_2n(batchSize, m, evalKeys,newCiphertext); } else { // Arbitray cyclotomics if (encodingParams->GetPlaintextGenerator() == 0) throw std::runtime_error("EvalSum: Packed encoding parameters 'plaintext generator' is not set; Please check the EncodingParams passed to the crypto context."); else { usint g = encodingParams->GetPlaintextGenerator(); for (int i = 0; i < floor(log2(batchSize)); i++) { auto ea = EvalAutomorphism(newCiphertext, g, evalKeys); newCiphertext = EvalAdd(newCiphertext, ea); g = (g * g) % m; } } } } return newCiphertext; } /** * Sums all elements over row-vectors in a matrix - works only with packed encoding * * @param ciphertext the input ciphertext. * @param rowSize size of rows in the matrix * @param &evalKeys - reference to the map of evaluation keys generated by EvalAutomorphismKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalSumRows(ConstCiphertext<Element> ciphertext, usint rowSize, const std::map<usint, LPEvalKey<Element>> &evalKeys) const { const shared_ptr<LPCryptoParameters<Element>> cryptoParams = ciphertext->GetCryptoParameters(); Ciphertext<Element> newCiphertext(new CiphertextImpl<Element>(*ciphertext)); const auto encodingParams = cryptoParams->GetEncodingParams(); const auto elementParams = cryptoParams->GetElementParams(); usint m = elementParams->GetCyclotomicOrder(); if ((encodingParams->GetBatchSize() == 0)) throw std::runtime_error("EvalSum: Packed encoding parameters 'batch size' is not set; Please check the EncodingParams passed to the crypto context."); else { if (!(m & (m-1))){ // Check if m is a power of 2 if (ciphertext->GetEncodingType() == CKKSPacked) newCiphertext = EvalSum2nComplexRows(rowSize, m, evalKeys,newCiphertext); else throw std::runtime_error("Matrix summation of row-vectors is only supported for CKKS packed encoding."); } else { // Arbitray cyclotomics throw std::runtime_error("Matrix summation of row-vectors is not supported for arbitrary cyclotomics."); } } return newCiphertext; } /** * Sums all elements over column-vectors in a matrix - works only with packed encoding * * @param ciphertext the input ciphertext. * @param rowSize size of rows in the matrixs * @param &evalKeys - reference to the map of evaluation keys generated by EvalAutomorphismKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalSumCols(ConstCiphertext<Element> ciphertext, usint batchSize, const std::map<usint, LPEvalKey<Element>> &evalKeys, const std::map<usint, LPEvalKey<Element>> &rightEvalKeys) const { const shared_ptr<LPCryptoParameters<Element>> cryptoParams = ciphertext->GetCryptoParameters(); Ciphertext<Element> newCiphertext(new CiphertextImpl<Element>(*ciphertext)); const auto encodingParams = cryptoParams->GetEncodingParams(); const auto elementParams = cryptoParams->GetElementParams(); usint m = elementParams->GetCyclotomicOrder(); if ((encodingParams->GetBatchSize() == 0)) throw std::runtime_error("EvalSumCols: Packed encoding parameters 'batch size' is not set; Please check the EncodingParams passed to the crypto context."); else { if (ciphertext->GetEncodingType() == CKKSPacked) { if (!(m & (m-1))){ // Check if m is a power of 2 newCiphertext = EvalSum2nComplex(batchSize, m, evalKeys,newCiphertext); std::vector<std::complex<double>> mask(m/4); for (size_t i = 0; i < mask.size(); i++) { if (i % batchSize == 0) mask[i] = 1; else mask[i] = 0; } auto cc = ciphertext->GetCryptoContext(); Plaintext plaintext = cc->MakeCKKSPackedPlaintext(mask,1); newCiphertext = EvalMult(newCiphertext,plaintext); newCiphertext = EvalSum2nComplexCols(batchSize, m, rightEvalKeys,newCiphertext); } else { // Arbitray cyclotomics throw std::runtime_error("Matrix summation of column-vectors is not supported for arbitrary cyclotomics."); } } else throw std::runtime_error("Matrix summation of column-vectors is only supported for CKKS packed encoding."); } return newCiphertext; } /** * Evaluates inner product in batched encoding * * @param ciphertext1 first vector. * @param ciphertext2 second vector. * @param batchSize size of the batch to be summed up * @param &evalSumKeys - reference to the map of evaluation keys generated by EvalAutomorphismKeyGen. * @param &evalMultKey - reference to the evaluation key generated by EvalMultKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalInnerProduct(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2, usint batchSize, const std::map<usint, LPEvalKey<Element>> &evalSumKeys, const LPEvalKey<Element> evalMultKey) const { Ciphertext<Element> result = EvalMult(ciphertext1, ciphertext2, evalMultKey); result = EvalSum(result, batchSize, evalSumKeys); // add a random number to all slots except for the first one so that no information is leaked //if (ciphertext1->GetEncodingType() != CKKSPacked) // result = AddRandomNoise(result); return result; } /** * Evaluates inner product in batched encoding * * @param ciphertext1 first vector. * @param ciphertext2 plaintext. * @param batchSize size of the batch to be summed up * @param &evalSumKeys - reference to the map of evaluation keys generated by EvalAutomorphismKeyGen. * @param &evalMultKey - reference to the evaluation key generated by EvalMultKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalInnerProduct(ConstCiphertext<Element> ciphertext1, ConstPlaintext ciphertext2, usint batchSize, const std::map<usint, LPEvalKey<Element>> &evalSumKeys) const { Ciphertext<Element> result = EvalMult(ciphertext1, ciphertext2); result = EvalSum(result, batchSize, evalSumKeys); // add a random number to all slots except for the first one so that no information is leaked //if (ciphertext1->GetEncodingType() != CKKSPacked) // result = AddRandomNoise(result); return result; } /** * Merges multiple ciphertexts with encrypted results in slot 0 into a single ciphertext * The slot assignment is done based on the order of ciphertexts in the vector * * @param ciphertextVector vector of ciphertexts to be merged. * @param &evalKeys - reference to the map of evaluation keys generated by EvalAutomorphismKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalMerge(const vector<Ciphertext<Element>> &ciphertextVector, const std::map<usint, LPEvalKey<Element>> &evalKeys) const { if (ciphertextVector.size() == 0) throw std::runtime_error("EvalMerge: the vector of ciphertexts to be merged cannot be empty"); const shared_ptr<LPCryptoParameters<Element>> cryptoParams = ciphertextVector[0]->GetCryptoParameters(); Ciphertext<Element> newCiphertext(new CiphertextImpl<Element>(*(ciphertextVector[0]))); auto cc = ciphertextVector[0]->GetCryptoContext(); Plaintext plaintext; if (ciphertextVector[0]->GetEncodingType() == CKKSPacked){ std::vector<std::complex<double>> plaintextVector({{1,0}, {0,0}}); plaintext = cc->MakeCKKSPackedPlaintext(plaintextVector); } else { std::vector<int64_t> plaintextVector = {1,0}; plaintext = cc->MakePackedPlaintext(plaintextVector); } newCiphertext = EvalMult(newCiphertext,plaintext); for (size_t i = 1; i < ciphertextVector.size(); i++) { newCiphertext = EvalAdd(newCiphertext,EvalAtIndex(EvalMult(ciphertextVector[i],plaintext),-(int32_t)i,evalKeys)); } return newCiphertext; } /** * EvalLinRegressBatched - Computes the parameter vector for linear regression using the least squares method * Currently supports only two regressors * @param x - matrix of regressors * @param y - vector of dependent variables * @return the parameter vector using (x^T x)^{-1} x^T y (using least squares method) */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalLinRegressBatched(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize, const std::map<usint, LPEvalKey<Element>> &evalSumKeys, const LPEvalKey<Element> evalMultKey) const { Matrix<RationalCiphertext<Element>> covarianceMatrix(x->GetAllocator(), 2, 2); Ciphertext<Element> x0 = (*x)(0, 0).GetNumerator(); Ciphertext<Element> x1 = (*x)(0, 1).GetNumerator(); Ciphertext<Element> y0 = (*y)(0, 0).GetNumerator(); //Compute the covariance matrix for X covarianceMatrix(0, 0).SetNumerator(EvalInnerProduct(x0, x0, batchSize, evalSumKeys, evalMultKey)); covarianceMatrix(0, 1).SetNumerator(EvalInnerProduct(x0, x1, batchSize, evalSumKeys, evalMultKey)); covarianceMatrix(1, 0) = covarianceMatrix(0, 1); covarianceMatrix(1, 1).SetNumerator(EvalInnerProduct(x1, x1, batchSize, evalSumKeys, evalMultKey)); Matrix<RationalCiphertext<Element>> cofactorMatrix = covarianceMatrix.CofactorMatrix(); Matrix<RationalCiphertext<Element>> adjugateMatrix = cofactorMatrix.Transpose(); shared_ptr<Matrix<RationalCiphertext<Element>>> result(new Matrix<RationalCiphertext<Element>>(x->GetAllocator(), 2, 1)); (*result)(0, 0).SetNumerator(EvalInnerProduct(x0, y0, batchSize, evalSumKeys, evalMultKey)); (*result)(1, 0).SetNumerator(EvalInnerProduct(x1, y0, batchSize, evalSumKeys, evalMultKey)); *result = adjugateMatrix * (*result); RationalCiphertext<Element> determinant; covarianceMatrix.Determinant(&determinant); for (size_t row = 0; row < result->GetRows(); row++) for (size_t col = 0; col < result->GetCols(); col++) (*result)(row, col).SetDenominator(determinant.GetNumerator()); return result; } /** * EvalCrossCorrelation - Computes the sliding sum of inner products (known as * as cross-correlation, sliding inner product, or sliding dot product in * image processing * @param x - first vector of row vectors * @param y - second vector of row vectors * @param batchSize - batch size for packed encoding * @param indexStart - starting index in the vectors of row vectors * @param length - length of the slice in the vectors of row vectors * @param evalSumKeys - evaluation keys used for the automorphism operation * @param evalMultKey - the evaluation key used for multiplication * @return sum(x_i*y_i), i.e., a sum of inner products */ Ciphertext<Element> EvalCrossCorrelation(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize, usint indexStart, usint length, const std::map<usint, LPEvalKey<Element>> &evalSumKeys, const LPEvalKey<Element> evalMultKey) const { if (length == 0) length = x->GetRows(); if (length - indexStart > x->GetRows()) throw std::runtime_error("The number of rows exceeds the dimension of the vector"); //additional error checking can be added here Ciphertext<Element> result; Ciphertext<Element> x0 = (*x)(indexStart, 0).GetNumerator(); Ciphertext<Element> y0 = (*y)(indexStart, 0).GetNumerator(); result = EvalInnerProduct(x0, y0, batchSize, evalSumKeys, evalMultKey); #pragma omp parallel for ordered schedule(dynamic) for (usint i = indexStart + 1; i < indexStart + length; i++) { Ciphertext<Element> xi = (*x)(i, 0).GetNumerator(); Ciphertext<Element> yi = (*y)(i, 0).GetNumerator(); auto product = EvalInnerProduct(xi, yi, batchSize, evalSumKeys, evalMultKey); #pragma omp ordered { result = EvalAdd(result,product); } } return result; } /* Maintenance procedure used in the exact RNS variant of CKKS * @param c1 input ciphertext. * @param targetLevel The number of the level we want to take this ciphertext * to. Levels are numbered from 0 (all towers) to GetNumberOfTowers()-1 * (one remaining tower). * @return A ciphertext containing the same value as c1, but at level targetLevel. */ virtual Ciphertext<Element> AdjustLevelWithRescale( Ciphertext<Element> &c1, uint32_t targetLevel) const { std::string errMsg = "AdjustLevelWithoutRescale is not implemented for this scheme."; throw std::runtime_error(errMsg); } private: std::vector<usint> GenerateIndices_2n(usint batchSize, usint m) const { // stores automorphism indices needed for EvalSum std::vector<usint> indices; usint g = 5; for (int i = 0; i < ceil(log2(batchSize)) - 1; i++) { indices.push_back(g); g = (g * g) % m; } if (2*batchSize<m) indices.push_back(g); else indices.push_back(m-1); return indices; } std::vector<usint> GenerateIndices2nComplex(usint batchSize, usint m) const { // stores automorphism indices needed for EvalSum std::vector<usint> indices; // generator int32_t g = 5; usint gFinal = g; for (size_t j = 0; j < ceil(log2(batchSize)); j++) { indices.push_back(gFinal); g = (g * g) % m; gFinal = g; } return indices; } std::vector<usint> GenerateIndices2nComplexRows(usint rowSize, usint m) const { // stores automorphism indices needed for EvalSum std::vector<usint> indices; usint colSize = m/(4*rowSize); // generator int32_t g0 = 5; usint g = 0; int32_t f = (NativeInteger(g0).ModExp(rowSize,m)).ConvertToInt(); for (size_t j = 0; j < ceil(log2(colSize)); j++) { g = f; indices.push_back(g); f = (f * f) % m; } return indices; } std::vector<usint> GenerateIndices2nComplexCols(usint batchSize, usint m) const { // stores automorphism indices needed for EvalSum std::vector<usint> indices; // generator int32_t g = NativeInteger(5).ModInverse(m).ConvertToInt(); usint gFinal = g; for (size_t j = 0; j < ceil(log2(batchSize)); j++) { indices.push_back(gFinal); g = (g * g) % m; gFinal = g; } return indices; } Ciphertext<Element> EvalSum_2n(usint batchSize, usint m, const std::map<usint, LPEvalKey<Element>> &evalKeys, ConstCiphertext<Element> ciphertext) const{ Ciphertext<Element> newCiphertext(new CiphertextImpl<Element>(*ciphertext)); usint g = 5; for (int i = 0; i < ceil(log2(batchSize)) - 1; i++) { newCiphertext = EvalAdd(newCiphertext, EvalAutomorphism(newCiphertext, g, evalKeys)); g = (g * g) % m; } if (2*batchSize<m) newCiphertext = EvalAdd(newCiphertext, EvalAutomorphism(newCiphertext, g, evalKeys)); else newCiphertext = EvalAdd(newCiphertext, EvalAutomorphism(newCiphertext, m - 1, evalKeys)); return newCiphertext; } Ciphertext<Element> EvalSum2nComplex(usint batchSize, usint m, const std::map<usint, LPEvalKey<Element>> &evalKeys, ConstCiphertext<Element> ciphertext) const{ Ciphertext<Element> newCiphertext(new CiphertextImpl<Element>(*ciphertext)); // generator int32_t g = 5; usint gFinal = g; for (int i = 0; i < ceil(log2(batchSize)); i++) { newCiphertext = EvalAdd(newCiphertext, EvalAutomorphism(newCiphertext, gFinal, evalKeys)); g = (g * g) % m; gFinal = g; } return newCiphertext; } Ciphertext<Element> EvalSum2nComplexRows(usint rowSize, usint m, const std::map<usint, LPEvalKey<Element>> &evalKeys, ConstCiphertext<Element> ciphertext) const{ Ciphertext<Element> newCiphertext(new CiphertextImpl<Element>(*ciphertext)); usint colSize = m/(4*rowSize); // generator int32_t g0 = 5; usint g = 0; int32_t f = (NativeInteger(g0).ModExp(rowSize,m)).ConvertToInt(); for (size_t j = 0; j < ceil(log2(colSize)); j++) { g = f; newCiphertext = EvalAdd(newCiphertext, EvalAutomorphism(newCiphertext, g, evalKeys)); f = (f * f) % m; } return newCiphertext; } Ciphertext<Element> EvalSum2nComplexCols(usint batchSize, usint m, const std::map<usint, LPEvalKey<Element>> &evalKeys, ConstCiphertext<Element> ciphertext) const{ Ciphertext<Element> newCiphertext(new CiphertextImpl<Element>(*ciphertext)); // generator int32_t g = NativeInteger(5).ModInverse(m).ConvertToInt(); usint gFinal = g; for (int i = 0; i < ceil(log2(batchSize)); i++) { newCiphertext = EvalAdd(newCiphertext, EvalAutomorphism(newCiphertext, gFinal, evalKeys)); g = (g * g) % m; gFinal = g; } return newCiphertext; } }; /** * @brief main implementation class to capture essential cryptoparameters of any LBC system * @tparam Element a ring element. */ template <typename Element> class LPCryptoParameters : public Serializable { public: LPCryptoParameters() {} virtual ~LPCryptoParameters() {} /** * Returns the value of plaintext modulus p * * @return the plaintext modulus. */ const PlaintextModulus &GetPlaintextModulus() const { return m_encodingParams->GetPlaintextModulus(); } /** * Returns the reference to IL params * * @return the ring element parameters. */ const shared_ptr<typename Element::Params> GetElementParams() const { return m_params; } /** * Returns the reference to encoding params * * @return the encoding parameters. */ const EncodingParams GetEncodingParams() const { return m_encodingParams; } /** * Sets the value of plaintext modulus p */ void SetPlaintextModulus(const PlaintextModulus &plaintextModulus) { m_encodingParams->SetPlaintextModulus(plaintextModulus); } virtual bool operator==(const LPCryptoParameters<Element>& cmp) const = 0; bool operator!=(const LPCryptoParameters<Element>& cmp) const { return !(*this == cmp); } /** * Overload to allow printing of parameters to an iostream * NOTE that the implementation relies on calling the virtual PrintParameters method * @param out - the stream to print to * @param item - reference to the item to print * @return the stream */ friend std::ostream& operator<<(std::ostream& out, const LPCryptoParameters& item) { item.PrintParameters(out); return out; } virtual usint GetRelinWindow() const { return 0; } virtual int GetDepth() const { return 0; } virtual size_t GetMaxDepth() const { return 0; } virtual const typename Element::DggType &GetDiscreteGaussianGenerator() const { throw std::logic_error("No DGG Available for this parameter set"); } /** * Sets the reference to element params */ void SetElementParams(shared_ptr<typename Element::Params> params) { m_params = params; } /** * Sets the reference to encoding params */ void SetEncodingParams(EncodingParams encodingParams) { m_encodingParams = encodingParams; } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::make_nvp("elp", m_params) ); ar( ::cereal::make_nvp("enp", m_encodingParams) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { if( version > SerializedVersion() ) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } ar( ::cereal::make_nvp("elp", m_params) ); ar( ::cereal::make_nvp("enp", m_encodingParams) ); } std::string SerializedObjectName() const { return "CryptoParameters"; } static uint32_t SerializedVersion() { return 1; } protected: LPCryptoParameters(const PlaintextModulus &plaintextModulus) { m_encodingParams.reset( new EncodingParamsImpl(plaintextModulus) ); } LPCryptoParameters(shared_ptr<typename Element::Params> params, const PlaintextModulus &plaintextModulus) { m_params = params; m_encodingParams.reset( new EncodingParamsImpl(plaintextModulus) ); } LPCryptoParameters(shared_ptr<typename Element::Params> params, EncodingParams encodingParams) { m_params = params; m_encodingParams = encodingParams; } LPCryptoParameters(LPCryptoParameters<Element> *from, shared_ptr<typename Element::Params> newElemParms) { *this = *from; m_params = newElemParms; } virtual void PrintParameters(std::ostream& out) const { out << "Element Parameters: " << *m_params << std::endl; out << "Encoding Parameters: " << *m_encodingParams << std::endl; } private: //element-specific parameters shared_ptr<typename Element::Params> m_params; //encoding-specific parameters EncodingParams m_encodingParams; }; // forward decl so SchemeIdentifier works template<typename Element> class LPPublicKeyEncryptionScheme; template<typename Element> class PalisadeSchemeIdentifier { string schemeName; LPPublicKeyEncryptionScheme<Element> *(*schemeMaker)(); public: PalisadeSchemeIdentifier(string n, LPPublicKeyEncryptionScheme<Element> (*f)()) : schemeName(n), schemeMaker(f) {} const string& GetName() const { return schemeName; } LPPublicKeyEncryptionScheme<Element> *GetScheme() const { return (*schemeMaker)(); } }; /** * @brief Abstract interface for public key encryption schemes * @tparam Element a ring element. */ template<typename Element> class LPPublicKeyEncryptionScheme { protected: //PalisadeSchemeIdentifier<Element> *SchemeId; public: LPPublicKeyEncryptionScheme() {} virtual ~LPPublicKeyEncryptionScheme() {} virtual bool operator==(const LPPublicKeyEncryptionScheme& sch) const = 0; bool operator!=(const LPPublicKeyEncryptionScheme& sch) const { return !(*this == sch); } /** * Enable features with a bit mast of PKESchemeFeature codes * @param mask */ virtual void Enable(usint mask) { if (mask&ENCRYPTION) Enable(ENCRYPTION); if (mask&PRE) Enable(PRE); if (mask&SHE) Enable(SHE); if (mask&LEVELEDSHE) Enable(LEVELEDSHE); if (mask&MULTIPARTY) Enable(MULTIPARTY); } virtual usint GetEnabled() const { usint flag = 0; if (m_algorithmEncryption != NULL) flag |= ENCRYPTION; if (m_algorithmPRE != NULL) flag |= PRE; if (m_algorithmSHE != NULL) flag |= SHE; if (m_algorithmLeveledSHE != NULL) flag |= LEVELEDSHE; if (m_algorithmMultiparty != NULL) flag |= MULTIPARTY; return flag; } //instantiated in the scheme implementation class virtual void Enable(PKESchemeFeature feature) = 0; ///////////////////////////////////////// // wrapper for LPParameterSelectionAlgorithm // bool ParamsGen(shared_ptr<LPCryptoParameters<Element>> cryptoParams, int32_t evalAddCount = 0, int32_t evalMultCount = 0, int32_t keySwitchCount = 0, size_t dcrtBits = 0, uint32_t n = 0) const { if (this->m_algorithmParamsGen) { return this->m_algorithmParamsGen->ParamsGen(cryptoParams, evalAddCount, evalMultCount, keySwitchCount, dcrtBits, n); } else { throw std::logic_error("Parameter generation operation has not been implemented"); } } ///////////////////////////////////////// // the three functions below are wrappers for things in LPEncryptionAlgorithm (ENCRYPT) // Ciphertext<Element> Encrypt(const LPPublicKey<Element> publicKey, const Element &plaintext) const { if(this->m_algorithmEncryption) { return this->m_algorithmEncryption->Encrypt(publicKey,plaintext); } else { throw std::logic_error("Encrypt operation has not been enabled"); } } Ciphertext<Element> Encrypt(const LPPrivateKey<Element> privateKey, const Element &plaintext) const { if(this->m_algorithmEncryption) { return this->m_algorithmEncryption->Encrypt(privateKey,plaintext); } else { throw std::logic_error("Encrypt operation has not been enabled"); } } DecryptResult Decrypt(const LPPrivateKey<Element> privateKey, ConstCiphertext<Element> ciphertext, NativePoly *plaintext) const { if(this->m_algorithmEncryption) return this->m_algorithmEncryption->Decrypt(privateKey,ciphertext,plaintext); else { throw std::logic_error("Decrypt operation has not been enabled"); } } DecryptResult Decrypt(const LPPrivateKey<Element> privateKey, ConstCiphertext<Element> ciphertext, Poly *plaintext) const { if(this->m_algorithmEncryption) return this->m_algorithmEncryption->Decrypt(privateKey,ciphertext,plaintext); else { throw std::logic_error("Decrypt operation has not been enabled"); } } LPKeyPair<Element> KeyGen(CryptoContext<Element> cc, bool makeSparse) { if(this->m_algorithmEncryption) { auto kp = this->m_algorithmEncryption->KeyGen(cc, makeSparse); kp.publicKey->SetKeyTag( kp.secretKey->GetKeyTag() ); return kp; } else { throw std::logic_error("KeyGen operation has not been enabled"); } } ///////////////////////////////////////// // the three functions below are wrappers for things in LPPREAlgorithm (PRE) // LPEvalKey<Element> ReKeyGen(const LPPublicKey<Element> newKey, const LPPrivateKey<Element> origPrivateKey) const { if(this->m_algorithmPRE) { auto rk = this->m_algorithmPRE->ReKeyGen(newKey,origPrivateKey); rk->SetKeyTag( newKey->GetKeyTag() ); return rk; } else { throw std::logic_error("ReKeyGen operation has not been enabled"); } } Ciphertext<Element> ReEncrypt(const LPEvalKey<Element> evalKey, ConstCiphertext<Element> ciphertext, const LPPublicKey<Element> publicKey) const { if(this->m_algorithmPRE) { auto ct = this->m_algorithmPRE->ReEncrypt(evalKey, ciphertext, publicKey); ct->SetKeyTag( evalKey->GetKeyTag() ); return ct; } else { throw std::logic_error("ReEncrypt operation has not been enabled"); } } ///////////////////////////////////////// // the three functions below are wrappers for things in LPMultipartyAlgorithm (Multiparty) // // Wrapper for Multiparty Key Gen // FIXME check key ID for multiparty LPKeyPair<Element> MultipartyKeyGen(CryptoContext<Element> cc, const LPPublicKey<Element> pk1, bool makeSparse, bool PRE) { if(this->m_algorithmMultiparty) { auto k = this->m_algorithmMultiparty->MultipartyKeyGen(cc, pk1, makeSparse, PRE); k.publicKey->SetKeyTag( k.secretKey->GetKeyTag() ); return k; } else { throw std::logic_error("MultipartyKeyGen operation has not been enabled"); } } // Wrapper for Multiparty Key Gen // FIXME key IDs for multiparty LPKeyPair<Element> MultipartyKeyGen(CryptoContext<Element> cc, const vector<LPPrivateKey<Element>>& secretKeys, bool makeSparse) { if(this->m_algorithmMultiparty) { auto k = this->m_algorithmMultiparty->MultipartyKeyGen(cc, secretKeys, makeSparse); k.publicKey->SetKeyTag( k.secretKey->GetKeyTag() ); return k; } else { throw std::logic_error("MultipartyKeyGen operation has not been enabled"); } } // FIXME key IDs for multiparty Ciphertext<Element> MultipartyDecryptMain(const LPPrivateKey<Element> privateKey, ConstCiphertext<Element> ciphertext) const { if(this->m_algorithmMultiparty) { auto ct = this->m_algorithmMultiparty->MultipartyDecryptMain(privateKey,ciphertext); ct->SetKeyTag( privateKey->GetKeyTag() ); return ct; } else { throw std::logic_error("MultipartyDecryptMain operation has not been enabled"); } } // FIXME key IDs for multiparty Ciphertext<Element> MultipartyDecryptLead(const LPPrivateKey<Element> privateKey, ConstCiphertext<Element> ciphertext) const { if(this->m_algorithmMultiparty) { auto ct = this->m_algorithmMultiparty->MultipartyDecryptLead(privateKey,ciphertext); ct->SetKeyTag( privateKey->GetKeyTag() ); return ct; } else { throw std::logic_error("MultipartyDecryptLead operation has not been enabled"); } } DecryptResult MultipartyDecryptFusion(const vector<Ciphertext<Element>>& ciphertextVec, NativePoly *plaintext) const { if(this->m_algorithmMultiparty) { return this->m_algorithmMultiparty->MultipartyDecryptFusion(ciphertextVec,plaintext); } else { throw std::logic_error("MultipartyDecrypt operation has not been enabled"); } } DecryptResult MultipartyDecryptFusion(const vector<Ciphertext<Element>>& ciphertextVec, Poly *plaintext) const { if(this->m_algorithmMultiparty) { return this->m_algorithmMultiparty->MultipartyDecryptFusion(ciphertextVec,plaintext); } else { throw std::logic_error("MultipartyDecrypt operation has not been enabled"); } } ///////////////////////////////////////// // the three functions below are wrappers for things in LPSHEAlgorithm (SHE) // Ciphertext<Element> AddRandomNoise(ConstCiphertext<Element> ciphertext) const { if (this->m_algorithmSHE) return this->m_algorithmSHE->AddRandomNoise(ciphertext); else { throw std::logic_error("AddRandomNoise operation has not been enabled"); } } Ciphertext<Element> EvalAdd(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalAdd(ciphertext1, ciphertext2); return ct; } else { throw std::logic_error("EvalAdd operation has not been enabled"); } } Ciphertext<Element> EvalAddMutable(Ciphertext<Element> &ciphertext1, Ciphertext<Element> &ciphertext2) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalAddMutable(ciphertext1, ciphertext2); return ct; } else { throw std::logic_error("EvalAdd operation has not been enabled"); } } Ciphertext<Element> EvalAdd(ConstCiphertext<Element> ciphertext1, ConstPlaintext plaintext) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalAdd(ciphertext1, plaintext); return ct; } else { throw std::logic_error("EvalAdd operation has not been enabled"); } } Ciphertext<Element> EvalAddMutable(Ciphertext<Element> &ciphertext1, Plaintext plaintext) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalAddMutable(ciphertext1, plaintext); return ct; } else { throw std::logic_error("EvalAdd operation has not been enabled"); } } Ciphertext<Element> EvalAdd(ConstCiphertext<Element> ciphertext1, double constant) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalAdd(ciphertext1, constant); return ct; } else { throw std::logic_error("EvalAdd operation has not been enabled"); } } Ciphertext<Element> EvalLinearWSum( vector<Ciphertext<Element>> ciphertexts, vector<double> constants) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalLinearWSum(ciphertexts, constants); return ct; } else { throw std::logic_error("EvalLinearWSum operation has not been enabled"); } } Ciphertext<Element> EvalLinearWSumMutable( vector<Ciphertext<Element>> ciphertexts, vector<double> constants) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalLinearWSumMutable(ciphertexts, constants); return ct; } else { throw std::logic_error("EvalLinearWSum operation has not been enabled"); } } Ciphertext<Element> EvalSub(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalSub(ciphertext1, ciphertext2); return ct; } else { throw std::logic_error("EvalSub operation has not been enabled"); } } Ciphertext<Element> EvalSubMutable(Ciphertext<Element> &ciphertext1, Ciphertext<Element> &ciphertext2) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalSubMutable(ciphertext1, ciphertext2); return ct; } else { throw std::logic_error("EvalSub operation has not been enabled"); } } Ciphertext<Element> EvalSub(ConstCiphertext<Element> ciphertext1, ConstPlaintext plaintext) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalSub(ciphertext1, plaintext); return ct; } else { throw std::logic_error("EvalSub operation has not been enabled"); } } Ciphertext<Element> EvalSubMutable(Ciphertext<Element> &ciphertext1, Plaintext plaintext) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalSubMutable(ciphertext1, plaintext); return ct; } else { throw std::logic_error("EvalSub operation has not been enabled"); } } Ciphertext<Element> EvalSub(ConstCiphertext<Element> ciphertext1, double constant) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalSub(ciphertext1, constant); return ct; } else { throw std::logic_error("EvalSub operation has not been enabled"); } } Ciphertext<Element> EvalMult(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalMult(ciphertext1, ciphertext2); return ct; } else { throw std::logic_error("EvalMult operation has not been enabled"); } } Ciphertext<Element> EvalMultMutable(Ciphertext<Element> &ciphertext1, Ciphertext<Element> &ciphertext2) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalMultMutable(ciphertext1, ciphertext2); return ct; } else { throw std::logic_error("EvalMult operation has not been enabled"); } } Ciphertext<Element> EvalMult(ConstCiphertext<Element> ciphertext, ConstPlaintext plaintext) const { if (this->m_algorithmSHE) return this->m_algorithmSHE->EvalMult(ciphertext, plaintext); else { throw std::logic_error("EvalMult operation has not been enabled"); } } Ciphertext<Element> EvalMultMutable(Ciphertext<Element> &ciphertext, ConstPlaintext plaintext) const { if (this->m_algorithmSHE) return this->m_algorithmSHE->EvalMultMutable(ciphertext, plaintext); else { throw std::logic_error("EvalMult operation has not been enabled"); } } Ciphertext<Element> EvalMult(ConstCiphertext<Element> ciphertext1, double constant) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalMult(ciphertext1, constant); return ct; } else { throw std::logic_error("EvalMult operation has not been enabled"); } } Ciphertext<Element> EvalMultMutable(Ciphertext<Element> &ciphertext1, double constant) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalMultMutable(ciphertext1, constant); return ct; } else { throw std::logic_error("EvalMult operation has not been enabled"); } } Ciphertext<Element> EvalMult(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2, const LPEvalKey<Element> evalKey) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalMult(ciphertext1, ciphertext2, evalKey); return ct; } else { throw std::logic_error("EvalMult operation has not been enabled"); } } Ciphertext<Element> EvalMultMutable(Ciphertext<Element> &ciphertext1, Ciphertext<Element> &ciphertext2, const LPEvalKey<Element> evalKey) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalMultMutable(ciphertext1, ciphertext2, evalKey); return ct; } else { throw std::logic_error("EvalMult operation has not been enabled"); } } Ciphertext<Element> EvalMultMany(const vector<Ciphertext<Element>>& ciphertext, const vector<LPEvalKey<Element>> &evalKeys) const { if (this->m_algorithmSHE){ return this->m_algorithmSHE->EvalMultMany(ciphertext, evalKeys); } else { throw std::logic_error("EvalMultMany operation has not been enabled"); } } Ciphertext<Element> EvalAddMany( const vector<Ciphertext<Element>>& ciphertexts) const { if (this->m_algorithmSHE){ return this->m_algorithmSHE->EvalAddMany(ciphertexts); } else { throw std::logic_error("EvalMultMany operation has not been enabled"); } } Ciphertext<Element> EvalAddManyInPlace( vector<Ciphertext<Element>>& ciphertexts) const { if (this->m_algorithmSHE){ return this->m_algorithmSHE->EvalAddManyInPlace(ciphertexts); } else { throw std::logic_error("EvalAddManyInPlace operation has not been enabled"); } } Ciphertext<Element> EvalNegate(ConstCiphertext<Element> ciphertext) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalNegate(ciphertext); return ct; } else { throw std::logic_error("EvalNegate operation has not been enabled"); } } shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalAutomorphismKeyGen(const LPPublicKey<Element> publicKey, const LPPrivateKey<Element> origPrivateKey, const std::vector<usint> &indexList) const { if (this->m_algorithmSHE) { auto km = this->m_algorithmSHE->EvalAutomorphismKeyGen(publicKey,origPrivateKey,indexList); for( auto& k : *km ) k.second->SetKeyTag( origPrivateKey->GetKeyTag() ); return km; } else throw std::logic_error("EvalAutomorphismKeyGen operation has not been enabled"); } shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalAtIndexKeyGen(const LPPublicKey<Element> publicKey, const LPPrivateKey<Element> origPrivateKey, const std::vector<int32_t> &indexList) const { if (this->m_algorithmSHE) { auto km = this->m_algorithmSHE->EvalAtIndexKeyGen(publicKey,origPrivateKey,indexList); for( auto& k : *km ) k.second->SetKeyTag( origPrivateKey->GetKeyTag() ); return km; } else throw std::logic_error("EvalAtIndexKeyGen operation has not been enabled"); } Ciphertext<Element> EvalAutomorphism(ConstCiphertext<Element> ciphertext, usint i, const std::map<usint, LPEvalKey<Element>> &evalKeys) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalAutomorphism(ciphertext, i, evalKeys); return ct; } else throw std::logic_error("EvalAutomorphism operation has not been enabled"); } Ciphertext<Element> EvalAtIndex(ConstCiphertext<Element> ciphertext, usint i, const std::map<usint, LPEvalKey<Element>> &evalKeys) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalAtIndex(ciphertext, i, evalKeys); return ct; } else throw std::logic_error("EvalAtIndex operation has not been enabled"); } shared_ptr<vector<Element>> EvalFastRotationPrecompute( ConstCiphertext<Element> ciphertext ) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalFastRotationPrecompute(ciphertext); return ct; } else throw std::logic_error("EvalFastRotationPrecompute operation has not been enabled"); } Ciphertext<Element> EvalFastRotation( ConstCiphertext<Element> ciphertext, const usint index, const usint m, const shared_ptr<vector<Element>> digits ) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalFastRotation(ciphertext, index, m, digits); return ct; } else throw std::logic_error("EvalFastRotation operation has not been enabled"); } shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalAutomorphismKeyGen(const LPPrivateKey<Element> privateKey, const std::vector<usint> &indexList) const { if (this->m_algorithmSHE) { auto km = this->m_algorithmSHE->EvalAutomorphismKeyGen(privateKey, indexList); for( auto& k : *km ) k.second->SetKeyTag( privateKey->GetKeyTag() ); return km; } else throw std::logic_error("EvalAutomorphismKeyGen operation has not been enabled"); } shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalSumKeyGen( const LPPrivateKey<Element> privateKey, const LPPublicKey<Element> publicKey) const { if (this->m_algorithmSHE) { auto km = this->m_algorithmSHE->EvalSumKeyGen(privateKey,publicKey); for( auto& k : *km ) { k.second->SetKeyTag( privateKey->GetKeyTag() ); } return km; } else throw std::logic_error("EvalSumKeyGen operation has not been enabled"); } shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalSumRowsKeyGen( const LPPrivateKey<Element> privateKey, const LPPublicKey<Element> publicKey, usint rowSize) const { if (this->m_algorithmSHE) { auto km = this->m_algorithmSHE->EvalSumRowsKeyGen(privateKey,publicKey,rowSize); for( auto& k : *km ) { k.second->SetKeyTag( privateKey->GetKeyTag() ); } return km; } else throw std::logic_error("EvalSumRowsKeyGen operation has not been enabled"); } shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalSumColsKeyGen( const LPPrivateKey<Element> privateKey, const LPPublicKey<Element> publicKey) const { if (this->m_algorithmSHE) { auto km = this->m_algorithmSHE->EvalSumColsKeyGen(privateKey,publicKey); for( auto& k : *km ) { k.second->SetKeyTag( privateKey->GetKeyTag() ); } return km; } else throw std::logic_error("EvalSumColsKeyGen operation has not been enabled"); } Ciphertext<Element> EvalSum(ConstCiphertext<Element> ciphertext, usint batchSize, const std::map<usint, LPEvalKey<Element>> &evalKeys) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalSum(ciphertext, batchSize, evalKeys); return ct; } else throw std::logic_error("EvalSum operation has not been enabled"); } Ciphertext<Element> EvalSumRows(ConstCiphertext<Element> ciphertext, usint rowSize, const std::map<usint, LPEvalKey<Element>> &evalKeys) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalSumRows(ciphertext, rowSize, evalKeys); return ct; } else throw std::logic_error("EvalSumRow operation has not been enabled"); } Ciphertext<Element> EvalSumCols(ConstCiphertext<Element> ciphertext, usint batchSize, const std::map<usint, LPEvalKey<Element>> &evalKeys, const std::map<usint, LPEvalKey<Element>> &rightEvalKeys) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalSumCols(ciphertext, batchSize, evalKeys, rightEvalKeys); return ct; } else throw std::logic_error("EvalSumCols operation has not been enabled"); } Ciphertext<Element> EvalInnerProduct(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2, usint batchSize, const std::map<usint, LPEvalKey<Element>> &evalSumKeys, const LPEvalKey<Element> evalMultKey) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalInnerProduct(ciphertext1, ciphertext2, batchSize, evalSumKeys, evalMultKey); ct->SetKeyTag( evalSumKeys.begin()->second->GetKeyTag() ); return ct; } else throw std::logic_error("EvalInnerProduct operation has not been enabled"); } Ciphertext<Element> EvalMerge(const vector<Ciphertext<Element>> &ciphertextVector, const std::map<usint, LPEvalKey<Element>> &evalKeys) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalMerge(ciphertextVector,evalKeys); return ct; } else throw std::logic_error("EvalMerge operation has not been enabled"); } Ciphertext<Element> EvalInnerProduct(ConstCiphertext<Element> ciphertext1, ConstPlaintext ciphertext2, usint batchSize, const std::map<usint, LPEvalKey<Element>> &evalSumKeys) const { if (this->m_algorithmSHE) return this->m_algorithmSHE->EvalInnerProduct(ciphertext1, ciphertext2, batchSize, evalSumKeys); else throw std::logic_error("EvalInnerProduct operation has not been enabled"); } shared_ptr<Matrix<RationalCiphertext<Element>>> EvalLinRegressBatched(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize, const std::map<usint, LPEvalKey<Element>> &evalSumKeys, const LPEvalKey<Element> evalMultKey) const { if (this->m_algorithmSHE) { string kID = evalMultKey->GetKeyTag(); auto ctm = this->m_algorithmSHE->EvalLinRegressBatched(x, y, batchSize, evalSumKeys, evalMultKey); for( size_t r = 0; r < ctm->GetRows(); r++ ) for( size_t c = 0; c < ctm->GetCols(); c++ ) (*ctm)(r,c).SetKeyTag(kID); return ctm; } else throw std::logic_error("EvalLinRegressionBatched operation has not been enabled"); } Ciphertext<Element> EvalCrossCorrelation(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize, usint indexStart, usint length, const std::map<usint, LPEvalKey<Element>> &evalSumKeys, const LPEvalKey<Element> evalMultKey) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->EvalCrossCorrelation(x, y, batchSize, indexStart, length, evalSumKeys, evalMultKey); // FIXME: mark with which key? return ct; } else throw std::logic_error("EvalCrossCorrelation operation has not been enabled"); } /** * EvalLinRegression - Computes the parameter vector for linear regression using the least squares method * @param x - matrix of regressors * @param y - vector of dependent variables * @return the parameter vector using (x^T x)^{-1} x^T y (using least squares method) */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalLinRegression(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y) const { if (this->m_algorithmSHE) { auto ctm = this->m_algorithmSHE->EvalLinRegression(x, y); // FIXME mark with which key?? return ctm; } else { throw std::logic_error("EvalLinRegression operation has not been enabled"); } } LPEvalKey<Element> KeySwitchGen( const LPPrivateKey<Element> originalPrivateKey, const LPPrivateKey<Element> newPrivateKey) const { if (this->m_algorithmSHE) { auto kp = this->m_algorithmSHE->KeySwitchGen(originalPrivateKey, newPrivateKey); kp->SetKeyTag( newPrivateKey->GetKeyTag() ); return kp; } else { throw std::logic_error("KeySwitchGen operation has not been enabled"); } } Ciphertext<Element> KeySwitch( const LPEvalKey<Element> keySwitchHint, ConstCiphertext<Element> cipherText) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->KeySwitch(keySwitchHint, cipherText); return ct; } else { throw std::logic_error("KeySwitch operation has not been enabled"); } } LPEvalKey<Element> KeySwitchRelinGen(const LPPublicKey<Element> newKey, const LPPrivateKey<Element> origPrivateKey) const { if (this->m_algorithmSHE) { auto kp = this->m_algorithmSHE->KeySwitchRelinGen(newKey, origPrivateKey); kp->SetKeyTag( newKey->GetKeyTag() ); return kp; } else { throw std::logic_error("KeySwitchRelinGen operation has not been enabled"); } } Ciphertext<Element> KeySwitchRelin(const LPEvalKey<Element> evalKey, ConstCiphertext<Element> ciphertext) const { if (this->m_algorithmSHE) { auto ct = this->m_algorithmSHE->KeySwitchRelin(evalKey, ciphertext); ct->SetKeyTag( evalKey->GetKeyTag() ); return ct; } else { throw std::logic_error("KeySwitchRelin operation has not been enabled"); } } LPEvalKey<Element> EvalMultKeyGen(const LPPrivateKey<Element> originalPrivateKey) const { if(this->m_algorithmSHE) { auto ek = this->m_algorithmSHE->EvalMultKeyGen(originalPrivateKey); ek->SetKeyTag( originalPrivateKey->GetKeyTag() ); return ek; } else { throw std::logic_error("EvalMultKeyGen operation has not been enabled"); } } vector<LPEvalKey<Element>> EvalMultKeysGen(const LPPrivateKey<Element> originalPrivateKey) const { if(this->m_algorithmSHE){ auto ek = this->m_algorithmSHE->EvalMultKeysGen(originalPrivateKey); for(size_t i=0; i<ek.size(); i++) ek[i]->SetKeyTag( originalPrivateKey->GetKeyTag() ); return ek; } else { throw std::logic_error("EvalMultKeysGen operation has not been enabled"); } } Ciphertext<Element> EvalMultAndRelinearize(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2, const vector<LPEvalKey<Element>> &ek) const { if(this->m_algorithmSHE) return this->m_algorithmSHE->EvalMultAndRelinearize(ct1, ct2, ek); else { throw std::logic_error("EvalMultAndRelinearize operation has not been enabled"); } } Ciphertext<Element> Relinearize(ConstCiphertext<Element> ciphertext, const vector<LPEvalKey<Element>> &ek) const { if(this->m_algorithmSHE) return this->m_algorithmSHE->Relinearize(ciphertext, ek); else { throw std::logic_error("Relinearize operation has not been enabled"); } } ///////////////////////////////////////// // the functions below are wrappers for things in LPFHEAlgorithm (FHE) // // TODO: Add Bootstrap and any other FHE methods ///////////////////////////////////////// // the functions below are wrappers for things in LPSHEAlgorithm (SHE) // Ciphertext<Element> ModReduce(ConstCiphertext<Element> cipherText) const { if(this->m_algorithmLeveledSHE) { auto ct = this->m_algorithmLeveledSHE->ModReduce(cipherText); ct->SetKeyTag( cipherText->GetKeyTag() ); return ct; } else{ throw std::logic_error("ModReduce operation has not been enabled"); } } Ciphertext<Element> ComposedEvalMult( ConstCiphertext<Element> cipherText1, ConstCiphertext<Element> cipherText2, const LPEvalKey<Element> quadKeySwitchHint) const { if(this->m_algorithmLeveledSHE){ auto ct = this->m_algorithmLeveledSHE->ComposedEvalMult(cipherText1,cipherText2,quadKeySwitchHint); ct->SetKeyTag( quadKeySwitchHint->GetKeyTag() ); return ct; } else{ throw std::logic_error("ComposedEvalMult operation has not been enabled"); } } Ciphertext<Element> LevelReduce(ConstCiphertext<Element> cipherText1, const LPEvalKeyNTRU<Element> linearKeySwitchHint, size_t levels = 1) const { if(this->m_algorithmLeveledSHE){ auto ct = this->m_algorithmLeveledSHE->LevelReduce(cipherText1,linearKeySwitchHint,levels); ct->SetKeyTag( cipherText1->GetKeyTag() ); return ct; } else{ throw std::logic_error("LevelReduce operation has not been enabled"); } } /* * This exposes CKKS's own ParamsGen through the LPPublicKeyEncryptionSchemeCKKS API. * See LPAlgorithmParamsGenCKKS::ParamsGen for a description of the arguments. * */ bool ParamsGen(shared_ptr<LPCryptoParameters<Element>> cryptoParams, usint cyclOrder, usint numPrimes, usint scaleExp, usint relinWindow, MODE mode, enum KeySwitchTechnique ksTech, usint firstModSize, RescalingTechnique rsTech, uint32_t numLargeDigits) const { if (this->m_algorithmParamsGen) { return m_algorithmParamsGen->ParamsGen(cryptoParams, cyclOrder, numPrimes, scaleExp, relinWindow, mode, ksTech, firstModSize, rsTech, numLargeDigits); } else { throw std::logic_error("Parameter generation operation has not been implemented for this scheme."); } } /* * Internal method performing level reduce (drop towers). * It's exposed here so methods in LPAlgorithmSHECKKS can access methods * from LPLeveledSHEAlgorithmCKKS (so that automatic rescaling can work * in EXACTRESCALE). * * @param cipherText1 input ciphertext * @param linearKeySwitchHint not used in the CKKS scheme. * @param levels the number of towers to drop from the input ciphertext * @return a ciphertext of the same plaintext value as that of the input, * but with fewer towers. * */ Ciphertext<Element> LevelReduceInternal(ConstCiphertext<Element> cipherText1, const LPEvalKey<Element> linearKeySwitchHint, size_t levels) const { if (this->m_algorithmLeveledSHE) { return m_algorithmLeveledSHE->LevelReduceInternal(cipherText1, linearKeySwitchHint, levels); } else { throw std::logic_error("LevelReduceInternal has not been enabled for this scheme."); } } /* * Internal method performing mod reduce (rescaling). * It's exposed here so methods in LPAlgorithmSHECKKS can access the method * from LPLeveledSHEAlgorithmCKKS (so that automatic rescaling can work * in EXACTRESCALE). * * @param cipherText1 input ciphertext * @return the rescaled ciphertext. * */ Ciphertext<Element> ModReduceInternal(ConstCiphertext<Element> cipherText) const { if (this->m_algorithmLeveledSHE) { return m_algorithmLeveledSHE->ModReduceInternal(cipherText); } else { throw std::logic_error("ModReduceInternal has not been enabled for this scheme."); } } Ciphertext<Element> AdjustLevelWithRescale(Ciphertext<Element> cipherText, uint32_t targetLevel) const { if (this->m_algorithmSHE) { return m_algorithmSHE->AdjustLevelWithRescale(cipherText, targetLevel); } else { throw std::logic_error("AdjustLevelWithRescale has not been enabled for this scheme."); } } const std::shared_ptr<LPEncryptionAlgorithm<Element>> getAlgorithm() const { return m_algorithmEncryption; } template <class Archive> void save( Archive & ar, std::uint32_t const version ) const { ar( ::cereal::make_nvp("enabled",GetEnabled()) ); } template <class Archive> void load( Archive & ar, std::uint32_t const version ) { if( version > SerializedVersion() ) { PALISADE_THROW(deserialize_error, "serialized object version " + std::to_string(version) + " is from a later version of the library"); } usint enabled; ar( ::cereal::make_nvp("enabled",enabled) ); this->Enable(enabled); } virtual std::string SerializedObjectName() const { return "Scheme"; } static uint32_t SerializedVersion() { return 1; } friend std::ostream& operator<<(std::ostream& out, const LPPublicKeyEncryptionScheme<Element>& s) { out << typeid(s).name() << ":" ; out << " ParameterGeneration " << (s.m_algorithmParamsGen == 0 ? "none" : typeid(*s.m_algorithmParamsGen).name()); out << ", Encryption " << (s.m_algorithmEncryption == 0 ? "none" : typeid(*s.m_algorithmEncryption).name()); out << ", PRE " << (s.m_algorithmPRE == 0 ? "none" : typeid(*s.m_algorithmPRE).name()); out << ", Multiparty " << (s.m_algorithmMultiparty == 0 ? "none" : typeid(*s.m_algorithmMultiparty).name()); out << ", SHE " << (s.m_algorithmSHE == 0 ? "none" : typeid(*s.m_algorithmSHE).name()); out << ", LeveledSHE " << (s.m_algorithmLeveledSHE == 0 ? "none" : typeid(*s.m_algorithmLeveledSHE).name()); return out; } protected: std::shared_ptr<LPParameterGenerationAlgorithm<Element>> m_algorithmParamsGen; std::shared_ptr<LPEncryptionAlgorithm<Element>> m_algorithmEncryption; std::shared_ptr<LPPREAlgorithm<Element>> m_algorithmPRE; std::shared_ptr<LPMultipartyAlgorithm<Element>> m_algorithmMultiparty; std::shared_ptr<LPSHEAlgorithm<Element>> m_algorithmSHE; std::shared_ptr<LPLeveledSHEAlgorithm<Element>> m_algorithmLeveledSHE; }; } // namespace lbcrypto ends #endif
ConcatenateCoefficient.h
// -------------------------------------------------------------------------- // Binary Brain -- binary neural net framework // // Copyright (C) 2018-2019 by Ryuji Fuchikami // https://github.com/ryuz // ryuji.fuchikami@nifty.com // -------------------------------------------------------------------------- #pragma once #include "bb/Manager.h" #include "bb/Model.h" namespace bb { // 定数を連結する template <typename FT = float, typename BT = float> class ConcatenateCoefficient : public Model { protected: bool m_host_only = false; bool m_binary_mode = true; indices_t m_input_shape; indices_t m_output_shape; indices_t m_coeff_shape; index_t m_concatenate_size; std::shared_ptr<Tensor> m_param; std::shared_ptr<Tensor> m_grad; FrameBuffer m_y_buf; FrameBuffer m_dx_buf; std::mt19937_64 m_mt; public: struct create_t { index_t concatenate_size = 0; std::uint64_t seed = 1; }; protected: ConcatenateCoefficient(create_t const &create) { m_concatenate_size = create.concatenate_size; m_mt.seed(create.seed); m_param = std::shared_ptr<Tensor>(new Tensor); m_grad = std::shared_ptr<Tensor>(new Tensor); } /** * @brief コマンド処理 * @detail コマンド処理 * @param args コマンド */ void CommandProc(std::vector<std::string> args) { // HostOnlyモード設定 if (args.size() == 2 && args[0] == "host_only") { m_host_only = EvalBool(args[1]); } } public: ~ConcatenateCoefficient() {} static std::shared_ptr<ConcatenateCoefficient> Create(create_t const &create) { return std::shared_ptr<ConcatenateCoefficient>(new ConcatenateCoefficient(create)); } static std::shared_ptr<ConcatenateCoefficient> Create(index_t concatenate_size, std::uint64_t seed = 1) { create_t create; create.concatenate_size = concatenate_size; create.seed = seed; return std::shared_ptr<ConcatenateCoefficient>(new ConcatenateCoefficient(create)); } std::string GetModelName(void) const { return "ConcatenateCoefficient"; } /** * @brief 入力のshape設定 * @detail 入力のshape設定 * @param shape 新しいshape * @return なし */ indices_t SetInputShape(indices_t shape) { // 設定済みなら何もしない if ( shape == this->GetInputShape() ) { return this->GetOutputShape(); } BB_ASSERT(shape.size() > 0); // 形状設定 m_input_shape = shape; // 最後の次元にサイズを積み増しして出力形状設定 m_output_shape = m_input_shape; m_output_shape[m_output_shape.size() - 1] += m_concatenate_size; m_coeff_shape = m_input_shape; m_coeff_shape[m_output_shape.size() - 1] = m_concatenate_size; // パラメータ初期化 m_param->Resize(DataType<BT>::type, m_coeff_shape); *m_param = 0.5; m_grad->Resize(DataType<BT>::type, m_coeff_shape); *m_grad = 0; return m_output_shape; } /** * @brief 入力形状取得 * @detail 入力形状を取得する * @return 入力形状を返す */ indices_t GetInputShape(void) const { return m_input_shape; } /** * @brief 出力形状取得 * @detail 出力形状を取得する * @return 出力形状を返す */ indices_t GetOutputShape(void) const { return m_output_shape; } Variables GetParameters(void) { Variables parameters; parameters.PushBack(m_param); return parameters; } Variables GetGradients(void) { Variables gradients; gradients.PushBack(m_grad); return gradients; } void SetParameter(index_t index, BT coeff) { auto param_ptr = m_param->Lock<BT>(); param_ptr[index] = coeff; } void GetParameter(index_t index) const { auto param_ptr = m_param->LockConst<BT>(); return param_ptr[index]; } /** * @brief forward演算 * @detail forward演算を行う * @param x 入力データ * @param train 学習時にtrueを指定 * @return forward演算結果 */ inline FrameBuffer Forward(FrameBuffer x_buf, bool train = true) { BB_ASSERT(x_buf.GetType() == DataType<FT>::type); // パラメータクリップ if ( m_binary_mode ) { m_param->Clamp(0.0, 1.0); } // 戻り値のサイズ設定 m_y_buf.Resize(x_buf.GetType(), x_buf.GetFrameSize(), m_output_shape); #if 0 // #ifdef BB_WITH_CUDA if ( DataType<FT>::type == BB_TYPE_FP32 && !m_host_only && m_x_buf.IsDeviceAvailable() && m_y_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable() ) { // CUDA版 auto ptr_x = x_buf.LockDeviceMemoryConst(); auto ptr_y = m_y_buf.LockDeviceMemory(true); bbcu_fp32_ConcatenateConstant_Forward( (float const *)ptr_x.GetAddr(), (float *)ptr_y.GetAddr(), (int )m_x_buf.GetNodeSize(), (int )m_x_buf.GetFrameSize(), (int )(m_x_buf.GetFrameStride() / sizeof(float)) ); return m_y_buf; } #endif { // 汎用版 index_t input_node_size = x_buf.GetNodeSize(); index_t output_node_size = m_y_buf.GetNodeSize(); index_t frame_size = m_y_buf.GetFrameSize(); auto x_ptr = x_buf.LockConst<FT>(); auto y_ptr = m_y_buf.Lock<FT>(); auto param_ptr = m_param->Lock<BT>(); #pragma omp parallel for for (index_t node = 0; node < input_node_size; ++node) { for (index_t frame = 0; frame < frame_size; ++frame) { auto x = x_ptr.Get(frame, node); y_ptr.Set(frame, node, x); } } index_t coeff_size = output_node_size - input_node_size; if ( DataType<FT>::type == BB_TYPE_BIT ) { std::uniform_real_distribution<BT> dist((BT)0, (BT)1); for (index_t i = 0; i < coeff_size; ++i) { auto coeff = param_ptr[i]; for (index_t frame = 0; frame < frame_size; ++frame) { y_ptr.Set(frame, input_node_size + i, dist(m_mt) < coeff); } } } else { #pragma omp parallel for for (index_t i = 0; i < coeff_size; ++i) { auto coeff = param_ptr[i]; for (index_t frame = 0; frame < frame_size; ++frame) { y_ptr.Set(frame, input_node_size + i, (FT)coeff); } } } return m_y_buf; } } /** * @brief backward演算 * @detail backward演算を行う * * @return backward演算結果 */ inline FrameBuffer Backward(FrameBuffer dy_buf) { if (dy_buf.Empty()) { return dy_buf; } BB_ASSERT(dy_buf.GetType() == DataType<BT>::type); // 戻り値のサイズ設定 m_dx_buf.Resize(DataType<BT>::type, dy_buf.GetFrameSize(), m_input_shape); #if 0 // #ifdef BB_WITH_CUDA if ( DataType<T>::type == BB_TYPE_FP32 && !m_host_only && m_x_buf.IsDeviceAvailable() && m_dx_buf.IsDeviceAvailable() && dy_buf.IsDeviceAvailable() && Manager::IsDeviceAvailable() ) { // GPU版 auto ptr_x = m_x_buf.LockDeviceMemoryConst(); auto ptr_dy = dy_buf.LockDeviceMemoryConst(); auto ptr_dx = m_dx_buf.LockDeviceMemory(true); bbcu_fp32_ReLU_Backward( (float const *)ptr_x.GetAddr(), (float const *)ptr_dy.GetAddr(), (float *)ptr_dx.GetAddr(), (int )dy_buf.GetNodeSize(), (int )dy_buf.GetFrameSize(), (int )(dy_buf.GetFrameStride() / sizeof(float)) ); return m_dx_buf; } #endif { //汎用版 index_t input_node_size = m_dx_buf.GetNodeSize(); index_t output_node_size = dy_buf.GetNodeSize(); index_t frame_size = dy_buf.GetFrameSize(); auto dy_ptr = dy_buf.LockConst<BT>(); auto dx_ptr = m_dx_buf.Lock<BT>(); auto grad_ptr = m_grad->Lock<BT>(); #pragma omp parallel for for (index_t node = 0; node < input_node_size; ++node) { for (index_t frame = 0; frame < frame_size; ++frame) { auto dy = dy_ptr.Get(frame, node); dx_ptr.Set(frame, node, dy); } } index_t coeff_size = output_node_size - input_node_size; #pragma omp parallel for for (index_t i = 0; i < coeff_size; ++i) { BT dy = 0; for (index_t frame = 0; frame < frame_size; ++frame) { dy += dy_ptr.Get(frame, input_node_size + i); } grad_ptr[i] += dy / (BT)frame_size; } return m_dx_buf; } } }; } // end of file
GB_unaryop__minv_fp64_int32.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_fp64_int32 // op(A') function: GB_tran__minv_fp64_int32 // C type: double // A type: int32_t // cast: double cij = (double) aij // unaryop: cij = 1./aij #define GB_ATYPE \ int32_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = 1./x ; // casting #define GB_CASTING(z, aij) \ double z = (double) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_FP64 || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_fp64_int32 ( double *Cx, // Cx and Ax may be aliased int32_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_fp64_int32 ( 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
quantize.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE % % Q Q U U A A NN N T I ZZ E % % Q Q U U AAAAA N N N T I ZZZ EEEEE % % Q QQ U U A A N NN T I ZZ E % % QQQQ UUU A A N N T IIIII ZZZZZ EEEEE % % % % % % MagickCore Methods to Reduce the Number of Unique Colors in an Image % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Realism in computer graphics typically requires using 24 bits/pixel to % generate an image. Yet many graphic display devices do not contain the % amount of memory necessary to match the spatial and color resolution of % the human eye. The Quantize methods takes a 24 bit image and reduces % the number of colors so it can be displayed on raster device with less % bits per pixel. In most instances, the quantized image closely % resembles the original reference image. % % A reduction of colors in an image is also desirable for image % transmission and real-time animation. % % QuantizeImage() takes a standard RGB or monochrome images and quantizes % them down to some fixed number of colors. % % For purposes of color allocation, an image is a set of n pixels, where % each pixel is a point in RGB space. RGB space is a 3-dimensional % vector space, and each pixel, Pi, is defined by an ordered triple of % red, green, and blue coordinates, (Ri, Gi, Bi). % % Each primary color component (red, green, or blue) represents an % intensity which varies linearly from 0 to a maximum value, Cmax, which % corresponds to full saturation of that color. Color allocation is % defined over a domain consisting of the cube in RGB space with opposite % vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax = % 255. % % The algorithm maps this domain onto a tree in which each node % represents a cube within that domain. In the following discussion % these cubes are defined by the coordinate of two opposite vertices (vertex % nearest the origin in RGB space and the vertex farthest from the origin). % % The tree's root node represents the entire domain, (0,0,0) through % (Cmax,Cmax,Cmax). Each lower level in the tree is generated by % subdividing one node's cube into eight smaller cubes of equal size. % This corresponds to bisecting the parent cube with planes passing % through the midpoints of each edge. % % The basic algorithm operates in three phases: Classification, % Reduction, and Assignment. Classification builds a color description % tree for the image. Reduction collapses the tree until the number it % represents, at most, the number of colors desired in the output image. % Assignment defines the output image's color map and sets each pixel's % color by restorage_class in the reduced tree. Our goal is to minimize % the numerical discrepancies between the original colors and quantized % colors (quantization error). % % Classification begins by initializing a color description tree of % sufficient depth to represent each possible input color in a leaf. % However, it is impractical to generate a fully-formed color description % tree in the storage_class phase for realistic values of Cmax. If % colors components in the input image are quantized to k-bit precision, % so that Cmax= 2k-1, the tree would need k levels below the root node to % allow representing each possible input color in a leaf. This becomes % prohibitive because the tree's total number of nodes is 1 + % sum(i=1, k, 8k). % % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255. % Therefore, to avoid building a fully populated tree, QUANTIZE: (1) % Initializes data structures for nodes only as they are needed; (2) % Chooses a maximum depth for the tree as a function of the desired % number of colors in the output image (currently log2(colormap size)). % % For each pixel in the input image, storage_class scans downward from % the root of the color description tree. At each level of the tree it % identifies the single node which represents a cube in RGB space % containing the pixel's color. It updates the following data for each % such node: % % n1: Number of pixels whose color is contained in the RGB cube which % this node represents; % % n2: Number of pixels whose color is not represented in a node at % lower depth in the tree; initially, n2 = 0 for all nodes except % leaves of the tree. % % Sr, Sg, Sb: Sums of the red, green, and blue component values for all % pixels not classified at a lower depth. The combination of these sums % and n2 will ultimately characterize the mean color of a set of pixels % represented by this node. % % E: the distance squared in RGB space between each pixel contained % within a node and the nodes' center. This represents the % quantization error for a node. % % Reduction repeatedly prunes the tree until the number of nodes with n2 % > 0 is less than or equal to the maximum number of colors allowed in % the output image. On any given iteration over the tree, it selects % those nodes whose E count is minimal for pruning and merges their color % statistics upward. It uses a pruning threshold, Ep, to govern node % selection as follows: % % Ep = 0 % while number of nodes with (n2 > 0) > required maximum number of colors % prune all nodes such that E <= Ep % Set Ep to minimum E in remaining nodes % % This has the effect of minimizing any quantization error when merging % two nodes together. % % When a node to be pruned has offspring, the pruning procedure invokes % itself recursively in order to prune the tree from the leaves upward. % n2, Sr, Sg, and Sb in a node being pruned are always added to the % corresponding data in that node's parent. This retains the pruned % node's color characteristics for later averaging. % % For each node, n2 pixels exist for which that node represents the % smallest volume in RGB space containing those pixel's colors. When n2 % > 0 the node will uniquely define a color in the output image. At the % beginning of reduction, n2 = 0 for all nodes except a the leaves of % the tree which represent colors present in the input image. % % The other pixel count, n1, indicates the total number of colors within % the cubic volume which the node represents. This includes n1 - n2 % pixels whose colors should be defined by nodes at a lower level in the % tree. % % Assignment generates the output image from the pruned tree. The output % image consists of two parts: (1) A color map, which is an array of % color descriptions (RGB triples) for each color present in the output % image; (2) A pixel array, which represents each pixel as an index % into the color map array. % % First, the assignment phase makes one pass over the pruned color % description tree to establish the image's color map. For each node % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean % color of all pixels that classify no lower than this node. Each of % these colors becomes an entry in the color map. % % Finally, the assignment phase reclassifies each pixel in the pruned % tree to identify the deepest node containing the pixel's color. The % pixel's value in the pixel array becomes the index of this node's mean % color in the color map. % % This method is based on a similar algorithm written by Paul Raveling. % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/histogram.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/resource_.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" /* Define declarations. */ #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE) #define CacheShift 2 #else #define CacheShift 3 #endif #define ErrorQueueLength 16 #define MaxNodes 266817 #define MaxTreeDepth 8 #define NodesInAList 1920 /* Typdef declarations. */ typedef struct _NodeInfo { struct _NodeInfo *parent, *child[16]; MagickSizeType number_unique; DoublePixelPacket total_color; MagickRealType quantize_error; size_t color_number, id, level; } NodeInfo; typedef struct _Nodes { NodeInfo *nodes; struct _Nodes *next; } Nodes; typedef struct _CubeInfo { NodeInfo *root; size_t colors, maximum_colors; ssize_t transparent_index; MagickSizeType transparent_pixels; DoublePixelPacket target; MagickRealType distance, pruning_threshold, next_threshold; size_t nodes, free_nodes, color_number; NodeInfo *next_node; Nodes *node_queue; MemoryInfo *memory_info; ssize_t *cache; DoublePixelPacket error[ErrorQueueLength]; MagickRealType weights[ErrorQueueLength]; QuantizeInfo *quantize_info; MagickBooleanType associate_alpha; ssize_t x, y; size_t depth; MagickOffsetType offset; MagickSizeType span; } CubeInfo; /* Method prototypes. */ static CubeInfo *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t); static NodeInfo *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *); static MagickBooleanType AssignImageColors(Image *,CubeInfo *), ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *), DitherImage(Image *,CubeInfo *), SetGrayscaleImage(Image *); static size_t DefineImageColormap(Image *,CubeInfo *,NodeInfo *); static void ClosestColor(const Image *,CubeInfo *,const NodeInfo *), DestroyCubeInfo(CubeInfo *), PruneLevel(CubeInfo *,const NodeInfo *), PruneToCubeDepth(CubeInfo *,const NodeInfo *), ReduceImageColors(const Image *,CubeInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantizeInfo() allocates the QuantizeInfo structure. % % The format of the AcquireQuantizeInfo method is: % % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info) { QuantizeInfo *quantize_info; quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info)); if (quantize_info == (QuantizeInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); GetQuantizeInfo(quantize_info); if (image_info != (ImageInfo *) NULL) { const char *option; quantize_info->dither=image_info->dither; option=GetImageOption(image_info,"dither"); if (option != (const char *) NULL) quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,option); quantize_info->measure_error=image_info->verbose; } return(quantize_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A s s i g n I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AssignImageColors() generates the output image from the pruned tree. The % output image consists of two parts: (1) A color map, which is an array % of color descriptions (RGB triples) for each color present in the % output image; (2) A pixel array, which represents each pixel as an % index into the color map array. % % First, the assignment phase makes one pass over the pruned color % description tree to establish the image's color map. For each node % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean % color of all pixels that classify no lower than this node. Each of % these colors becomes an entry in the color map. % % Finally, the assignment phase reclassifies each pixel in the pruned % tree to identify the deepest node containing the pixel's color. The % pixel's value in the pixel array becomes the index of this node's mean % color in the color map. % % The format of the AssignImageColors() method is: % % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static inline void AssociateAlphaPixel(const CubeInfo *cube_info, const PixelPacket *pixel,DoublePixelPacket *alpha_pixel) { MagickRealType alpha; alpha_pixel->index=0; if ((cube_info->associate_alpha == MagickFalse) || (pixel->opacity == OpaqueOpacity)) { alpha_pixel->red=(MagickRealType) GetPixelRed(pixel); alpha_pixel->green=(MagickRealType) GetPixelGreen(pixel); alpha_pixel->blue=(MagickRealType) GetPixelBlue(pixel); alpha_pixel->opacity=(MagickRealType) GetPixelOpacity(pixel); return; } alpha=(MagickRealType) (QuantumScale*(QuantumRange-GetPixelOpacity(pixel))); alpha_pixel->red=alpha*GetPixelRed(pixel); alpha_pixel->green=alpha*GetPixelGreen(pixel); alpha_pixel->blue=alpha*GetPixelBlue(pixel); alpha_pixel->opacity=(MagickRealType) GetPixelOpacity(pixel); } static inline size_t ColorToNodeId(const CubeInfo *cube_info, const DoublePixelPacket *pixel,size_t index) { size_t id; id=(size_t) (((ScaleQuantumToChar(ClampPixel(GetPixelRed(pixel))) >> index) & 0x01) | ((ScaleQuantumToChar(ClampPixel(GetPixelGreen(pixel))) >> index) & 0x01) << 1 | ((ScaleQuantumToChar(ClampPixel(GetPixelBlue(pixel))) >> index) & 0x01) << 2); if (cube_info->associate_alpha != MagickFalse) id|=((ScaleQuantumToChar(ClampPixel(GetPixelOpacity(pixel))) >> index) & 0x1) << 3; return(id); } static inline MagickBooleanType IsSameColor(const Image *image, const PixelPacket *p,const PixelPacket *q) { if ((GetPixelRed(p) != GetPixelRed(q)) || (GetPixelGreen(p) != GetPixelGreen(q)) || (GetPixelBlue(p) != GetPixelBlue(q))) return(MagickFalse); if ((image->matte != MagickFalse) && (GetPixelOpacity(p) != GetPixelOpacity(q))) return(MagickFalse); return(MagickTrue); } static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info) { #define AssignImageTag "Assign/Image" ColorspaceType colorspace; ssize_t y; /* Allocate image colormap. */ colorspace=image->colorspace; if (cube_info->quantize_info->colorspace != UndefinedColorspace) (void) TransformImageColorspace(image,cube_info->quantize_info->colorspace); if (AcquireImageColormap(image,cube_info->colors) == MagickFalse) ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed", image->filename); image->colors=0; cube_info->transparent_pixels=0; cube_info->transparent_index=(-1); (void) DefineImageColormap(image,cube_info,cube_info->root); /* Create a reduced color image. */ if ((cube_info->quantize_info->dither != MagickFalse) && (cube_info->quantize_info->dither_method != NoDitherMethod)) (void) DitherImage(image,cube_info); else { CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CubeInfo cube; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; ssize_t count; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); cube=(*cube_info); for (x=0; x < (ssize_t) image->columns; x+=count) { DoublePixelPacket pixel; register const NodeInfo *node_info; register ssize_t i; size_t id, index; /* Identify the deepest node containing the pixel's color. */ for (count=1; (x+count) < (ssize_t) image->columns; count++) if (IsSameColor(image,q,q+count) == MagickFalse) break; AssociateAlphaPixel(&cube,q,&pixel); node_info=cube.root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(&cube,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ cube.target=pixel; cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)* (QuantumRange+1.0)+1.0); ClosestColor(image,&cube,node_info->parent); index=cube.color_number; for (i=0; i < (ssize_t) count; i++) { if (image->storage_class == PseudoClass) SetPixelIndex(indexes+x+i,index); if (cube.quantize_info->measure_error == MagickFalse) { SetPixelRgb(q,image->colormap+index); if (cube.associate_alpha != MagickFalse) SetPixelOpacity(q,image->colormap[index].opacity); } q++; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); } if (cube_info->quantize_info->measure_error != MagickFalse) (void) GetImageQuantizeError(image); if ((cube_info->quantize_info->number_colors == 2) && ((cube_info->quantize_info->colorspace == LinearGRAYColorspace) || (cube_info->quantize_info->colorspace == GRAYColorspace))) { double intensity; /* Monochrome image. */ intensity=0.0; if ((image->colors > 1) && (GetPixelLuma(image,image->colormap+0) > GetPixelLuma(image,image->colormap+1))) intensity=(double) QuantumRange; image->colormap[0].red=intensity; image->colormap[0].green=intensity; image->colormap[0].blue=intensity; if (image->colors > 1) { image->colormap[1].red=(double) QuantumRange-intensity; image->colormap[1].green=(double) QuantumRange-intensity; image->colormap[1].blue=(double) QuantumRange-intensity; } } (void) SyncImage(image); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (IssRGBCompatibleColorspace(colorspace) == MagickFalse)) (void) TransformImageColorspace(image,colorspace); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l a s s i f y I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClassifyImageColors() begins by initializing a color description tree % of sufficient depth to represent each possible input color in a leaf. % However, it is impractical to generate a fully-formed color % description tree in the storage_class phase for realistic values of % Cmax. If colors components in the input image are quantized to k-bit % precision, so that Cmax= 2k-1, the tree would need k levels below the % root node to allow representing each possible input color in a leaf. % This becomes prohibitive because the tree's total number of nodes is % 1 + sum(i=1,k,8k). % % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255. % Therefore, to avoid building a fully populated tree, QUANTIZE: (1) % Initializes data structures for nodes only as they are needed; (2) % Chooses a maximum depth for the tree as a function of the desired % number of colors in the output image (currently log2(colormap size)). % % For each pixel in the input image, storage_class scans downward from % the root of the color description tree. At each level of the tree it % identifies the single node which represents a cube in RGB space % containing It updates the following data for each such node: % % n1 : Number of pixels whose color is contained in the RGB cube % which this node represents; % % n2 : Number of pixels whose color is not represented in a node at % lower depth in the tree; initially, n2 = 0 for all nodes except % leaves of the tree. % % Sr, Sg, Sb : Sums of the red, green, and blue component values for % all pixels not classified at a lower depth. The combination of % these sums and n2 will ultimately characterize the mean color of a % set of pixels represented by this node. % % E: the distance squared in RGB space between each pixel contained % within a node and the nodes' center. This represents the quantization % error for a node. % % The format of the ClassifyImageColors() method is: % % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info, % const Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o image: the image. % */ static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info) { MagickBooleanType associate_alpha; associate_alpha=image->matte; if ((cube_info->quantize_info->number_colors == 2) && ((cube_info->quantize_info->colorspace == LinearGRAYColorspace) || (cube_info->quantize_info->colorspace == GRAYColorspace))) associate_alpha=MagickFalse; cube_info->associate_alpha=associate_alpha; } static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info, const Image *image,ExceptionInfo *exception) { #define ClassifyImageTag "Classify/Image" CacheView *image_view; DoublePixelPacket error, mid, midpoint, pixel; MagickBooleanType proceed; MagickRealType bisect; NodeInfo *node_info; size_t count, id, index, level; ssize_t y; /* Classify the first cube_info->maximum_colors colors to a tree depth of 8. */ SetAssociatedAlpha(image,cube_info); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace((Image *) image, cube_info->quantize_info->colorspace); else if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace((Image *) image,sRGBColorspace); midpoint.red=(MagickRealType) QuantumRange/2.0; midpoint.green=(MagickRealType) QuantumRange/2.0; midpoint.blue=(MagickRealType) QuantumRange/2.0; midpoint.opacity=(MagickRealType) QuantumRange/2.0; midpoint.index=(MagickRealType) QuantumRange/2.0; error.opacity=0.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; if (cube_info->nodes > MaxNodes) { /* Prune one level if the color tree is too large. */ PruneLevel(cube_info,cube_info->root); cube_info->depth--; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count) { /* Start at the root and descend the color cube tree. */ for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++) if (IsSameColor(image,p,p+count) == MagickFalse) break; AssociateAlphaPixel(cube_info,p,&pixel); index=MaxTreeDepth-1; bisect=((MagickRealType) QuantumRange+1.0)/2.0; mid=midpoint; node_info=cube_info->root; for (level=1; level <= MaxTreeDepth; level++) { double distance; bisect*=0.5; id=ColorToNodeId(cube_info,&pixel,index); mid.red+=(id & 1) != 0 ? bisect : -bisect; mid.green+=(id & 2) != 0 ? bisect : -bisect; mid.blue+=(id & 4) != 0 ? bisect : -bisect; mid.opacity+=(id & 8) != 0 ? bisect : -bisect; if (node_info->child[id] == (NodeInfo *) NULL) { /* Set colors of new node to contain pixel. */ node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info); if (node_info->child[id] == (NodeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); continue; } if (level == MaxTreeDepth) cube_info->colors++; } /* Approximate the quantization error represented by this node. */ node_info=node_info->child[id]; error.red=QuantumScale*(pixel.red-mid.red); error.green=QuantumScale*(pixel.green-mid.green); error.blue=QuantumScale*(pixel.blue-mid.blue); if (cube_info->associate_alpha != MagickFalse) error.opacity=QuantumScale*(pixel.opacity-mid.opacity); distance=(double) (error.red*error.red+error.green*error.green+ error.blue*error.blue+error.opacity*error.opacity); if (IsNaN(distance) != MagickFalse) distance=0.0; node_info->quantize_error+=count*sqrt(distance); cube_info->root->quantize_error+=node_info->quantize_error; index--; } /* Sum RGB for this leaf for later derivation of the mean cube color. */ node_info->number_unique+=count; node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red); node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green); node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) node_info->total_color.opacity+=count*QuantumScale* ClampPixel(pixel.opacity); else node_info->total_color.opacity+=count*QuantumScale* ClampPixel(OpaqueOpacity); p+=count; } if (cube_info->colors > cube_info->maximum_colors) { PruneToCubeDepth(cube_info,cube_info->root); break; } proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } for (y++; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; if (cube_info->nodes > MaxNodes) { /* Prune one level if the color tree is too large. */ PruneLevel(cube_info,cube_info->root); cube_info->depth--; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count) { /* Start at the root and descend the color cube tree. */ for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++) if (IsSameColor(image,p,p+count) == MagickFalse) break; AssociateAlphaPixel(cube_info,p,&pixel); index=MaxTreeDepth-1; bisect=((MagickRealType) QuantumRange+1.0)/2.0; mid=midpoint; node_info=cube_info->root; for (level=1; level <= cube_info->depth; level++) { double distance; bisect*=0.5; id=ColorToNodeId(cube_info,&pixel,index); mid.red+=(id & 1) != 0 ? bisect : -bisect; mid.green+=(id & 2) != 0 ? bisect : -bisect; mid.blue+=(id & 4) != 0 ? bisect : -bisect; mid.opacity+=(id & 8) != 0 ? bisect : -bisect; if (node_info->child[id] == (NodeInfo *) NULL) { /* Set colors of new node to contain pixel. */ node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info); if (node_info->child[id] == (NodeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","%s", image->filename); continue; } if (level == cube_info->depth) cube_info->colors++; } /* Approximate the quantization error represented by this node. */ node_info=node_info->child[id]; error.red=QuantumScale*(pixel.red-mid.red); error.green=QuantumScale*(pixel.green-mid.green); error.blue=QuantumScale*(pixel.blue-mid.blue); if (cube_info->associate_alpha != MagickFalse) error.opacity=QuantumScale*(pixel.opacity-mid.opacity); distance=(double) (error.red*error.red+error.green*error.green+ error.blue*error.blue+error.opacity*error.opacity); if (IsNaN(distance)) distance=0.0; node_info->quantize_error+=count*sqrt(distance); cube_info->root->quantize_error+=node_info->quantize_error; index--; } /* Sum RGB for this leaf for later derivation of the mean cube color. */ node_info->number_unique+=count; node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red); node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green); node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) node_info->total_color.opacity+=count*QuantumScale*ClampPixel( pixel.opacity); else node_info->total_color.opacity+=count*QuantumScale* ClampPixel(OpaqueOpacity); p+=count; } proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } image_view=DestroyCacheView(image_view); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace((Image *) image,sRGBColorspace); return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneQuantizeInfo() makes a duplicate of the given quantize info structure, % or if quantize info is NULL, a new one. % % The format of the CloneQuantizeInfo method is: % % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given % quantize info, or if image info is NULL a new one. % % o quantize_info: a structure of type info. % */ MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info) { QuantizeInfo *clone_info; clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info)); if (clone_info == (QuantizeInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); GetQuantizeInfo(clone_info); if (quantize_info == (QuantizeInfo *) NULL) return(clone_info); clone_info->number_colors=quantize_info->number_colors; clone_info->tree_depth=quantize_info->tree_depth; clone_info->dither=quantize_info->dither; clone_info->dither_method=quantize_info->dither_method; clone_info->colorspace=quantize_info->colorspace; clone_info->measure_error=quantize_info->measure_error; return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o s e s t C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClosestColor() traverses the color cube tree at a particular node and % determines which colormap entry best represents the input color. % % The format of the ClosestColor method is: % % void ClosestColor(const Image *image,CubeInfo *cube_info, % const NodeInfo *node_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o node_info: the address of a structure of type NodeInfo which points to a % node in the color cube tree that is to be pruned. % */ static void ClosestColor(const Image *image,CubeInfo *cube_info, const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) ClosestColor(image,cube_info,node_info->child[i]); if (node_info->number_unique != 0) { MagickRealType pixel; register DoublePixelPacket *magick_restrict q; register MagickRealType alpha, beta, distance; register PixelPacket *magick_restrict p; /* Determine if this color is "closest". */ p=image->colormap+node_info->color_number; q=(&cube_info->target); alpha=1.0; beta=1.0; if (cube_info->associate_alpha != MagickFalse) { alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p)); beta=(MagickRealType) (QuantumScale*GetPixelAlpha(q)); } pixel=alpha*GetPixelRed(p)-beta*GetPixelRed(q); distance=pixel*pixel; if (distance <= cube_info->distance) { pixel=alpha*GetPixelGreen(p)-beta*GetPixelGreen(q); distance+=pixel*pixel; if (distance <= cube_info->distance) { pixel=alpha*GetPixelBlue(p)-beta*GetPixelBlue(q); distance+=pixel*pixel; if (distance <= cube_info->distance) { if (cube_info->associate_alpha != MagickFalse) { pixel=GetPixelAlpha(p)-GetPixelAlpha(q); distance+=pixel*pixel; } if (distance <= cube_info->distance) { cube_info->distance=distance; cube_info->color_number=node_info->color_number; } } } } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p r e s s I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompressImageColormap() compresses an image colormap by removing any % duplicate or unused color entries. % % The format of the CompressImageColormap method is: % % MagickBooleanType CompressImageColormap(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickBooleanType CompressImageColormap(Image *image) { QuantizeInfo quantize_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (IsPaletteImage(image,&image->exception) == MagickFalse) return(MagickFalse); GetQuantizeInfo(&quantize_info); quantize_info.number_colors=image->colors; quantize_info.tree_depth=MaxTreeDepth; return(QuantizeImage(&quantize_info,image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e f i n e I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DefineImageColormap() traverses the color cube tree and notes each colormap % entry. A colormap entry is any node in the color cube tree where the % of unique colors is not zero. DefineImageColormap() returns the number of % colors in the image colormap. % % The format of the DefineImageColormap method is: % % size_t DefineImageColormap(Image *image,CubeInfo *cube_info, % NodeInfo *node_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o node_info: the address of a structure of type NodeInfo which points to a % node in the color cube tree that is to be pruned. % */ static size_t DefineImageColormap(Image *image,CubeInfo *cube_info, NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) (void) DefineImageColormap(image,cube_info,node_info->child[i]); if (node_info->number_unique != 0) { register MagickRealType alpha; register PixelPacket *magick_restrict q; /* Colormap entry is defined by the mean color in this cube. */ q=image->colormap+image->colors; alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique); alpha=PerceptibleReciprocal(alpha); if (cube_info->associate_alpha == MagickFalse) { SetPixelRed(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.red))); SetPixelGreen(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.green))); SetPixelBlue(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.blue))); SetPixelOpacity(q,OpaqueOpacity); } else { MagickRealType opacity; opacity=(MagickRealType) (alpha*QuantumRange* node_info->total_color.opacity); SetPixelOpacity(q,ClampToQuantum(opacity)); if (q->opacity == OpaqueOpacity) { SetPixelRed(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.red))); SetPixelGreen(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.green))); SetPixelBlue(q,ClampToQuantum((MagickRealType) (alpha* QuantumRange*node_info->total_color.blue))); } else { double gamma; gamma=(double) (QuantumScale*(QuantumRange-(double) q->opacity)); gamma=PerceptibleReciprocal(gamma); SetPixelRed(q,ClampToQuantum((MagickRealType) (alpha* gamma*QuantumRange*node_info->total_color.red))); SetPixelGreen(q,ClampToQuantum((MagickRealType) (alpha* gamma*QuantumRange*node_info->total_color.green))); SetPixelBlue(q,ClampToQuantum((MagickRealType) (alpha* gamma*QuantumRange*node_info->total_color.blue))); if (node_info->number_unique > cube_info->transparent_pixels) { cube_info->transparent_pixels=node_info->number_unique; cube_info->transparent_index=(ssize_t) image->colors; } } } node_info->color_number=image->colors++; } return(image->colors); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y C u b e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyCubeInfo() deallocates memory associated with an image. % % The format of the DestroyCubeInfo method is: % % DestroyCubeInfo(CubeInfo *cube_info) % % A description of each parameter follows: % % o cube_info: the address of a structure of type CubeInfo. % */ static void DestroyCubeInfo(CubeInfo *cube_info) { register Nodes *nodes; /* Release color cube tree storage. */ do { nodes=cube_info->node_queue->next; cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory( cube_info->node_queue->nodes); cube_info->node_queue=(Nodes *) RelinquishMagickMemory( cube_info->node_queue); cube_info->node_queue=nodes; } while (cube_info->node_queue != (Nodes *) NULL); if (cube_info->memory_info != (MemoryInfo *) NULL) cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info); cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info); cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo % structure. % % The format of the DestroyQuantizeInfo method is: % % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % */ MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(quantize_info != (QuantizeInfo *) NULL); assert(quantize_info->signature == MagickCoreSignature); quantize_info->signature=(~MagickCoreSignature); quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info); return(quantize_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DitherImage() distributes the difference between an original image and % the corresponding color reduced algorithm to neighboring pixels using % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns % MagickTrue if the image is dithered otherwise MagickFalse. % % The format of the DitherImage method is: % % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static DoublePixelPacket **DestroyPixelThreadSet(DoublePixelPacket **pixels) { register ssize_t i; assert(pixels != (DoublePixelPacket **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (DoublePixelPacket *) NULL) pixels[i]=(DoublePixelPacket *) RelinquishMagickMemory(pixels[i]); pixels=(DoublePixelPacket **) RelinquishMagickMemory(pixels); return(pixels); } static DoublePixelPacket **AcquirePixelThreadSet(const size_t count) { DoublePixelPacket **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(DoublePixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (DoublePixelPacket **) NULL) return((DoublePixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(DoublePixelPacket *) AcquireQuantumMemory(count, 2*sizeof(**pixels)); if (pixels[i] == (DoublePixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); } return(pixels); } static inline ssize_t CacheOffset(CubeInfo *cube_info, const DoublePixelPacket *pixel) { #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift))) #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift))) #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift))) #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift))) ssize_t offset; offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) | GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) | BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue)))); if (cube_info->associate_alpha != MagickFalse) offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->opacity))); return(offset); } static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info) { #define DitherImageTag "Dither/Image" CacheView *image_view; const char *artifact; double amount; DoublePixelPacket **pixels; ExceptionInfo *exception; MagickBooleanType status; ssize_t y; /* Distribute quantization error using Floyd-Steinberg. */ pixels=AcquirePixelThreadSet(image->columns); if (pixels == (DoublePixelPacket **) NULL) return(MagickFalse); exception=(&image->exception); status=MagickTrue; amount=1.0; artifact=GetImageArtifact(image,"dither:diffusion-amount"); if (artifact != (const char *) NULL) amount=StringToDoubleInterval(artifact,1.0); image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); CubeInfo cube; DoublePixelPacket *current, *previous; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; size_t index; ssize_t v; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); cube=(*cube_info); current=pixels[id]+(y & 0x01)*image->columns; previous=pixels[id]+((y+1) & 0x01)*image->columns; v=(ssize_t) ((y & 0x01) ? -1 : 1); for (x=0; x < (ssize_t) image->columns; x++) { DoublePixelPacket color, pixel; register ssize_t i; ssize_t u; u=(y & 0x01) ? (ssize_t) image->columns-1-x : x; AssociateAlphaPixel(&cube,q+u,&pixel); if (x > 0) { pixel.red+=7.0*amount*current[u-v].red/16; pixel.green+=7.0*amount*current[u-v].green/16; pixel.blue+=7.0*amount*current[u-v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.opacity+=7.0*amount*current[u-v].opacity/16; } if (y > 0) { if (x < (ssize_t) (image->columns-1)) { pixel.red+=previous[u+v].red/16; pixel.green+=previous[u+v].green/16; pixel.blue+=previous[u+v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.opacity+=previous[u+v].opacity/16; } pixel.red+=5.0*amount*previous[u].red/16; pixel.green+=5.0*amount*previous[u].green/16; pixel.blue+=5.0*amount*previous[u].blue/16; if (cube.associate_alpha != MagickFalse) pixel.opacity+=5.0*amount*previous[u].opacity/16; if (x > 0) { pixel.red+=3.0*amount*previous[u-v].red/16; pixel.green+=3.0*amount*previous[u-v].green/16; pixel.blue+=3.0*amount*previous[u-v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.opacity+=3.0*amount*previous[u-v].opacity/16; } } pixel.red=(MagickRealType) ClampPixel(pixel.red); pixel.green=(MagickRealType) ClampPixel(pixel.green); pixel.blue=(MagickRealType) ClampPixel(pixel.blue); if (cube.associate_alpha != MagickFalse) pixel.opacity=(MagickRealType) ClampPixel(pixel.opacity); i=CacheOffset(&cube,&pixel); if (cube.cache[i] < 0) { register NodeInfo *node_info; register size_t id; /* Identify the deepest node containing the pixel's color. */ node_info=cube.root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(&cube,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ cube.target=pixel; cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+ 1.0)+1.0); ClosestColor(image,&cube,node_info->parent); cube.cache[i]=(ssize_t) cube.color_number; } /* Assign pixel to closest colormap entry. */ index=(size_t) cube.cache[i]; if (image->storage_class == PseudoClass) SetPixelIndex(indexes+u,index); if (cube.quantize_info->measure_error == MagickFalse) { SetPixelRgb(q+u,image->colormap+index); if (cube.associate_alpha != MagickFalse) SetPixelOpacity(q+u,image->colormap[index].opacity); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; /* Store the error. */ AssociateAlphaPixel(&cube,image->colormap+index,&color); current[u].red=pixel.red-color.red; current[u].green=pixel.green-color.green; current[u].blue=pixel.blue-color.blue; if (cube.associate_alpha != MagickFalse) current[u].opacity=pixel.opacity-color.opacity; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } image_view=DestroyCacheView(image_view); pixels=DestroyPixelThreadSet(pixels); return(MagickTrue); } static MagickBooleanType RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int); static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info, const size_t level,const unsigned int direction) { if (level == 1) switch (direction) { case WestGravity: { (void) RiemersmaDither(image,image_view,cube_info,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); break; } case EastGravity: { (void) RiemersmaDither(image,image_view,cube_info,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); break; } case NorthGravity: { (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); break; } case SouthGravity: { (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); break; } default: break; } else switch (direction) { case WestGravity: { Riemersma(image,image_view,cube_info,level-1,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); Riemersma(image,image_view,cube_info,level-1,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); Riemersma(image,image_view,cube_info,level-1,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); Riemersma(image,image_view,cube_info,level-1,SouthGravity); break; } case EastGravity: { Riemersma(image,image_view,cube_info,level-1,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); Riemersma(image,image_view,cube_info,level-1,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); Riemersma(image,image_view,cube_info,level-1,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); Riemersma(image,image_view,cube_info,level-1,NorthGravity); break; } case NorthGravity: { Riemersma(image,image_view,cube_info,level-1,WestGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); Riemersma(image,image_view,cube_info,level-1,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,EastGravity); Riemersma(image,image_view,cube_info,level-1,NorthGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); Riemersma(image,image_view,cube_info,level-1,EastGravity); break; } case SouthGravity: { Riemersma(image,image_view,cube_info,level-1,EastGravity); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity); Riemersma(image,image_view,cube_info,level-1,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,WestGravity); Riemersma(image,image_view,cube_info,level-1,SouthGravity); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity); Riemersma(image,image_view,cube_info,level-1,WestGravity); break; } default: break; } } static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view, CubeInfo *cube_info,const unsigned int direction) { #define DitherImageTag "Dither/Image" DoublePixelPacket color, pixel; MagickBooleanType proceed; register CubeInfo *p; size_t index; p=cube_info; if ((p->x >= 0) && (p->x < (ssize_t) image->columns) && (p->y >= 0) && (p->y < (ssize_t) image->rows)) { ExceptionInfo *exception; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t i; /* Distribute error. */ exception=(&image->exception); q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickFalse); indexes=GetCacheViewAuthenticIndexQueue(image_view); AssociateAlphaPixel(cube_info,q,&pixel); for (i=0; i < ErrorQueueLength; i++) { pixel.red+=p->weights[i]*p->error[i].red; pixel.green+=p->weights[i]*p->error[i].green; pixel.blue+=p->weights[i]*p->error[i].blue; if (cube_info->associate_alpha != MagickFalse) pixel.opacity+=p->weights[i]*p->error[i].opacity; } pixel.red=(MagickRealType) ClampPixel(pixel.red); pixel.green=(MagickRealType) ClampPixel(pixel.green); pixel.blue=(MagickRealType) ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) pixel.opacity=(MagickRealType) ClampPixel(pixel.opacity); i=CacheOffset(cube_info,&pixel); if (p->cache[i] < 0) { register NodeInfo *node_info; register size_t id; /* Identify the deepest node containing the pixel's color. */ node_info=p->root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(cube_info,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ p->target=pixel; p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType) QuantumRange+1.0)+1.0); ClosestColor(image,p,node_info->parent); p->cache[i]=(ssize_t) p->color_number; } /* Assign pixel to closest colormap entry. */ index=(size_t) (1*p->cache[i]); if (image->storage_class == PseudoClass) *indexes=(IndexPacket) index; if (cube_info->quantize_info->measure_error == MagickFalse) { SetPixelRgb(q,image->colormap+index); if (cube_info->associate_alpha != MagickFalse) SetPixelOpacity(q,image->colormap[index].opacity); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) return(MagickFalse); /* Propagate the error as the last entry of the error queue. */ (void) memmove(p->error,p->error+1,(ErrorQueueLength-1)* sizeof(p->error[0])); AssociateAlphaPixel(cube_info,image->colormap+index,&color); p->error[ErrorQueueLength-1].red=pixel.red-color.red; p->error[ErrorQueueLength-1].green=pixel.green-color.green; p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue; if (cube_info->associate_alpha != MagickFalse) p->error[ErrorQueueLength-1].opacity=pixel.opacity-color.opacity; proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span); if (proceed == MagickFalse) return(MagickFalse); p->offset++; } switch (direction) { case WestGravity: p->x--; break; case EastGravity: p->x++; break; case NorthGravity: p->y--; break; case SouthGravity: p->y++; break; } return(MagickTrue); } static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info) { CacheView *image_view; MagickBooleanType status; register ssize_t i; size_t depth; if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod) return(FloydSteinbergDither(image,cube_info)); /* Distribute quantization error along a Hilbert curve. */ (void) memset(cube_info->error,0,ErrorQueueLength* sizeof(*cube_info->error)); cube_info->x=0; cube_info->y=0; i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows); for (depth=1; i != 0; depth++) i>>=1; if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows)) depth++; cube_info->offset=0; cube_info->span=(MagickSizeType) image->columns*image->rows; image_view=AcquireAuthenticCacheView(image,&image->exception); if (depth > 1) Riemersma(image,image_view,cube_info,depth-1,NorthGravity); status=RiemersmaDither(image,image_view,cube_info,ForgetGravity); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t C u b e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetCubeInfo() initialize the Cube data structure. % % The format of the GetCubeInfo method is: % % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info, % const size_t depth,const size_t maximum_colors) % % A description of each parameter follows. % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o depth: Normally, this integer value is zero or one. A zero or % one tells Quantize to choose a optimal tree depth of Log4(number_colors). % A tree of this depth generally allows the best representation of the % reference image with the least amount of memory and the fastest % computational speed. In some cases, such as an image with low color % dispersion (a few number of colors), a value other than % Log4(number_colors) is required. To expand the color tree completely, % use a value of 8. % % o maximum_colors: maximum colors. % */ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info, const size_t depth,const size_t maximum_colors) { CubeInfo *cube_info; MagickRealType sum, weight; register ssize_t i; size_t length; /* Initialize tree to describe color cube_info. */ cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info)); if (cube_info == (CubeInfo *) NULL) return((CubeInfo *) NULL); (void) memset(cube_info,0,sizeof(*cube_info)); cube_info->depth=depth; if (cube_info->depth > MaxTreeDepth) cube_info->depth=MaxTreeDepth; if (cube_info->depth < 2) cube_info->depth=2; cube_info->maximum_colors=maximum_colors; /* Initialize root node. */ cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL); if (cube_info->root == (NodeInfo *) NULL) return((CubeInfo *) NULL); cube_info->root->parent=cube_info->root; cube_info->quantize_info=CloneQuantizeInfo(quantize_info); if (cube_info->quantize_info->dither == MagickFalse) return(cube_info); /* Initialize dither resources. */ length=(size_t) (1UL << (4*(8-CacheShift))); cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache)); if (cube_info->memory_info == (MemoryInfo *) NULL) return((CubeInfo *) NULL); cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info); /* Initialize color cache. */ (void) memset(cube_info->cache,(-1),sizeof(*cube_info->cache)* length); /* Distribute weights along a curve of exponential decay. */ weight=1.0; for (i=0; i < ErrorQueueLength; i++) { cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight); weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0)); } /* Normalize the weighting factors. */ weight=0.0; for (i=0; i < ErrorQueueLength; i++) weight+=cube_info->weights[i]; sum=0.0; for (i=0; i < ErrorQueueLength; i++) { cube_info->weights[i]/=weight; sum+=cube_info->weights[i]; } cube_info->weights[0]+=1.0-sum; return(cube_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t N o d e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNodeInfo() allocates memory for a new node in the color cube tree and % presets all fields to zero. % % The format of the GetNodeInfo method is: % % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id, % const size_t level,NodeInfo *parent) % % A description of each parameter follows. % % o node: The GetNodeInfo method returns a pointer to a queue of nodes. % % o id: Specifies the child number of the node. % % o level: Specifies the level in the storage_class the node resides. % */ static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id, const size_t level,NodeInfo *parent) { NodeInfo *node_info; if (cube_info->free_nodes == 0) { Nodes *nodes; /* Allocate a new queue of nodes. */ nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes)); if (nodes == (Nodes *) NULL) return((NodeInfo *) NULL); nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList, sizeof(*nodes->nodes)); if (nodes->nodes == (NodeInfo *) NULL) return((NodeInfo *) NULL); nodes->next=cube_info->node_queue; cube_info->node_queue=nodes; cube_info->next_node=nodes->nodes; cube_info->free_nodes=NodesInAList; } cube_info->nodes++; cube_info->free_nodes--; node_info=cube_info->next_node++; (void) memset(node_info,0,sizeof(*node_info)); node_info->parent=parent; node_info->id=id; node_info->level=level; return(node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e Q u a n t i z e E r r o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageQuantizeError() measures the difference between the original % and quantized images. This difference is the total quantization error. % The error is computed by summing over all pixels in an image the distance % squared in RGB space between each reference pixel value and its quantized % value. These values are computed: % % o mean_error_per_pixel: This value is the mean error for any single % pixel in the image. % % o normalized_mean_square_error: This value is the normalized mean % quantization error for any single pixel in the image. This distance % measure is normalized to a range between 0 and 1. It is independent % of the range of red, green, and blue values in the image. % % o normalized_maximum_square_error: Thsi value is the normalized % maximum quantization error for any single pixel in the image. This % distance measure is normalized to a range between 0 and 1. It is % independent of the range of red, green, and blue values in your image. % % The format of the GetImageQuantizeError method is: % % MagickBooleanType GetImageQuantizeError(Image *image) % % A description of each parameter follows. % % o image: the image. % */ MagickExport MagickBooleanType GetImageQuantizeError(Image *image) { CacheView *image_view; ExceptionInfo *exception; IndexPacket *indexes; MagickRealType alpha, area, beta, distance, gamma, maximum_error, mean_error, mean_error_per_pixel; size_t index; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception); (void) memset(&image->error,0,sizeof(image->error)); if (image->storage_class == DirectClass) return(MagickTrue); alpha=1.0; beta=1.0; area=3.0*image->columns*image->rows; maximum_error=0.0; mean_error_per_pixel=0.0; mean_error=0.0; exception=(&image->exception); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { index=1UL*GetPixelIndex(indexes+x); if (image->matte != MagickFalse) { alpha=(MagickRealType) (QuantumScale*(GetPixelAlpha(p))); beta=(MagickRealType) (QuantumScale*(QuantumRange- image->colormap[index].opacity)); } distance=fabs((double) (alpha*GetPixelRed(p)-beta* image->colormap[index].red)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; distance=fabs((double) (alpha*GetPixelGreen(p)-beta* image->colormap[index].green)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; distance=fabs((double) (alpha*GetPixelBlue(p)-beta* image->colormap[index].blue)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; p++; } } image_view=DestroyCacheView(image_view); gamma=PerceptibleReciprocal(area); image->error.mean_error_per_pixel=gamma*mean_error_per_pixel; image->error.normalized_mean_error=gamma*QuantumScale*QuantumScale*mean_error; image->error.normalized_maximum_error=QuantumScale*maximum_error; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantizeInfo() initializes the QuantizeInfo structure. % % The format of the GetQuantizeInfo method is: % % GetQuantizeInfo(QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to a QuantizeInfo structure. % */ MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(quantize_info != (QuantizeInfo *) NULL); (void) memset(quantize_info,0,sizeof(*quantize_info)); quantize_info->number_colors=256; quantize_info->dither=MagickTrue; quantize_info->dither_method=RiemersmaDitherMethod; quantize_info->colorspace=UndefinedColorspace; quantize_info->measure_error=MagickFalse; quantize_info->signature=MagickCoreSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o s t e r i z e I m a g e C h a n n e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PosterizeImage() reduces the image to a limited number of colors for a % "poster" effect. % % The format of the PosterizeImage method is: % % MagickBooleanType PosterizeImage(Image *image,const size_t levels, % const MagickBooleanType dither) % MagickBooleanType PosterizeImageChannel(Image *image, % const ChannelType channel,const size_t levels, % const MagickBooleanType dither) % % A description of each parameter follows: % % o image: Specifies a pointer to an Image structure. % % o levels: Number of color levels allowed in each channel. Very low values % (2, 3, or 4) have the most visible effect. % % o dither: Set this integer value to something other than zero to dither % the mapped image. % */ static inline double MagickRound(double x) { /* Round the fraction to nearest integer. */ if ((x-floor(x)) < (ceil(x)-x)) return(floor(x)); return(ceil(x)); } MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels, const MagickBooleanType dither) { MagickBooleanType status; status=PosterizeImageChannel(image,DefaultChannels,levels,dither); return(status); } MagickExport MagickBooleanType PosterizeImageChannel(Image *image, const ChannelType channel,const size_t levels,const MagickBooleanType dither) { #define PosterizeImageTag "Posterize/Image" #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \ QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1)) CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; QuantizeInfo *quantize_info; register ssize_t i; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->colors,1) #endif for (i=0; i < (ssize_t) image->colors; i++) { /* Posterize colormap. */ if ((channel & RedChannel) != 0) image->colormap[i].red=PosterizePixel(image->colormap[i].red); if ((channel & GreenChannel) != 0) image->colormap[i].green=PosterizePixel(image->colormap[i].green); if ((channel & BlueChannel) != 0) image->colormap[i].blue=PosterizePixel(image->colormap[i].blue); if ((channel & OpacityChannel) != 0) image->colormap[i].opacity=PosterizePixel(image->colormap[i].opacity); } /* Posterize image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,PosterizePixel(GetPixelRed(q))); if ((channel & GreenChannel) != 0) SetPixelGreen(q,PosterizePixel(GetPixelGreen(q))); if ((channel & BlueChannel) != 0) SetPixelBlue(q,PosterizePixel(GetPixelBlue(q))); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetPixelOpacity(q,PosterizePixel(GetPixelOpacity(q))); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(indexes+x,PosterizePixel(GetPixelIndex(indexes+x))); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,PosterizeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL); quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels* levels,MaxColormapSize+1); quantize_info->dither=dither; quantize_info->tree_depth=MaxTreeDepth; status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e C h i l d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneChild() deletes the given node and merges its statistics into its % parent. % % The format of the PruneSubtree method is: % % PruneChild(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneChild(CubeInfo *cube_info,const NodeInfo *node_info) { NodeInfo *parent; register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneChild(cube_info,node_info->child[i]); /* Merge color statistics into parent. */ parent=node_info->parent; parent->number_unique+=node_info->number_unique; parent->total_color.red+=node_info->total_color.red; parent->total_color.green+=node_info->total_color.green; parent->total_color.blue+=node_info->total_color.blue; parent->total_color.opacity+=node_info->total_color.opacity; parent->child[node_info->id]=(NodeInfo *) NULL; cube_info->nodes--; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e L e v e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneLevel() deletes all nodes at the bottom level of the color tree merging % their color statistics into their parent node. % % The format of the PruneLevel method is: % % PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneLevel(cube_info,node_info->child[i]); if (node_info->level == cube_info->depth) PruneChild(cube_info,node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e T o C u b e D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneToCubeDepth() deletes any nodes at a depth greater than % cube_info->depth while merging their color statistics into their parent % node. % % The format of the PruneToCubeDepth method is: % % PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneToCubeDepth(cube_info,node_info->child[i]); if (node_info->level > cube_info->depth) PruneChild(cube_info,node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u a n t i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeImage() analyzes the colors within a reference image and chooses a % fixed number of colors to represent the image. The goal of the algorithm % is to minimize the color difference between the input and output image while % minimizing the processing time. % % The format of the QuantizeImage method is: % % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info, % Image *image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o image: the image. % */ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info, Image *image) { CubeInfo *cube_info; MagickBooleanType status; size_t depth, maximum_colors; assert(quantize_info != (const QuantizeInfo *) NULL); assert(quantize_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); maximum_colors=quantize_info->number_colors; if (maximum_colors == 0) maximum_colors=MaxColormapSize; if (maximum_colors > MaxColormapSize) maximum_colors=MaxColormapSize; if (image->matte == MagickFalse) { if (SetImageGray(image,&image->exception) != MagickFalse) (void) SetGrayscaleImage(image); } if ((image->storage_class == PseudoClass) && (image->colors <= maximum_colors)) { if ((quantize_info->colorspace != UndefinedColorspace) && (quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace(image,quantize_info->colorspace); return(MagickTrue); } depth=quantize_info->tree_depth; if (depth == 0) { size_t colors; /* Depth of color tree is: Log4(colormap size)+2. */ colors=maximum_colors; for (depth=1; colors != 0; depth++) colors>>=2; if ((quantize_info->dither != MagickFalse) && (depth > 2)) depth--; if ((image->matte != MagickFalse) && (depth > 5)) depth--; if (SetImageGray(image,&image->exception) != MagickFalse) depth=MaxTreeDepth; } /* Initialize color cube. */ cube_info=GetCubeInfo(quantize_info,depth,maximum_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,image,&image->exception); if (status != MagickFalse) { /* Reduce the number of colors in the image if it contains more than the maximum, otherwise we can disable dithering to improve the performance. */ if (cube_info->colors > cube_info->maximum_colors) ReduceImageColors(image,cube_info); else cube_info->quantize_info->dither_method=NoDitherMethod; status=AssignImageColors(image,cube_info); } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u a n t i z e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeImages() analyzes the colors within a set of reference images and % chooses a fixed number of colors to represent the set. The goal of the % algorithm is to minimize the color difference between the input and output % images while minimizing the processing time. % % The format of the QuantizeImages method is: % % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info, % Image *images) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o images: Specifies a pointer to a list of Image structures. % */ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info, Image *images) { CubeInfo *cube_info; Image *image; MagickBooleanType proceed, status; MagickProgressMonitor progress_monitor; register ssize_t i; size_t depth, maximum_colors, number_images; assert(quantize_info != (const QuantizeInfo *) NULL); assert(quantize_info->signature == MagickCoreSignature); assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); if (GetNextImageInList(images) == (Image *) NULL) { /* Handle a single image with QuantizeImage. */ status=QuantizeImage(quantize_info,images); return(status); } status=MagickFalse; maximum_colors=quantize_info->number_colors; if (maximum_colors == 0) maximum_colors=MaxColormapSize; if (maximum_colors > MaxColormapSize) maximum_colors=MaxColormapSize; depth=quantize_info->tree_depth; if (depth == 0) { size_t colors; /* Depth of color tree is: Log4(colormap size)+2. */ colors=maximum_colors; for (depth=1; colors != 0; depth++) colors>>=2; if (quantize_info->dither != MagickFalse) depth--; } /* Initialize color cube. */ cube_info=GetCubeInfo(quantize_info,depth,maximum_colors); if (cube_info == (CubeInfo *) NULL) { (void) ThrowMagickException(&images->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return(MagickFalse); } number_images=GetImageListLength(images); image=images; for (i=0; image != (Image *) NULL; i++) { progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL, image->client_data); status=ClassifyImageColors(cube_info,image,&image->exception); if (status == MagickFalse) break; (void) SetImageProgressMonitor(image,progress_monitor,image->client_data); proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); } if (status != MagickFalse) { /* Reduce the number of colors in an image sequence. */ ReduceImageColors(images,cube_info); image=images; for (i=0; image != (Image *) NULL; i++) { progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,image->client_data); status=AssignImageColors(image,cube_info); if (status == MagickFalse) break; (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); } } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u a n t i z e E r r o r F l a t t e n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeErrorFlatten() traverses the color cube and flattens the quantization % error into a sorted 1D array. This accelerates the color reduction process. % % Contributed by Yoya. % % The format of the QuantizeErrorFlatten method is: % % size_t QuantizeErrorFlatten(const CubeInfo *cube_info, % const NodeInfo *node_info,const ssize_t offset, % MagickRealType *quantize_error) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is current pointer. % % o offset: quantize error offset. % % o quantize_error: the quantization error vector. % */ static size_t QuantizeErrorFlatten(const CubeInfo *cube_info, const NodeInfo *node_info,const ssize_t offset, MagickRealType *quantize_error) { register ssize_t i; size_t n, number_children; if (offset >= (ssize_t) cube_info->nodes) return(0); quantize_error[offset]=node_info->quantize_error; n=1; number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children ; i++) if (node_info->child[i] != (NodeInfo *) NULL) n+=QuantizeErrorFlatten(cube_info,node_info->child[i],offset+n, quantize_error); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e d u c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Reduce() traverses the color cube tree and prunes any node whose % quantization error falls below a particular threshold. % % The format of the Reduce method is: % % Reduce(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void Reduce(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) Reduce(cube_info,node_info->child[i]); if (node_info->quantize_error <= cube_info->pruning_threshold) PruneChild(cube_info,node_info); else { /* Find minimum pruning threshold. */ if (node_info->number_unique > 0) cube_info->colors++; if (node_info->quantize_error < cube_info->next_threshold) cube_info->next_threshold=node_info->quantize_error; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e d u c e I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReduceImageColors() repeatedly prunes the tree until the number of nodes % with n2 > 0 is less than or equal to the maximum number of colors allowed % in the output image. On any given iteration over the tree, it selects % those nodes whose E value is minimal for pruning and merges their % color statistics upward. It uses a pruning threshold, Ep, to govern % node selection as follows: % % Ep = 0 % while number of nodes with (n2 > 0) > required maximum number of colors % prune all nodes such that E <= Ep % Set Ep to minimum E in remaining nodes % % This has the effect of minimizing any quantization error when merging % two nodes together. % % When a node to be pruned has offspring, the pruning procedure invokes % itself recursively in order to prune the tree from the leaves upward. % n2, Sr, Sg, and Sb in a node being pruned are always added to the % corresponding data in that node's parent. This retains the pruned % node's color characteristics for later averaging. % % For each node, n2 pixels exist for which that node represents the % smallest volume in RGB space containing those pixel's colors. When n2 % > 0 the node will uniquely define a color in the output image. At the % beginning of reduction, n2 = 0 for all nodes except a the leaves of % the tree which represent colors present in the input image. % % The other pixel count, n1, indicates the total number of colors % within the cubic volume which the node represents. This includes n1 - % n2 pixels whose colors should be defined by nodes at a lower level in % the tree. % % The format of the ReduceImageColors method is: % % ReduceImageColors(const Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static int MagickRealTypeCompare(const void *error_p,const void *error_q) { MagickRealType *p, *q; p=(MagickRealType *) error_p; q=(MagickRealType *) error_q; if (*p > *q) return(1); if (fabs((double) (*q-*p)) <= MagickEpsilon) return(0); return(-1); } static void ReduceImageColors(const Image *image,CubeInfo *cube_info) { #define ReduceImageTag "Reduce/Image" MagickBooleanType proceed; MagickOffsetType offset; size_t span; cube_info->next_threshold=0.0; if (cube_info->colors > cube_info->maximum_colors) { MagickRealType *quantize_error; /* Enable rapid reduction of the number of unique colors. */ quantize_error=(MagickRealType *) AcquireQuantumMemory(cube_info->nodes, sizeof(*quantize_error)); if (quantize_error != (MagickRealType *) NULL) { (void) QuantizeErrorFlatten(cube_info,cube_info->root,0, quantize_error); qsort(quantize_error,cube_info->nodes,sizeof(MagickRealType), MagickRealTypeCompare); if (cube_info->nodes > (110*(cube_info->maximum_colors+1)/100)) cube_info->next_threshold=quantize_error[cube_info->nodes-110* (cube_info->maximum_colors+1)/100]; quantize_error=(MagickRealType *) RelinquishMagickMemory( quantize_error); } } for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; ) { cube_info->pruning_threshold=cube_info->next_threshold; cube_info->next_threshold=cube_info->root->quantize_error-1; cube_info->colors=0; Reduce(cube_info,cube_info->root); offset=(MagickOffsetType) span-cube_info->colors; proceed=SetImageProgress(image,ReduceImageTag,offset,span- cube_info->maximum_colors+1); if (proceed == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m a p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemapImage() replaces the colors of an image with the closest color from % a reference image. % % The format of the RemapImage method is: % % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info, % Image *image,const Image *remap_image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o image: the image. % % o remap_image: the reference image. % */ MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info, Image *image,const Image *remap_image) { CubeInfo *cube_info; MagickBooleanType status; /* Initialize color cube. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(remap_image != (Image *) NULL); assert(remap_image->signature == MagickCoreSignature); cube_info=GetCubeInfo(quantize_info,MaxTreeDepth, quantize_info->number_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,remap_image,&image->exception); if (status != MagickFalse) { /* Classify image colors from the reference image. */ cube_info->quantize_info->number_colors=cube_info->colors; status=AssignImageColors(image,cube_info); } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m a p I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemapImages() replaces the colors of a sequence of images with the % closest color from a reference image. % % The format of the RemapImage method is: % % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info, % Image *images,Image *remap_image) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o images: the image sequence. % % o remap_image: the reference image. % */ MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info, Image *images,const Image *remap_image) { CubeInfo *cube_info; Image *image; MagickBooleanType status; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); image=images; if (remap_image == (Image *) NULL) { /* Create a global colormap for an image sequence. */ status=QuantizeImages(quantize_info,images); return(status); } /* Classify image colors from the reference image. */ cube_info=GetCubeInfo(quantize_info,MaxTreeDepth, quantize_info->number_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,remap_image,&image->exception); if (status != MagickFalse) { /* Classify image colors from the reference image. */ cube_info->quantize_info->number_colors=cube_info->colors; image=images; for ( ; image != (Image *) NULL; image=GetNextImageInList(image)) { status=AssignImageColors(image,cube_info); if (status == MagickFalse) break; } } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t G r a y s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetGrayscaleImage() converts an image to a PseudoClass grayscale image. % % The format of the SetGrayscaleImage method is: % % MagickBooleanType SetGrayscaleImage(Image *image) % % A description of each parameter follows: % % o image: The image. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { PixelPacket *color_1, *color_2; int intensity; color_1=(PixelPacket *) x; color_2=(PixelPacket *) y; intensity=PixelPacketIntensity(color_1)-(int) PixelPacketIntensity(color_2); return((int) intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickBooleanType SetGrayscaleImage(Image *image) { CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; PixelPacket *colormap; register ssize_t i; ssize_t *colormap_index, j, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); exception=(&image->exception); if (image->type != GrayscaleType) (void) TransformImageColorspace(image,GRAYColorspace); if (image->storage_class == PseudoClass) colormap_index=(ssize_t *) AcquireQuantumMemory(image->colors+1, sizeof(*colormap_index)); else colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize+1, sizeof(*colormap_index)); if (colormap_index == (ssize_t *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); if (image->storage_class != PseudoClass) { (void) memset(colormap_index,(-1),MaxColormapSize* sizeof(*colormap_index)); if (AcquireImageColormap(image,MaxColormapSize) == MagickFalse) { colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } image->colors=0; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { register size_t intensity; intensity=ScaleQuantumToMap(GetPixelRed(q)); if (colormap_index[intensity] < 0) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SetGrayscaleImage) #endif if (colormap_index[intensity] < 0) { colormap_index[intensity]=(ssize_t) image->colors; image->colormap[image->colors].red=GetPixelRed(q); image->colormap[image->colors].green=GetPixelGreen(q); image->colormap[image->colors].blue=GetPixelBlue(q); image->colors++; } } SetPixelIndex(indexes+x,colormap_index[intensity]); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); } for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].opacity=(unsigned short) i; qsort((void *) image->colormap,image->colors,sizeof(PixelPacket), IntensityCompare); colormap=(PixelPacket *) AcquireQuantumMemory(image->colors, sizeof(*colormap)); if (colormap == (PixelPacket *) NULL) { colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } j=0; colormap[j]=image->colormap[0]; for (i=0; i < (ssize_t) image->colors; i++) { if (IsSameColor(image,&colormap[j],&image->colormap[i]) == MagickFalse) { j++; colormap[j]=image->colormap[i]; } colormap_index[(ssize_t) image->colormap[i].opacity]=j; } image->colors=(size_t) (j+1); image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap); image->colormap=colormap; status=MagickTrue; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,colormap_index[ScaleQuantumToMap(GetPixelIndex( indexes+x))]); if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); image->type=GrayscaleType; if (SetImageMonochrome(image,&image->exception) != MagickFalse) image->type=BilevelType; return(status); }
xthi_nested_omp.c
/* This nested OpenMP version is adapted by Helen He from the hybrid MPI/OpenMP Cray Source code "xthi.c" available at: http://docs.cray.com/books/S-2496-4101/html-S-2496-4101/cnlexamples.html */ #define _GNU_SOURCE #include <stdio.h> #include <unistd.h> #include <string.h> #include <sched.h> #include <omp.h> /* Borrowed from util-linux-2.13-pre7/schedutils/taskset.c */ static char *cpuset_to_cstr(cpu_set_t *mask, char *str) { char *ptr = str; int i, j, entry_made = 0; for (i = 0; i < CPU_SETSIZE; i++) { if (CPU_ISSET(i, mask)) { int run = 0; entry_made = 1; for (j = i + 1; j < CPU_SETSIZE; j++) { if (CPU_ISSET(j, mask)) run++; else break; } if (!run) sprintf(ptr, "%d,", i); else if (run == 1) { sprintf(ptr, "%d,%d,", i, i + 1); i++; } else { sprintf(ptr, "%d-%d,", i, i + run); i += run; } while (*ptr != 0) ptr++; } } ptr -= entry_made; *ptr = 0; return(str); } int main(int argc, char *argv[]) { int thread1, thread2; cpu_set_t coremask1, coremask2; char clbuf1[7 * CPU_SETSIZE], hnbuf1[64]; char clbuf2[7 * CPU_SETSIZE], hnbuf2[64]; memset(clbuf1, 0, sizeof(clbuf1)); memset(clbuf2, 0, sizeof(clbuf2)); memset(hnbuf1, 0, sizeof(hnbuf1)); memset(hnbuf2, 0, sizeof(hnbuf2)); (void)gethostname(hnbuf1, sizeof(hnbuf1)); (void)gethostname(hnbuf2, sizeof(hnbuf2)); #pragma omp parallel private(thread1, coremask1, clbuf1) { thread1 = omp_get_thread_num(); (void)sched_getaffinity(0, sizeof(coremask1), &coremask1); cpuset_to_cstr(&coremask1, clbuf1); #pragma omp barrier printf("Hello from level 1: thread level 1= %d, on %s. (core affinity = %s)\n", thread1, hnbuf1, clbuf1); #pragma omp parallel private(thread2, coremask2, clbuf2) { thread2 = omp_get_thread_num(); (void)sched_getaffinity(0, sizeof(coremask2), &coremask2); cpuset_to_cstr(&coremask2, clbuf2); #pragma omp barrier printf("Hello from level 2: thread level 1= %d, thread level 2= %d, on %s. (core affinity = %s)\n", thread1, thread2, hnbuf2, clbuf2); } } return(0); }
ParticleFilterOMP.h
//------------------------------------------------------------------------ // ____ _ _ // / ___|____ _ _ ____ ____| |__ | | // | | / ___| | | | _ \/ ___| _ \| | // | |___| | | |_| | | | | |___| | | ||_| // \____|_| \_____|_| |_|\____|_| |_|(_) Media benchmarks // // 2006, Intel Corporation, licensed under Apache 2.0 // // file : ParticleFilterOMP.h // author : Scott Ettinger - scott.m.ettinger@intel.com // // description : OpenMP parallelized version of the particle filter // object derived from ParticleFilter.h // // modified : //-------------------------------------------------------------------------- #ifndef PARTICLEFILTEROMP_H #define PARTICLEFILTEROMP_H #if defined(HAVE_CONFIG_H) # include "config.h" #endif #include <omp.h> #include "ParticleFilter.h" template<class T> class ParticleFilterOMP : public ParticleFilter<T> { using ParticleFilter<T>:: mModel; using ParticleFilter<T>:: mWeights; using ParticleFilter<T>:: mParticles; using ParticleFilter<T>:: mNewParticles; using ParticleFilter<T>:: mBestParticle; using ParticleFilter<T>:: mNParticles; using ParticleFilter<T>:: mMinParticles; using ParticleFilter<T>:: mBins; using ParticleFilter<T>:: mRnd; typedef typename ParticleFilter<T>::fpType fpType; typedef typename ParticleFilter<T>::Vectorf Vectorf; protected: std::vector<int> mIndex; //list of particles to regenerate //calculate particle weights - threaded version void CalcWeights(std::vector<Vectorf > &particles); //calculate particle weights based on model likelihood //New particle generation - threaded version void GenerateNewParticles(int k); }; //Calculate particle weights (mWeights) and find highest likelihood particle. //computes an optimal annealing factor and scales the likelihoods. template<class T> void ParticleFilterOMP<T>::CalcWeights(std::vector<Vectorf > &particles) { std::vector<unsigned char> valid(particles.size()); mBestParticle = 0; fpType total = 0, best = 0, minWeight = 1e30f, annealingFactor = 1; mWeights.resize(particles.size()); int np = (int)particles.size(), j; #pragma omp parallel for //OpenMP parallelized loop to compute log-likelihoods for(j = 0; j < np; j++) { bool vflag; int n = omp_get_thread_num(); mWeights[j] = mModel->LogLikelihood(particles[j], vflag, n); //compute log-likelihood weights for each particle valid[j] = vflag ? 1 : 0; } uint i = 0; while(i < particles.size()) { if(!valid[i]) //if not valid(model prior), remove the particle from the list { particles[i] = particles[particles.size() - 1]; mWeights[i] = mWeights[particles.size() - 1]; valid[i] = valid[valid.size() - 1]; particles.pop_back(); mWeights.pop_back(); valid.pop_back(); } else minWeight = std::min(mWeights[i++], minWeight); //find minimum log-likelihood } if((int)particles.size() < mMinParticles) return; //bail out if not enough valid particles mWeights -= minWeight; //shift weights to zero for numerical stability if(mModel->StdDevs().size() > 1) annealingFactor = BetaAnnealingFactor(mWeights, 0.5f); //calculate annealing factor if more than 1 step for(i = 0; i < mWeights.size(); i++) { double wa = annealingFactor * mWeights[i]; mWeights[i] = (float)exp(wa); //exponentiate log-likelihoods scaled by annealing factor total += mWeights[i]; //save sum of all weights if(i == 0 || mWeights[i] > best) //find highest likelihood particle { best = mWeights[i]; mBestParticle = i; } } mWeights *= fpType(1.0) / total; //normalize weights } //generate new particles distributed with std deviation given by the model annealing parameter - threaded template<class T> void ParticleFilterOMP<T>::GenerateNewParticles(int k) { int p = 0; mNewParticles.resize(mNParticles); mIndex.resize(mNParticles); for(int i = 0; i < (int)mBins.size(); i++) for(uint j = 0; j < mBins[i]; j++) //index particles to be regenerated mIndex[p++] = i; #pragma omp parallel for for(int i = 0; i < mNParticles; i++) //distribute new particles randomly according to model stdDevs { mNewParticles[i] = mParticles[mIndex[i]]; //add new particle for each entry in each bin distributed randomly about duplicated particle AddGaussianNoise(mNewParticles[i], mModel->StdDevs()[k], mRnd[i]); } } #endif
ast-dump-openmp-target-teams-distribute-simd.c
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s void test_one(int x) { #pragma omp target teams distribute simd for (int i = 0; i < x; i++) ; } void test_two(int x, int y) { #pragma omp target teams distribute simd for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_three(int x, int y) { #pragma omp target teams distribute simd collapse(1) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_four(int x, int y) { #pragma omp target teams distribute simd collapse(2) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_five(int x, int y, int z) { #pragma omp target teams distribute simd collapse(2) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) for (int i = 0; i < z; i++) ; } // CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK: |-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-target-teams-distribute-simd.c:3:1, line:7:1> line:3:6 test_one 'void (int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:22, line:7:1> // CHECK-NEXT: | `-OMPTargetTeamsDistributeSimdDirective {{.*}} <line:4:9, col:41> // CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:5:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-CapturedStmt {{.*}} <col:3, line:6:5> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:5:3, line:6:5> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-CapturedStmt {{.*}} <line:5:3, line:6:5> // CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:5:3, line:6:5> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:5:8, col:17> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:6:5> openmp_structured_block // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:5:23> col:23 implicit 'int' // CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <col:3, line:6:5> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:5:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:6:5> openmp_structured_block // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:5:23> col:23 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <col:3, line:6:5> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:5:3, line:6:5> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:5:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:6:5> openmp_structured_block // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:5:23> col:23 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <col:3, line:6:5> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:5:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:6:5> openmp_structured_block // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:4:9) *const restrict' // CHECK-NEXT: | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:9:1, line:14:1> line:9:6 test_two 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:22, col:26> col:26 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:29, line:14:1> // CHECK-NEXT: | `-OMPTargetTeamsDistributeSimdDirective {{.*}} <line:10:9, col:41> // CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:11:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-CapturedStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:11:8, col:17> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:12:5, line:13:7> openmp_structured_block // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:12:10, col:19> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:13:7> // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:10:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:10:9) *const restrict' // CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:11:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:10:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:10:9) *const restrict' // CHECK-NEXT: | | | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:11:23> col:23 implicit 'int' // CHECK-NEXT: | | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:12:25> col:25 implicit 'int' // CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:11:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:12:5, line:13:7> openmp_structured_block // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:12:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:13:7> // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:10:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:10:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:11:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:10:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:11:23> col:23 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:12:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:11:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:12:5, line:13:7> openmp_structured_block // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:12:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:13:7> // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:10:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:10:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:11:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:10:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:11:23> col:23 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:12:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:11:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:12:5, line:13:7> openmp_structured_block // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:12:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:13:7> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:10:9) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:11:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:16:1, line:21:1> line:16:6 test_three 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:17, col:21> col:21 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:24, col:28> col:28 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:31, line:21:1> // CHECK-NEXT: | `-OMPTargetTeamsDistributeSimdDirective {{.*}} <line:17:9, col:53> // CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:42, col:52> // CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:51> 'int' // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:51> 'int' 1 // CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:18:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-CapturedStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:18:8, col:17> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:19:5, line:20:7> openmp_structured_block // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:19:10, col:19> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:20:7> // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:17:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:17:9) *const restrict' // CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:18:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:17:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:17:9) *const restrict' // CHECK-NEXT: | | | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:18:23> col:23 implicit 'int' // CHECK-NEXT: | | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:19:25> col:25 implicit 'int' // CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:18:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:19:5, line:20:7> openmp_structured_block // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:19:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:20:7> // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:17:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:17:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:18:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:17:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:18:23> col:23 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:19:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:18:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:19:5, line:20:7> openmp_structured_block // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:19:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:20:7> // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:17:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:17:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:18:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:17:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:18:23> col:23 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:19:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:18:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:19:5, line:20:7> openmp_structured_block // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:19:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:20:7> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:17:9) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:18:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:23:1, line:28:1> line:23:6 test_four 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:30, line:28:1> // CHECK-NEXT: | `-OMPTargetTeamsDistributeSimdDirective {{.*}} <line:24:9, col:53> // CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:42, col:52> // CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:51> 'int' // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:51> 'int' 2 // CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:25:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:26:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-CapturedStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:25:8, col:17> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:26:5, line:27:7> // CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:26:10, col:19> // CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:27:7> openmp_structured_block // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:24:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:24:9) *const restrict' // CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:25:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:26:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:24:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:24:9) *const restrict' // CHECK-NEXT: | | | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:25:23> col:23 implicit 'int' // CHECK-NEXT: | | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:26:25> col:25 implicit 'int' // CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:25:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:26:5, line:27:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:26:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:27:7> openmp_structured_block // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:24:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:24:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:25:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:26:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:24:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:25:23> col:23 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:26:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:25:8, col:17> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:26:5, line:27:7> // CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:26:10, col:19> // CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:27:7> openmp_structured_block // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:24:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:24:9) *const restrict' // CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:25:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:26:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:24:9) *const restrict' // CHECK-NEXT: | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:25:23> col:23 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:26:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:25:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:26:5, line:27:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:26:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:27:7> openmp_structured_block // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:24:9) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:25:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:26:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-FunctionDecl {{.*}} <line:30:1, line:36:1> line:30:6 test_five 'void (int, int, int)' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:30, col:34> col:34 used z 'int' // CHECK-NEXT: `-CompoundStmt {{.*}} <col:37, line:36:1> // CHECK-NEXT: `-OMPTargetTeamsDistributeSimdDirective {{.*}} <line:31:9, col:53> // CHECK-NEXT: |-OMPCollapseClause {{.*}} <col:42, col:52> // CHECK-NEXT: | `-ConstantExpr {{.*}} <col:51> 'int' // CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:51> 'int' 2 // CHECK-NEXT: |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit> // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:32:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:33:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: `-CapturedStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-CapturedStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-CapturedStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | | | |-ForStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:32:8, col:17> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:33:5, line:35:9> // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:33:10, col:19> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:34:7, line:35:9> openmp_structured_block // CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:34:12, col:21> // CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:35:9> // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:31:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:31:9) *const restrict' // CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | | |-DeclRefExpr {{.*}} <line:32:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-DeclRefExpr {{.*}} <line:33:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:31:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:31:9) *const restrict' // CHECK-NEXT: | | | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | | | |-FieldDecl {{.*}} <line:32:23> col:23 implicit 'int' // CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | | |-FieldDecl {{.*}} <line:33:25> col:25 implicit 'int' // CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | | `-FieldDecl {{.*}} <line:34:27> col:27 implicit 'int' // CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-ForStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:32:8, col:17> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:33:5, line:35:9> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:33:10, col:19> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:34:7, line:35:9> openmp_structured_block // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:34:12, col:21> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:35:9> // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:31:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:31:9) *const restrict' // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:32:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:33:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:9> col:9 implicit .global_tid. 'const int' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .part_id. 'const int *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .privates. 'void *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .task_t. 'void *const' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:31:9) *const restrict' // CHECK-NEXT: | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | |-FieldDecl {{.*}} <line:32:23> col:23 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | |-FieldDecl {{.*}} <line:33:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-FieldDecl {{.*}} <line:34:27> col:27 implicit 'int' // CHECK-NEXT: | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-CapturedStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | | |-ForStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:32:8, col:17> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:33:5, line:35:9> // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:33:10, col:19> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:34:7, line:35:9> openmp_structured_block // CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:34:12, col:21> // CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | | | |-<<<NULL>>> // CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:35:9> // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:31:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:31:9) *const restrict' // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:32:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:33:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:31:9) *const restrict' // CHECK-NEXT: | |-RecordDecl {{.*}} <col:9> col:9 implicit struct definition // CHECK-NEXT: | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit // CHECK-NEXT: | | |-FieldDecl {{.*}} <line:32:23> col:23 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | |-FieldDecl {{.*}} <line:33:25> col:25 implicit 'int' // CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | | `-FieldDecl {{.*}} <line:34:27> col:27 implicit 'int' // CHECK-NEXT: | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit 9 // CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-ForStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: | | |-DeclStmt {{.*}} <line:32:8, col:17> // CHECK-NEXT: | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | |-<<<NULL>>> // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | `-ForStmt {{.*}} <line:33:5, line:35:9> // CHECK-NEXT: | | |-DeclStmt {{.*}} <line:33:10, col:19> // CHECK-NEXT: | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | |-<<<NULL>>> // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | `-ForStmt {{.*}} <line:34:7, line:35:9> openmp_structured_block // CHECK-NEXT: | | |-DeclStmt {{.*}} <line:34:12, col:21> // CHECK-NEXT: | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | |-<<<NULL>>> // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | `-NullStmt {{.*}} <line:35:9> // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:9> col:9 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:9> col:9 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-teams-distribute-simd.c:31:9) *const restrict' // CHECK-NEXT: | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:32:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:33:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
rendezvous.c
#include <stdio.h> #include <unistd.h> #include <omp.h> typedef struct printer printer; struct printer { int id, ink; }; printer pnt_main = { 1, 5 }; printer pnt_backup = { 2, 5 }; int print(const char * text, const char **error) { #pragma omp critical { printer *p = &pnt_main; if (!p->ink) p = &pnt_backup; if (!p->ink) *error = "Out of ink"; else { *error = 0; p->ink--; printf("%d | ", p->id, p->ink); while (*text != '\0') { putchar(*(text++)); fflush(stdout); usleep(30000); } putchar('\n'); } } return 0 != *error; } const char *humpty[] = { "Humpty Dumpty sat on a wall.", "Humpty Dumpty had a great fall.", "All the king's horses and all the king's men,", "Couldn't put Humpty together again." }; const char *goose[] = { "Old Mother Goose,", "When she wanted to wander,", "Would ride through the air,", "On a very fine gander.", "Jack's mother came in,", "And caught the goose soon,", "And mounting its back,", "Flew up to the moon." }; int main() { int i, j, len; const char *msg, **text; omp_set_num_threads(2); #pragma omp parallel for private(text, msg, len, j) for (i = 0; i < 2; i++) { text = i ? goose : humpty; len = (i ? sizeof(goose) : sizeof(humpty) ) / sizeof(const char*); for (j = 0; j < len; j++) { usleep(100000); if (print(text[j], &msg)) { fprintf(stderr, "Error: %s\n", msg); break; } } } return 0; }