source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
eval_XC_func.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "eval_XC_func.h"
// ========================= LDA functionals ========================= //
// Input parameters:
// npt : Total number of points
// rho : Size npt, electron density at each point
// Output parameters:
// exc : Size npt, = G / rho
// vxc : Size npt, = \frac{\part G}{\part rho}
// Slater exchange
void eval_LDA_exc_vxc_X(const int npt, const double *rho, double *exc, double *vxc)
{
const double c0 = 0.9847450218426965; // (3/pi)^(1/3)
const double a = 2.0/3.0;
const double c1 = -a * (9.0/8.0) * c0;
const double c2 = -a * (3.0/2.0) * c0;
#pragma omp simd
for (int i = 0; i < npt; i++)
{
double rho_cbrt = cbrt(rho[i]);
exc[i] = c1 * rho_cbrt;
vxc[i] = c2 * rho_cbrt;
}
}
// Slater Xalpha correlation (Xalpha = 0.7 - 2/3)
void eval_LDA_exc_vxc_C_XA(const int npt, const double *rho, double *exc, double *vxc)
{
const double c0 = 0.9847450218426965; // (3/pi)^(1/3)
const double a = 0.7 - (2.0/3.0); // alpha = 0.7, minus 2/3 exchange part
const double c1 = -a * (9.0/8.0) * c0;
const double c2 = -a * (3.0/2.0) * c0;
#pragma omp simd
for (int i = 0; i < npt; i++)
{
double rho_cbrt = cbrt(rho[i]);
exc[i] = c1 * rho_cbrt;
vxc[i] = c2 * rho_cbrt;
}
}
// LDA Perdew-Zunger correlation (PZ81)
void eval_LDA_exc_vxc_C_PZ81(const int npt, const double *rho, double *exc, double *vxc)
{
// PZ81 correlation parameters
const double A = 0.0311;
const double B = -0.048;
const double C = 0.002;
const double D = -0.0116;
const double g1 = -0.1423; // gamma1
const double b1 = 1.0529; // beta1
const double b2 = 0.3334; // beta2
const double c0 = 0.6203504908993999; // (3/(4*pi))^(1/3)
const double t0 = 2.0 * C / 3.0;
const double t1 = B - A / 3.0;
const double t2 = (2.0 * D - C) / 3.0;
const double t3 = (7.0/6.0) * g1 * b1;
const double t4 = (4.0/3.0) * g1 * b2;
#pragma omp simd
for (int i = 0; i < npt; i++)
{
double rho_cbrt = cbrt(rho[i]) + 1e-20;
double rs = c0 / rho_cbrt; // rs = (3/(4*pi*rho))^(1/3)
if (rs < 1.0)
{
double log_rs = log(rs);
vxc[i] = log_rs * (A + t0 * rs) + t1 + t2 * rs;
exc[i] = log_rs * (A + C * rs) + B + D * rs;
} else {
double rs_05 = sqrt(rs);
double t6 = 1.0 / (1.0 + b1 * rs_05 + b2 * rs);
vxc[i] = (g1 + t3 * rs_05 + t4 * rs) * t6 * t6;
exc[i] = g1 * t6;
}
}
}
// LDA Perdew-Wang correlation (PW92)
void eval_LDA_exc_vxc_C_PW92(const int npt, const double *rho, double *exc, double *vxc)
{
// PW92 correlation parameters
const double p = 1.0;
const double A = 0.031091;
const double A2 = 0.062182; // A * 2
const double a1 = 0.21370; // alpha1
const double b1 = 7.5957; // beta1
const double b2 = 3.5876; // beta2
const double b3 = 1.6382; // beta3
const double b4 = 0.49294; // beta4
const double c0 = 0.6203504908993999; // (3/(4*pi))^(1/3)
const double t0 = 2.0 * b2;
const double t1 = 3.0 * b3;
const double t2 = 2.0 * (p+1.0) * b4;
#pragma omp simd
for (int i = 0; i < npt; i++)
{
double rho_cbrt = cbrt(rho[i]) + 1e-20;
double rs = c0 / rho_cbrt; // rs = (3/(4*pi*rho))^(1/3)
double rs_05 = sqrt(rs); // rs^0.5
double rs_15 = rs_05 * rs; // rs^1.5
double rs_p = rs; // rs^p, p = 1
double rs_p1 = rs_p * rs; // rs^(p+1)
double G2 = A2 * (b1*rs_05 + b2*rs + b3*rs_15 + b4*rs_p1);
double G1 = log(1.0 + 1.0 / G2);
double vxc0 = A2 * (1.0 + a1*rs);
double vxc1 = -vxc0 * G1;
double vxc2 = -A2 * a1 * G1;
double vxc3 = b1/rs_05 + t0 + t1*rs_05 + t2*rs_p;
exc[i] = vxc1;
vxc[i] = vxc1 - (rs/3.0) * (vxc2 + (vxc0 * (A * vxc3)) / (G2 * (G2+1.0)) );
}
}
// Evaluate LDA XC functional E_xc = \int G(rho(r)) dr
void eval_LDA_exc_vxc(const int fid, const int npt, const double *rho, double *exc, double *vxc)
{
switch (fid)
{
case LDA_X: eval_LDA_exc_vxc_X (npt, rho, exc, vxc); break;
case LDA_C_XA: eval_LDA_exc_vxc_C_XA (npt, rho, exc, vxc); break;
case LDA_C_PZ: eval_LDA_exc_vxc_C_PZ81(npt, rho, exc, vxc); break;
case LDA_C_PW: eval_LDA_exc_vxc_C_PW92(npt, rho, exc, vxc); break;
}
}
// ========================= GGA functionals ========================= //
// Input parameters:
// npt : Total number of points
// rho : Size npt, electron density at each point
// sigma : Size npt, contracted gradient of rho
// Output parameters:
// exc : Size npt, = G / rho
// vrho : Size npt, = \frac{\part G}{\part rho}
// vsigma : Size npt, = \frac{\part G}{\part sigma}
// Perdew, Burke & Ernzerhof exchange
// Based on Libxc implementation, manually optimized
static void eval_GGA_exc_vxc_X_PBE(
const int npt, const double *rho, const double *sigma,
double *exc, double *vrho, double *vsigma
)
{
const double M_CBRT2 = 1.25992104989487316476721060727;
const double M_CBRT3 = 1.44224957030740838232163831078;
const double M_CBRT4 = 1.58740105196819947475170563927;
const double M_CBRT6 = 1.81712059283213965889121175632;
const double kappa = 0.8040;
const double mu = 0.2195149727645171; // mu = beta*pi^2/3
const double PI_N1_3 = 0.68278406325529568146702083315; // cbrt(1.0 / M_PI)
double r24 = 1.0 / 24.0;
double t6 = M_CBRT4 * M_CBRT4;
double t9 = M_CBRT2 * M_CBRT2;
double t7 = M_CBRT3 * PI_N1_3 * t6 * t9;
double t15 = cbrt(M_PI * M_PI);
double t17 = M_CBRT6 / (t15 * t15);
double t18 = mu * t17;
double t19 = t9 * t18 * r24;
double t41 = PI_N1_3 * M_CBRT2 * M_CBRT3 * t6;
double t43 = kappa * kappa;
t18 *= 0.015625;
#pragma omp simd
for (int i = 0; i < npt; i++)
{
double rho_1_3 = cbrt(rho[i]);
double rho_n1_3 = 1.0 / rho_1_3;
double rho_n2_3 = rho_n1_3 * rho_n1_3;
double inv_rho = rho_n2_3 * rho_n1_3;
double inv_rho2 = inv_rho * inv_rho;
double t27 = 1.0 / (kappa + sigma[i] * rho_n2_3 * inv_rho2 * t19);
double t34 = -0.25 * rho_1_3 * t7 * (1.0 + kappa - t27 * t43);
double t46 = t27 * t27 * t43;
double t50 = sigma[i] * mu * t17 * t46;
exc[i] = 0.75 * t34;
vrho[i] = t34 + rho_n1_3 * inv_rho2 * t41 * t50 * r24;
vsigma[i] = -rho_n1_3 * inv_rho * t18 * t41 * t46;
if (rho[i] < 1e-12)
{
exc[i] = 0.0;
vrho[i] = 0.0;
vsigma[i] = 0.0;
}
}
}
// Becke 88 exchange
// Based on Libxc implementation, manually optimized
static void eval_GGA_exc_vxc_X_B88(
const int npt, const double *rho, const double *sigma,
double *exc, double *vrho, double *vsigma
)
{
const double M_CBRT2 = 1.25992104989487316476721060727;
const double M_CBRT3 = 1.44224957030740838232163831078;
const double M_CBRT4 = 1.58740105196819947475170563927;
const double beta = 0.0042;
const double gamma = 6.0;
const double PI_N1_3 = 0.68278406325529568146702083315; // cbrt(1.0 / M_PI)
double t6 = M_CBRT4 * M_CBRT4;
double t7 = M_CBRT3 * PI_N1_3 * t6;
double t9 = M_CBRT2 * M_CBRT2;
double t13 = beta * M_CBRT3 * M_CBRT3;
double t14 = 1.0 / PI_N1_3;
double t16 = t13 * t14 * M_CBRT4;
double t22 = gamma * beta;
double t46 = t6 * t9;
double t81 = M_CBRT4 * t9;
double d2o9 = 2.0 / 9.0;
#pragma omp simd
for (int i = 0; i < npt; i++)
{
double rho_1_3 = cbrt(rho[i]);
double rho_n1_3 = 1.0 / rho_1_3;
double rho_n2_3 = rho_n1_3 * rho_n1_3;
double inv_rho = rho_n2_3 * rho_n1_3;
double inv_rho2 = inv_rho * inv_rho;
double t17 = sigma[i] * t9;
double t18 = t16 * t17;
double t21 = inv_rho2 * rho_n2_3;
double t23 = sqrt(sigma[i]);
double t24 = t22 * t23;
double t26 = rho_n2_3 * rho_n2_3;
double t29 = t23 * M_CBRT2 * t26;
double t30 = log(t23 * M_CBRT2 * t26 + sqrt(t29 * t29 + 1.0));
double t31 = M_CBRT2 * t26 * t30;
double t34 = 1.0 / (1.0 + t24 * t31);
double t35 = t21 * t34;
double t39 = 1.0 + d2o9 * t18 * t35;
double t41 = -0.25 * t7 * t9 * rho_1_3 * t39;
double t45 = -0.1875 * rho_1_3 * rho[i] * M_CBRT3 * PI_N1_3;
double t49 = rho_n2_3 * inv_rho * inv_rho2;
double t56 = t35 * t34;
double t67 = t9 / sqrt(1.0 + t17 * t21);
double t68 = t22 * t67;
double t71 = -1.33333333333333 * (M_CBRT2 * rho_n1_3 * inv_rho2 * t24 * t30 + sigma[i] * t49 * t68);
double t76 = t18 * (-0.59259259259259 * t49 * t34 - d2o9 * t56 * t71);
double t85 = t22 / t23;
double t91 = 0.5 * (t21 * t68 + t85 * t31);
double t97 = d2o9 * t46 * (-t18 * t56 * t91 + t13 * t14 * t35 * t81);
exc[i] = 0.75 * t41;
vrho[i] = t41 + t45 * t46 * t76;
vsigma[i] = t45 * t97;
if (rho[i] < 1e-25)
{
exc[i] = 0.0;
vrho[i] = 0.0;
vsigma[i] = 0.0;
}
}
}
// Perdew, Burke & Ernzerhof correlation
// Based on Libxc implementation, manually optimized
static void eval_GGA_exc_vxc_C_PBE(
const int npt, const double *rho, const double *sigma,
double *exc, double *vrho, double *vsigma
)
{
const double M_CBRT2 = 1.25992104989487316476721060727;
const double M_CBRT3 = 1.44224957030740838232163831078;
const double M_CBRT4 = 1.58740105196819947475170563927;
const double beta = 0.06672455060314922;
const double gamma = 0.031090690869654895034;
const double BB = 1.0;
const double PI_N1_3 = 0.68278406325529568146702083315; // cbrt(1.0 / M_PI)
double t4 = M_CBRT3 * PI_N1_3;
double t6 = M_CBRT4 * M_CBRT4;
double t18 = M_CBRT3 * M_CBRT3;
double t19 = PI_N1_3 * PI_N1_3;
double t20 = t18 * t19 * M_CBRT4;
double t41 = M_CBRT2 * t18 / PI_N1_3 * M_CBRT4;
double t44 = BB * beta;
double t45 = 1.0 / gamma;
double t46 = t44 * t45;
double t58 = M_CBRT2 * M_CBRT2;
double t60 = 1.0 / t19;
double t64 = t41 / 96.0;
double t122 = t58 * M_CBRT3;
double t124 = t4 * t6;
double t177 = beta * beta;
double t180 = 1.0 / (gamma * gamma);
#pragma omp simd
for (int i = 0; i < npt; i++)
{
double rho_n1_3 = 1.0 / cbrt(rho[i]);
double rho_n2_3 = rho_n1_3 * rho_n1_3;
double inv_rho = rho_n2_3 * rho_n1_3;
double rho_n4_3 = rho_n1_3 * inv_rho;
double inv_rho2 = inv_rho * inv_rho;
double rho_n7_3 = rho_n1_3 * inv_rho2;
double inv_rho3 = inv_rho2 * inv_rho;
double t7 = t6 * rho_n4_3;
double t10 = t124 * rho_n1_3;
double t12 = 1.0 + 0.053425 * t10;
double t13 = sqrt(t10);
double t26 = 3.79785 * t13 +
0.8969 * t10 +
0.204775 * t10 * t13 +
0.123235 * t20 * rho_n2_3;
double t27 = 1.0 / t26;
double t29 = 1.0 + 16.081979498692535067 * t27;
double t30 = log(t29);
double t31 = t12 * t30;
double t32 = 0.0621814 * t31;
double t48 = exp(0.0621814 * t31 * t45);
double t50 = 1.0 / (t48 - 1.0);
double t51 = t46 * t50;
double t52 = sigma[i] * sigma[i];
double t54 = t51 * t52;
double t57 = rho_n7_3 * rho_n7_3;
double t62 = M_CBRT3 * t6 * t60;
double t63 = t57 * t58 * t62 * 6.510416666666666e-04;
double t66 = sigma[i] * rho_n7_3 * t64 + t54 * t63 * 0.5;
double t67 = beta * t66;
double t68 = beta * t45;
double t69 = t68 * t50;
double t71 = 1.0 / (t69 * t66 + 1.0);
double t73 = t45 * t71;
double t75 = t67 * t73 + 1.0;
double t76 = log(t75);
double t77 = gamma * t76;
exc[i] = t77 - t32;
double t80 = t4 * t7;
double t86 = t12 * t27 * t27;
double t96 = PI_N1_3 * M_CBRT3 * t7;
double t104 = -0.632975 * t96 / t13 - 0.29896666666666666667 * t80 - 0.1023875 * t96 * t13 - 0.082156666666666666667 * t20 * rho_n2_3 * inv_rho;
double t106 = t104 / t29;
double t132 = -0.0011073470983333333333 * rho_n4_3 * t30 * t45 * t124 - t45 * t86 * t106;
double t118 = t50 * t50 * t132;
double t145 = -(7.0/288.0) * sigma[i] * rho_n1_3 * inv_rho3 * t41
-t6 * t46 * t48 * t52 * t57 * t60 * t118 * t122 / 3072.0
-(7.0/4608.0) * rho_n2_3 * inv_rho2 * inv_rho3 * t54 * t58 * t62;
double t149 = t71 * t71;
double t157 = t69 * t145 - t48 * t66 * t68 * t118;
double t160 = beta * t73 * t145 - t67 * t45 * t149 * t157;
double t162 = 1.0 / t75;
vrho[i] = t77 - t32 + rho[i] * (0.0011073470983333333333 * t30 * t80 + t86 * t106 + gamma * t160 * t162);
double t174 = rho_n7_3 * t64 + sigma[i] * t51 * t63;
double t185 = t174 * (beta * t73 - t50 * t66 * t149 * t177 * t180);
vsigma[i] = rho[i] * gamma * t185 * t162;
if (rho[i] < 1e-12)
{
exc[i] = 0.0;
vrho[i] = 0.0;
vsigma[i] = 0.0;
}
}
}
// Lee, Yang & Parr correlation
// Based on Libxc implementation, manually optimized
static void eval_GGA_exc_vxc_C_LYP(
const int npt, const double *rho, const double *sigma,
double *exc, double *vrho, double *vsigma
)
{
const double M_CBRT3 = 1.44224957030740838232163831078;
const double A = 0.04918;
const double B = 0.132;
const double c = 0.2533;
const double d = 0.349;
double t55 = B * c;
double t28 = M_PI * M_PI;
double t29 = cbrt(t28);
double t40 = M_CBRT3 * t29;
double t72 = d * d;
double d1o3 = 1.0 / 3.0;
double d5o24 = 5.0 / 24.0;
double d1o18 = 1.0 / 18.0;
double d1o54 = 1.0 / 54.0;
double d1o144 = 1.0 / 144.0;
double t83 = 0.125 - d1o144 * 18.0;
#pragma omp simd
for (int i = 0; i < npt; i++)
{
double rho_1_3 = cbrt(rho[i]);
double rho_n1_3 = 1.0 / rho_1_3;
double rho_n2_3 = rho_n1_3 * rho_n1_3;
double inv_rho = rho_n1_3 * rho_n2_3;
double rho_n4_3 = rho_n1_3 * inv_rho;
double inv_rho2 = inv_rho * inv_rho;
double t11 = 1.0 / (d * rho_n1_3 + 1.0);
double t13 = exp(-c * rho_n1_3);
double t14 = B * t13;
double t18 = rho_n2_3 * inv_rho2;
double t19 = sigma[i] * t18;
double t21 = d * t11 + c;
double t22 = t21 * rho_n1_3;
double t24 = d1o18 * (-0.25 - 1.75 * t22);
double t34 = 2.5 - t22 * d1o18;
double t35 = sigma[i] * t34;
double t38 = t22 - 11.0;
double t39 = sigma[i] * t38;
double t43 = -t19 * (t24 + d5o24) - 0.3 * t40 * t40
+t18 * (0.125 * t35 + d1o144 * t39);
double t47 = rho[i] * A;
double t49 = t11 * t11;
double t57 = t13 * t11;
double t68 = rho_n2_3 * inv_rho * inv_rho2;
double t69 = 8.0 * sigma[i] * t68;
double t78 = t21 * rho_n4_3 - t49 * t72 * rho_n2_3 * inv_rho;
double t79 = 1.75 * d1o54 * t78;
double t82 = sigma[i] * t78 * d1o54;
double t95 = d1o3 * (t24 * t69 - t35 * t68) - t19 * t79
+ t18 * t82 * t83
- d1o54 * t39 * t68 + 1.25 * d1o18 * t69;
double t97 = d * t49;
double t98 = rho_n4_3 * d1o3 * (-t97 + t43 * (t55 * t57 + t14 * t97))
+ t11 * t14 * t95;
double t107 = t18 * (-t24 + t34 * 0.125 + t38 * d1o144 - d5o24);
exc[i] = A * t11 * (t14 * t43 - 1.0);
vrho[i] = t47 * t98 + exc[i];
vsigma[i] = B * t47 * t57 * t107;
if (rho[i] < 1e-32)
{
exc[i] = 0.0;
vrho[i] = 0.0;
vsigma[i] = 0.0;
}
}
}
// Perdew 86 correlation
// Based on Libxc implementation, manually optimized
static void eval_GGA_exc_vxc_C_P86(
const int npt, const double *rho, const double *sigma,
double *exc, double *vrho, double *vsigma
)
{
const double M_CBRT3 = 1.44224957030740838232163831078;
const double M_CBRT4 = 1.58740105196819947475170563927;
const double PI_N1_3 = 0.68278406325529568146702083315; // cbrt(1.0 / M_PI)
double t4 = M_CBRT3 * PI_N1_3;
double t6 = M_CBRT4 * M_CBRT4;
double t7 = t4 * t6;
double t32 = M_CBRT3 * M_CBRT3;
double t33 = PI_N1_3 * PI_N1_3;
double t34 = M_CBRT4 * t32 * t33;
double c1 = -0.087741666666666666667 * M_CBRT3 * PI_N1_3;
#pragma omp simd
for (int i = 0; i < npt; i++)
{
double rho_1_3 = cbrt(rho[i]);
double rho_n1_3 = 1.0 / rho_1_3;
double rho_n2_3 = rho_n1_3 * rho_n1_3;
double inv_rho = rho_n2_3 * rho_n1_3;
double inv_rho2 = inv_rho * inv_rho;
double t10 = t7 * rho_n1_3;
double t11 = t10 * 0.25;
int t12 = (1.0 <= t11);
double t13 = sqrt(t10);
double t16 = 1.0 / (1.0 + 0.52645 * t13 + 0.08335 * t10);
double t19 = log(t11);
double t24 = -0.1423 * t16;
double t25 = 0.0311 * t19 - 0.048 + t10 * (0.0005 * t19 - 0.0029);
double t26 = t12 ? t24 : t25;
double t29 = rho_n1_3 * inv_rho2;
double t30 = sigma[i] * t29;
double t38 = t34 * rho_n2_3;
double t40 = 0.002568 + 0.0058165 * t10 + 0.184725e-5 * t38;
double t45 = 1.0 / (1.0 + 2.18075 * t10 + 0.118 * t38 + 0.01763993811759021954 * inv_rho);
double t46 = -t40 * t45;
double t48 = 0.001667 - t46;
double t49 = 1.0 / t48;
double t50 = sqrt(sigma[i]);
double t51 = t49 * t50;
double t52 = pow(rho[i], -0.1666666666666667);
double t54 = t52 * inv_rho;
double t55 = t51 * t54;
double t57 = exp(-0.00081290825 * t55);
double t58 = t57 * t48;
double t66 = rho_n1_3 * inv_rho;
double t71 = t7 * t66;
double t73 = c1 / t13 * t6 * t66 - 0.027783333333333333333 * t71;
double t80 = -t16 * t24 * t73;
double t81 = -0.010366666666666666667 * inv_rho - t71 * (0.16666666666666666667e-3 * t19 + 0.0008);
double t82 = t12 ? t80 : t81;
double t83 = inv_rho2 * inv_rho;
double t87 = sigma[i] * rho_n1_3 * t58 * t83;
double t96 = t38 * inv_rho;
double t98 = -0.001938833333333333333 * t71 - 0.12315e-5 * t96;
double t107 = -0.72691666666666666667 * t71 - 0.078666666666666666667 * t96 - 0.017639938117590219540 * inv_rho2;
double t109 = t45 * (t46 * t107 + t98);
double t117 = 0.00081290825 * t49 * t55 * t109 + 0.94839295833333333334e-3 * inv_rho2 * t51 * t52;
double t119 = t30 * t57;
double t120 = t48 * t117 * t119;
double t122 = t109 * t119;
double t132 = 0.000406454125 * t50 * t83 / sqrt(rho[i]) * t57;
exc[i] = t26 + t30 * t58;
vrho[i] = exc[i] + rho[i] * (t82 - 7.0/3.0 * t87 + t120 + t122);
vsigma[i] = rho[i] * (t29 * t57 * t48 - t132);
if (rho[i] < 1e-25)
{
exc[i] = 0.0;
vrho[i] = 0.0;
vsigma[i] = 0.0;
}
}
}
// Evaluate GGA XC functional E_xc = \int G(rho(r)) dr
void eval_GGA_exc_vxc(
const int fid, const int npt, const double *rho, const double *sigma,
double *exc, double *vrho, double *vsigma
)
{
switch (fid)
{
case GGA_X_PBE: eval_GGA_exc_vxc_X_PBE(npt, rho, sigma, exc, vrho, vsigma); break;
case GGA_X_B88: eval_GGA_exc_vxc_X_B88(npt, rho, sigma, exc, vrho, vsigma); break;
case GGA_C_PBE: eval_GGA_exc_vxc_C_PBE(npt, rho, sigma, exc, vrho, vsigma); break;
case GGA_C_LYP: eval_GGA_exc_vxc_C_LYP(npt, rho, sigma, exc, vrho, vsigma); break;
case GGA_C_P86: eval_GGA_exc_vxc_C_P86(npt, rho, sigma, exc, vrho, vsigma); break;
}
}
|
OpenMPClause.h | //===- OpenMPClause.h - Classes for OpenMP clauses --------------*- 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
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This file defines OpenMP AST classes for clauses.
/// There are clauses for executable directives, clauses for declarative
/// directives and clauses which can be used in both kinds of directives.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_OPENMPCLAUSE_H
#define LLVM_CLANG_AST_OPENMPCLAUSE_H
#include "clang/AST/Decl.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtIterator.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/iterator.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Frontend/OpenMP/OMPConstants.h"
#include "llvm/Frontend/OpenMP/OMPContext.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/TrailingObjects.h"
#include <cassert>
#include <cstddef>
#include <iterator>
#include <utility>
namespace clang {
class ASTContext;
//===----------------------------------------------------------------------===//
// AST classes for clauses.
//===----------------------------------------------------------------------===//
/// This is a basic class for representing single OpenMP clause.
class OMPClause {
/// Starting location of the clause (the clause keyword).
SourceLocation StartLoc;
/// Ending location of the clause.
SourceLocation EndLoc;
/// Kind of the clause.
OpenMPClauseKind Kind;
protected:
OMPClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation EndLoc)
: StartLoc(StartLoc), EndLoc(EndLoc), Kind(K) {}
public:
/// Returns the starting location of the clause.
SourceLocation getBeginLoc() const { return StartLoc; }
/// Returns the ending location of the clause.
SourceLocation getEndLoc() const { return EndLoc; }
/// Sets the starting location of the clause.
void setLocStart(SourceLocation Loc) { StartLoc = Loc; }
/// Sets the ending location of the clause.
void setLocEnd(SourceLocation Loc) { EndLoc = Loc; }
/// Returns kind of OpenMP clause (private, shared, reduction, etc.).
OpenMPClauseKind getClauseKind() const { return Kind; }
bool isImplicit() const { return StartLoc.isInvalid(); }
using child_iterator = StmtIterator;
using const_child_iterator = ConstStmtIterator;
using child_range = llvm::iterator_range<child_iterator>;
using const_child_range = llvm::iterator_range<const_child_iterator>;
child_range children();
const_child_range children() const {
auto Children = const_cast<OMPClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
/// Get the iterator range for the expressions used in the clauses. Used
/// expressions include only the children that must be evaluated at the
/// runtime before entering the construct.
child_range used_children();
const_child_range used_children() const {
auto Children = const_cast<OMPClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
static bool classof(const OMPClause *) { return true; }
};
/// Class that handles pre-initialization statement for some clauses, like
/// 'shedule', 'firstprivate' etc.
class OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Pre-initialization statement for the clause.
Stmt *PreInit = nullptr;
/// Region that captures the associated stmt.
OpenMPDirectiveKind CaptureRegion = llvm::omp::OMPD_unknown;
protected:
OMPClauseWithPreInit(const OMPClause *This) {
assert(get(This) && "get is not tuned for pre-init.");
}
/// Set pre-initialization statement for the clause.
void
setPreInitStmt(Stmt *S,
OpenMPDirectiveKind ThisRegion = llvm::omp::OMPD_unknown) {
PreInit = S;
CaptureRegion = ThisRegion;
}
public:
/// Get pre-initialization statement for the clause.
const Stmt *getPreInitStmt() const { return PreInit; }
/// Get pre-initialization statement for the clause.
Stmt *getPreInitStmt() { return PreInit; }
/// Get capture region for the stmt in the clause.
OpenMPDirectiveKind getCaptureRegion() const { return CaptureRegion; }
static OMPClauseWithPreInit *get(OMPClause *C);
static const OMPClauseWithPreInit *get(const OMPClause *C);
};
/// Class that handles post-update expression for some clauses, like
/// 'lastprivate', 'reduction' etc.
class OMPClauseWithPostUpdate : public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Post-update expression for the clause.
Expr *PostUpdate = nullptr;
protected:
OMPClauseWithPostUpdate(const OMPClause *This) : OMPClauseWithPreInit(This) {
assert(get(This) && "get is not tuned for post-update.");
}
/// Set pre-initialization statement for the clause.
void setPostUpdateExpr(Expr *S) { PostUpdate = S; }
public:
/// Get post-update expression for the clause.
const Expr *getPostUpdateExpr() const { return PostUpdate; }
/// Get post-update expression for the clause.
Expr *getPostUpdateExpr() { return PostUpdate; }
static OMPClauseWithPostUpdate *get(OMPClause *C);
static const OMPClauseWithPostUpdate *get(const OMPClause *C);
};
/// This structure contains most locations needed for by an OMPVarListClause.
struct OMPVarListLocTy {
/// Starting location of the clause (the clause keyword).
SourceLocation StartLoc;
/// Location of '('.
SourceLocation LParenLoc;
/// Ending location of the clause.
SourceLocation EndLoc;
OMPVarListLocTy() = default;
OMPVarListLocTy(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: StartLoc(StartLoc), LParenLoc(LParenLoc), EndLoc(EndLoc) {}
};
/// This represents clauses with the list of variables like 'private',
/// 'firstprivate', 'copyin', 'shared', or 'reduction' clauses in the
/// '#pragma omp ...' directives.
template <class T> class OMPVarListClause : public OMPClause {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Number of variables in the list.
unsigned NumVars;
protected:
/// Build a clause with \a N variables
///
/// \param K Kind of the clause.
/// \param StartLoc Starting location of the clause (the clause keyword).
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPVarListClause(OpenMPClauseKind K, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N)
: OMPClause(K, StartLoc, EndLoc), LParenLoc(LParenLoc), NumVars(N) {}
/// Fetches list of variables associated with this clause.
MutableArrayRef<Expr *> getVarRefs() {
return MutableArrayRef<Expr *>(
static_cast<T *>(this)->template getTrailingObjects<Expr *>(), NumVars);
}
/// Sets the list of variables for this clause.
void setVarRefs(ArrayRef<Expr *> VL) {
assert(VL.size() == NumVars &&
"Number of variables is not the same as the preallocated buffer");
std::copy(VL.begin(), VL.end(),
static_cast<T *>(this)->template getTrailingObjects<Expr *>());
}
public:
using varlist_iterator = MutableArrayRef<Expr *>::iterator;
using varlist_const_iterator = ArrayRef<const Expr *>::iterator;
using varlist_range = llvm::iterator_range<varlist_iterator>;
using varlist_const_range = llvm::iterator_range<varlist_const_iterator>;
unsigned varlist_size() const { return NumVars; }
bool varlist_empty() const { return NumVars == 0; }
varlist_range varlists() {
return varlist_range(varlist_begin(), varlist_end());
}
varlist_const_range varlists() const {
return varlist_const_range(varlist_begin(), varlist_end());
}
varlist_iterator varlist_begin() { return getVarRefs().begin(); }
varlist_iterator varlist_end() { return getVarRefs().end(); }
varlist_const_iterator varlist_begin() const { return getVarRefs().begin(); }
varlist_const_iterator varlist_end() const { return getVarRefs().end(); }
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Fetches list of all variables in the clause.
ArrayRef<const Expr *> getVarRefs() const {
return llvm::makeArrayRef(
static_cast<const T *>(this)->template getTrailingObjects<Expr *>(),
NumVars);
}
};
/// This represents 'allocator' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp allocate(a) allocator(omp_default_mem_alloc)
/// \endcode
/// In this example directive '#pragma omp allocate' has simple 'allocator'
/// clause with the allocator 'omp_default_mem_alloc'.
class OMPAllocatorClause : public OMPClause {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Expression with the allocator.
Stmt *Allocator = nullptr;
/// Set allocator.
void setAllocator(Expr *A) { Allocator = A; }
public:
/// Build 'allocator' clause with the given allocator.
///
/// \param A Allocator.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPAllocatorClause(Expr *A, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_allocator, StartLoc, EndLoc),
LParenLoc(LParenLoc), Allocator(A) {}
/// Build an empty clause.
OMPAllocatorClause()
: OMPClause(llvm::omp::OMPC_allocator, SourceLocation(),
SourceLocation()) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Returns allocator.
Expr *getAllocator() const { return cast_or_null<Expr>(Allocator); }
child_range children() { return child_range(&Allocator, &Allocator + 1); }
const_child_range children() const {
return const_child_range(&Allocator, &Allocator + 1);
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_allocator;
}
};
/// This represents clause 'allocate' in the '#pragma omp ...' directives.
///
/// \code
/// #pragma omp parallel private(a) allocate(omp_default_mem_alloc :a)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'private'
/// and clause 'allocate' for the variable 'a'.
class OMPAllocateClause final
: public OMPVarListClause<OMPAllocateClause>,
private llvm::TrailingObjects<OMPAllocateClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Allocator specified in the clause, or 'nullptr' if the default one is
/// used.
Expr *Allocator = nullptr;
/// Position of the ':' delimiter in the clause;
SourceLocation ColonLoc;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param Allocator Allocator expression.
/// \param ColonLoc Location of ':' delimiter.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPAllocateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
Expr *Allocator, SourceLocation ColonLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPAllocateClause>(llvm::omp::OMPC_allocate, StartLoc,
LParenLoc, EndLoc, N),
Allocator(Allocator), ColonLoc(ColonLoc) {}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPAllocateClause(unsigned N)
: OMPVarListClause<OMPAllocateClause>(llvm::omp::OMPC_allocate,
SourceLocation(), SourceLocation(),
SourceLocation(), N) {}
/// Sets location of ':' symbol in clause.
void setColonLoc(SourceLocation CL) { ColonLoc = CL; }
void setAllocator(Expr *A) { Allocator = A; }
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param Allocator Allocator expression.
/// \param ColonLoc Location of ':' delimiter.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
static OMPAllocateClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc, Expr *Allocator,
SourceLocation ColonLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL);
/// Returns the allocator expression or nullptr, if no allocator is specified.
Expr *getAllocator() const { return Allocator; }
/// Returns the location of the ':' delimiter.
SourceLocation getColonLoc() const { return ColonLoc; }
/// Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPAllocateClause *CreateEmpty(const ASTContext &C, unsigned N);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPAllocateClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_allocate;
}
};
/// This represents 'if' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp parallel if(parallel:a > 5)
/// \endcode
/// In this example directive '#pragma omp parallel' has simple 'if' clause with
/// condition 'a > 5' and directive name modifier 'parallel'.
class OMPIfClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Condition of the 'if' clause.
Stmt *Condition = nullptr;
/// Location of ':' (if any).
SourceLocation ColonLoc;
/// Directive name modifier for the clause.
OpenMPDirectiveKind NameModifier = llvm::omp::OMPD_unknown;
/// Name modifier location.
SourceLocation NameModifierLoc;
/// Set condition.
void setCondition(Expr *Cond) { Condition = Cond; }
/// Set directive name modifier for the clause.
void setNameModifier(OpenMPDirectiveKind NM) { NameModifier = NM; }
/// Set location of directive name modifier for the clause.
void setNameModifierLoc(SourceLocation Loc) { NameModifierLoc = Loc; }
/// Set location of ':'.
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
public:
/// Build 'if' clause with condition \a Cond.
///
/// \param NameModifier [OpenMP 4.1] Directive name modifier of clause.
/// \param Cond Condition of the clause.
/// \param HelperCond Helper condition for the clause.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param NameModifierLoc Location of directive name modifier.
/// \param ColonLoc [OpenMP 4.1] Location of ':'.
/// \param EndLoc Ending location of the clause.
OMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Cond, Stmt *HelperCond,
OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation NameModifierLoc,
SourceLocation ColonLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_if, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Condition(Cond),
ColonLoc(ColonLoc), NameModifier(NameModifier),
NameModifierLoc(NameModifierLoc) {
setPreInitStmt(HelperCond, CaptureRegion);
}
/// Build an empty clause.
OMPIfClause()
: OMPClause(llvm::omp::OMPC_if, SourceLocation(), SourceLocation()),
OMPClauseWithPreInit(this) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Return the location of ':'.
SourceLocation getColonLoc() const { return ColonLoc; }
/// Returns condition.
Expr *getCondition() const { return cast_or_null<Expr>(Condition); }
/// Return directive name modifier associated with the clause.
OpenMPDirectiveKind getNameModifier() const { return NameModifier; }
/// Return the location of directive name modifier.
SourceLocation getNameModifierLoc() const { return NameModifierLoc; }
child_range children() { return child_range(&Condition, &Condition + 1); }
const_child_range children() const {
return const_child_range(&Condition, &Condition + 1);
}
child_range used_children();
const_child_range used_children() const {
auto Children = const_cast<OMPIfClause *>(this)->used_children();
return const_child_range(Children.begin(), Children.end());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_if;
}
};
/// This represents 'final' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp task final(a > 5)
/// \endcode
/// In this example directive '#pragma omp task' has simple 'final'
/// clause with condition 'a > 5'.
class OMPFinalClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Condition of the 'if' clause.
Stmt *Condition = nullptr;
/// Set condition.
void setCondition(Expr *Cond) { Condition = Cond; }
public:
/// Build 'final' clause with condition \a Cond.
///
/// \param Cond Condition of the clause.
/// \param HelperCond Helper condition for the construct.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPFinalClause(Expr *Cond, Stmt *HelperCond,
OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_final, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Condition(Cond) {
setPreInitStmt(HelperCond, CaptureRegion);
}
/// Build an empty clause.
OMPFinalClause()
: OMPClause(llvm::omp::OMPC_final, SourceLocation(), SourceLocation()),
OMPClauseWithPreInit(this) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Returns condition.
Expr *getCondition() const { return cast_or_null<Expr>(Condition); }
child_range children() { return child_range(&Condition, &Condition + 1); }
const_child_range children() const {
return const_child_range(&Condition, &Condition + 1);
}
child_range used_children();
const_child_range used_children() const {
auto Children = const_cast<OMPFinalClause *>(this)->used_children();
return const_child_range(Children.begin(), Children.end());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_final;
}
};
/// This represents 'num_threads' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp parallel num_threads(6)
/// \endcode
/// In this example directive '#pragma omp parallel' has simple 'num_threads'
/// clause with number of threads '6'.
class OMPNumThreadsClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Condition of the 'num_threads' clause.
Stmt *NumThreads = nullptr;
/// Set condition.
void setNumThreads(Expr *NThreads) { NumThreads = NThreads; }
public:
/// Build 'num_threads' clause with condition \a NumThreads.
///
/// \param NumThreads Number of threads for the construct.
/// \param HelperNumThreads Helper Number of threads for the construct.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPNumThreadsClause(Expr *NumThreads, Stmt *HelperNumThreads,
OpenMPDirectiveKind CaptureRegion,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_num_threads, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc),
NumThreads(NumThreads) {
setPreInitStmt(HelperNumThreads, CaptureRegion);
}
/// Build an empty clause.
OMPNumThreadsClause()
: OMPClause(llvm::omp::OMPC_num_threads, SourceLocation(),
SourceLocation()),
OMPClauseWithPreInit(this) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Returns number of threads.
Expr *getNumThreads() const { return cast_or_null<Expr>(NumThreads); }
child_range children() { return child_range(&NumThreads, &NumThreads + 1); }
const_child_range children() const {
return const_child_range(&NumThreads, &NumThreads + 1);
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_num_threads;
}
};
/// This represents 'safelen' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp simd safelen(4)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'safelen'
/// with single expression '4'.
/// If the safelen clause is used then no two iterations executed
/// concurrently with SIMD instructions can have a greater distance
/// in the logical iteration space than its value. The parameter of
/// the safelen clause must be a constant positive integer expression.
class OMPSafelenClause : public OMPClause {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Safe iteration space distance.
Stmt *Safelen = nullptr;
/// Set safelen.
void setSafelen(Expr *Len) { Safelen = Len; }
public:
/// Build 'safelen' clause.
///
/// \param Len Expression associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPSafelenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_safelen, StartLoc, EndLoc),
LParenLoc(LParenLoc), Safelen(Len) {}
/// Build an empty clause.
explicit OMPSafelenClause()
: OMPClause(llvm::omp::OMPC_safelen, SourceLocation(), SourceLocation()) {
}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Return safe iteration space distance.
Expr *getSafelen() const { return cast_or_null<Expr>(Safelen); }
child_range children() { return child_range(&Safelen, &Safelen + 1); }
const_child_range children() const {
return const_child_range(&Safelen, &Safelen + 1);
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_safelen;
}
};
/// This represents 'simdlen' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp simd simdlen(4)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'simdlen'
/// with single expression '4'.
/// If the 'simdlen' clause is used then it specifies the preferred number of
/// iterations to be executed concurrently. The parameter of the 'simdlen'
/// clause must be a constant positive integer expression.
class OMPSimdlenClause : public OMPClause {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Safe iteration space distance.
Stmt *Simdlen = nullptr;
/// Set simdlen.
void setSimdlen(Expr *Len) { Simdlen = Len; }
public:
/// Build 'simdlen' clause.
///
/// \param Len Expression associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPSimdlenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_simdlen, StartLoc, EndLoc),
LParenLoc(LParenLoc), Simdlen(Len) {}
/// Build an empty clause.
explicit OMPSimdlenClause()
: OMPClause(llvm::omp::OMPC_simdlen, SourceLocation(), SourceLocation()) {
}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Return safe iteration space distance.
Expr *getSimdlen() const { return cast_or_null<Expr>(Simdlen); }
child_range children() { return child_range(&Simdlen, &Simdlen + 1); }
const_child_range children() const {
return const_child_range(&Simdlen, &Simdlen + 1);
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_simdlen;
}
};
/// This represents 'collapse' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp simd collapse(3)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'collapse'
/// with single expression '3'.
/// The parameter must be a constant positive integer expression, it specifies
/// the number of nested loops that should be collapsed into a single iteration
/// space.
class OMPCollapseClause : public OMPClause {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Number of for-loops.
Stmt *NumForLoops = nullptr;
/// Set the number of associated for-loops.
void setNumForLoops(Expr *Num) { NumForLoops = Num; }
public:
/// Build 'collapse' clause.
///
/// \param Num Expression associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPCollapseClause(Expr *Num, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_collapse, StartLoc, EndLoc),
LParenLoc(LParenLoc), NumForLoops(Num) {}
/// Build an empty clause.
explicit OMPCollapseClause()
: OMPClause(llvm::omp::OMPC_collapse, SourceLocation(),
SourceLocation()) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Return the number of associated for-loops.
Expr *getNumForLoops() const { return cast_or_null<Expr>(NumForLoops); }
child_range children() { return child_range(&NumForLoops, &NumForLoops + 1); }
const_child_range children() const {
return const_child_range(&NumForLoops, &NumForLoops + 1);
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_collapse;
}
};
/// This represents 'default' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp parallel default(shared)
/// \endcode
/// In this example directive '#pragma omp parallel' has simple 'default'
/// clause with kind 'shared'.
class OMPDefaultClause : public OMPClause {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// A kind of the 'default' clause.
llvm::omp::DefaultKind Kind = llvm::omp::OMP_DEFAULT_unknown;
/// Start location of the kind in source code.
SourceLocation KindKwLoc;
/// Set kind of the clauses.
///
/// \param K Argument of clause.
void setDefaultKind(llvm::omp::DefaultKind K) { Kind = K; }
/// Set argument location.
///
/// \param KLoc Argument location.
void setDefaultKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; }
public:
/// Build 'default' clause with argument \a A ('none' or 'shared').
///
/// \param A Argument of the clause ('none' or 'shared').
/// \param ALoc Starting location of the argument.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPDefaultClause(llvm::omp::DefaultKind A, SourceLocation ALoc,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_default, StartLoc, EndLoc),
LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {}
/// Build an empty clause.
OMPDefaultClause()
: OMPClause(llvm::omp::OMPC_default, SourceLocation(), SourceLocation()) {
}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Returns kind of the clause.
llvm::omp::DefaultKind getDefaultKind() const { return Kind; }
/// Returns location of clause kind.
SourceLocation getDefaultKindKwLoc() const { return KindKwLoc; }
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_default;
}
};
/// This represents 'proc_bind' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp parallel proc_bind(master)
/// \endcode
/// In this example directive '#pragma omp parallel' has simple 'proc_bind'
/// clause with kind 'master'.
class OMPProcBindClause : public OMPClause {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// A kind of the 'proc_bind' clause.
llvm::omp::ProcBindKind Kind = llvm::omp::OMP_PROC_BIND_unknown;
/// Start location of the kind in source code.
SourceLocation KindKwLoc;
/// Set kind of the clause.
///
/// \param K Kind of clause.
void setProcBindKind(llvm::omp::ProcBindKind K) { Kind = K; }
/// Set clause kind location.
///
/// \param KLoc Kind location.
void setProcBindKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; }
public:
/// Build 'proc_bind' clause with argument \a A ('master', 'close' or
/// 'spread').
///
/// \param A Argument of the clause ('master', 'close' or 'spread').
/// \param ALoc Starting location of the argument.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPProcBindClause(llvm::omp::ProcBindKind A, SourceLocation ALoc,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_proc_bind, StartLoc, EndLoc),
LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {}
/// Build an empty clause.
OMPProcBindClause()
: OMPClause(llvm::omp::OMPC_proc_bind, SourceLocation(),
SourceLocation()) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Returns kind of the clause.
llvm::omp::ProcBindKind getProcBindKind() const { return Kind; }
/// Returns location of clause kind.
SourceLocation getProcBindKindKwLoc() const { return KindKwLoc; }
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_proc_bind;
}
};
/// This represents 'unified_address' clause in the '#pragma omp requires'
/// directive.
///
/// \code
/// #pragma omp requires unified_address
/// \endcode
/// In this example directive '#pragma omp requires' has 'unified_address'
/// clause.
class OMPUnifiedAddressClause final : public OMPClause {
public:
friend class OMPClauseReader;
/// Build 'unified_address' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_unified_address, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPUnifiedAddressClause()
: OMPClause(llvm::omp::OMPC_unified_address, SourceLocation(),
SourceLocation()) {}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_unified_address;
}
};
/// This represents 'unified_shared_memory' clause in the '#pragma omp requires'
/// directive.
///
/// \code
/// #pragma omp requires unified_shared_memory
/// \endcode
/// In this example directive '#pragma omp requires' has 'unified_shared_memory'
/// clause.
class OMPUnifiedSharedMemoryClause final : public OMPClause {
public:
friend class OMPClauseReader;
/// Build 'unified_shared_memory' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_unified_shared_memory, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPUnifiedSharedMemoryClause()
: OMPClause(llvm::omp::OMPC_unified_shared_memory, SourceLocation(),
SourceLocation()) {}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_unified_shared_memory;
}
};
/// This represents 'reverse_offload' clause in the '#pragma omp requires'
/// directive.
///
/// \code
/// #pragma omp requires reverse_offload
/// \endcode
/// In this example directive '#pragma omp requires' has 'reverse_offload'
/// clause.
class OMPReverseOffloadClause final : public OMPClause {
public:
friend class OMPClauseReader;
/// Build 'reverse_offload' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_reverse_offload, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPReverseOffloadClause()
: OMPClause(llvm::omp::OMPC_reverse_offload, SourceLocation(),
SourceLocation()) {}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_reverse_offload;
}
};
/// This represents 'dynamic_allocators' clause in the '#pragma omp requires'
/// directive.
///
/// \code
/// #pragma omp requires dynamic_allocators
/// \endcode
/// In this example directive '#pragma omp requires' has 'dynamic_allocators'
/// clause.
class OMPDynamicAllocatorsClause final : public OMPClause {
public:
friend class OMPClauseReader;
/// Build 'dynamic_allocators' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_dynamic_allocators, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPDynamicAllocatorsClause()
: OMPClause(llvm::omp::OMPC_dynamic_allocators, SourceLocation(),
SourceLocation()) {}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_dynamic_allocators;
}
};
/// This represents 'atomic_default_mem_order' clause in the '#pragma omp
/// requires' directive.
///
/// \code
/// #pragma omp requires atomic_default_mem_order(seq_cst)
/// \endcode
/// In this example directive '#pragma omp requires' has simple
/// atomic_default_mem_order' clause with kind 'seq_cst'.
class OMPAtomicDefaultMemOrderClause final : public OMPClause {
friend class OMPClauseReader;
/// Location of '('
SourceLocation LParenLoc;
/// A kind of the 'atomic_default_mem_order' clause.
OpenMPAtomicDefaultMemOrderClauseKind Kind =
OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown;
/// Start location of the kind in source code.
SourceLocation KindKwLoc;
/// Set kind of the clause.
///
/// \param K Kind of clause.
void setAtomicDefaultMemOrderKind(OpenMPAtomicDefaultMemOrderClauseKind K) {
Kind = K;
}
/// Set clause kind location.
///
/// \param KLoc Kind location.
void setAtomicDefaultMemOrderKindKwLoc(SourceLocation KLoc) {
KindKwLoc = KLoc;
}
public:
/// Build 'atomic_default_mem_order' clause with argument \a A ('seq_cst',
/// 'acq_rel' or 'relaxed').
///
/// \param A Argument of the clause ('seq_cst', 'acq_rel' or 'relaxed').
/// \param ALoc Starting location of the argument.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPAtomicDefaultMemOrderClause(OpenMPAtomicDefaultMemOrderClauseKind A,
SourceLocation ALoc, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_atomic_default_mem_order, StartLoc, EndLoc),
LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {}
/// Build an empty clause.
OMPAtomicDefaultMemOrderClause()
: OMPClause(llvm::omp::OMPC_atomic_default_mem_order, SourceLocation(),
SourceLocation()) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the locaiton of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Returns kind of the clause.
OpenMPAtomicDefaultMemOrderClauseKind getAtomicDefaultMemOrderKind() const {
return Kind;
}
/// Returns location of clause kind.
SourceLocation getAtomicDefaultMemOrderKindKwLoc() const { return KindKwLoc; }
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_atomic_default_mem_order;
}
};
/// This represents 'schedule' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp for schedule(static, 3)
/// \endcode
/// In this example directive '#pragma omp for' has 'schedule' clause with
/// arguments 'static' and '3'.
class OMPScheduleClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// A kind of the 'schedule' clause.
OpenMPScheduleClauseKind Kind = OMPC_SCHEDULE_unknown;
/// Modifiers for 'schedule' clause.
enum {FIRST, SECOND, NUM_MODIFIERS};
OpenMPScheduleClauseModifier Modifiers[NUM_MODIFIERS];
/// Locations of modifiers.
SourceLocation ModifiersLoc[NUM_MODIFIERS];
/// Start location of the schedule ind in source code.
SourceLocation KindLoc;
/// Location of ',' (if any).
SourceLocation CommaLoc;
/// Chunk size.
Expr *ChunkSize = nullptr;
/// Set schedule kind.
///
/// \param K Schedule kind.
void setScheduleKind(OpenMPScheduleClauseKind K) { Kind = K; }
/// Set the first schedule modifier.
///
/// \param M Schedule modifier.
void setFirstScheduleModifier(OpenMPScheduleClauseModifier M) {
Modifiers[FIRST] = M;
}
/// Set the second schedule modifier.
///
/// \param M Schedule modifier.
void setSecondScheduleModifier(OpenMPScheduleClauseModifier M) {
Modifiers[SECOND] = M;
}
/// Set location of the first schedule modifier.
void setFirstScheduleModifierLoc(SourceLocation Loc) {
ModifiersLoc[FIRST] = Loc;
}
/// Set location of the second schedule modifier.
void setSecondScheduleModifierLoc(SourceLocation Loc) {
ModifiersLoc[SECOND] = Loc;
}
/// Set schedule modifier location.
///
/// \param M Schedule modifier location.
void setScheduleModifer(OpenMPScheduleClauseModifier M) {
if (Modifiers[FIRST] == OMPC_SCHEDULE_MODIFIER_unknown)
Modifiers[FIRST] = M;
else {
assert(Modifiers[SECOND] == OMPC_SCHEDULE_MODIFIER_unknown);
Modifiers[SECOND] = M;
}
}
/// Sets the location of '('.
///
/// \param Loc Location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Set schedule kind start location.
///
/// \param KLoc Schedule kind location.
void setScheduleKindLoc(SourceLocation KLoc) { KindLoc = KLoc; }
/// Set location of ','.
///
/// \param Loc Location of ','.
void setCommaLoc(SourceLocation Loc) { CommaLoc = Loc; }
/// Set chunk size.
///
/// \param E Chunk size.
void setChunkSize(Expr *E) { ChunkSize = E; }
public:
/// Build 'schedule' clause with schedule kind \a Kind and chunk size
/// expression \a ChunkSize.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param KLoc Starting location of the argument.
/// \param CommaLoc Location of ','.
/// \param EndLoc Ending location of the clause.
/// \param Kind Schedule kind.
/// \param ChunkSize Chunk size.
/// \param HelperChunkSize Helper chunk size for combined directives.
/// \param M1 The first modifier applied to 'schedule' clause.
/// \param M1Loc Location of the first modifier
/// \param M2 The second modifier applied to 'schedule' clause.
/// \param M2Loc Location of the second modifier
OMPScheduleClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation KLoc, SourceLocation CommaLoc,
SourceLocation EndLoc, OpenMPScheduleClauseKind Kind,
Expr *ChunkSize, Stmt *HelperChunkSize,
OpenMPScheduleClauseModifier M1, SourceLocation M1Loc,
OpenMPScheduleClauseModifier M2, SourceLocation M2Loc)
: OMPClause(llvm::omp::OMPC_schedule, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Kind(Kind),
KindLoc(KLoc), CommaLoc(CommaLoc), ChunkSize(ChunkSize) {
setPreInitStmt(HelperChunkSize);
Modifiers[FIRST] = M1;
Modifiers[SECOND] = M2;
ModifiersLoc[FIRST] = M1Loc;
ModifiersLoc[SECOND] = M2Loc;
}
/// Build an empty clause.
explicit OMPScheduleClause()
: OMPClause(llvm::omp::OMPC_schedule, SourceLocation(), SourceLocation()),
OMPClauseWithPreInit(this) {
Modifiers[FIRST] = OMPC_SCHEDULE_MODIFIER_unknown;
Modifiers[SECOND] = OMPC_SCHEDULE_MODIFIER_unknown;
}
/// Get kind of the clause.
OpenMPScheduleClauseKind getScheduleKind() const { return Kind; }
/// Get the first modifier of the clause.
OpenMPScheduleClauseModifier getFirstScheduleModifier() const {
return Modifiers[FIRST];
}
/// Get the second modifier of the clause.
OpenMPScheduleClauseModifier getSecondScheduleModifier() const {
return Modifiers[SECOND];
}
/// Get location of '('.
SourceLocation getLParenLoc() { return LParenLoc; }
/// Get kind location.
SourceLocation getScheduleKindLoc() { return KindLoc; }
/// Get the first modifier location.
SourceLocation getFirstScheduleModifierLoc() const {
return ModifiersLoc[FIRST];
}
/// Get the second modifier location.
SourceLocation getSecondScheduleModifierLoc() const {
return ModifiersLoc[SECOND];
}
/// Get location of ','.
SourceLocation getCommaLoc() { return CommaLoc; }
/// Get chunk size.
Expr *getChunkSize() { return ChunkSize; }
/// Get chunk size.
const Expr *getChunkSize() const { return ChunkSize; }
child_range children() {
return child_range(reinterpret_cast<Stmt **>(&ChunkSize),
reinterpret_cast<Stmt **>(&ChunkSize) + 1);
}
const_child_range children() const {
auto Children = const_cast<OMPScheduleClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_schedule;
}
};
/// This represents 'ordered' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp for ordered (2)
/// \endcode
/// In this example directive '#pragma omp for' has 'ordered' clause with
/// parameter 2.
class OMPOrderedClause final
: public OMPClause,
private llvm::TrailingObjects<OMPOrderedClause, Expr *> {
friend class OMPClauseReader;
friend TrailingObjects;
/// Location of '('.
SourceLocation LParenLoc;
/// Number of for-loops.
Stmt *NumForLoops = nullptr;
/// Real number of loops.
unsigned NumberOfLoops = 0;
/// Build 'ordered' clause.
///
/// \param Num Expression, possibly associated with this clause.
/// \param NumLoops Number of loops, associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPOrderedClause(Expr *Num, unsigned NumLoops, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_ordered, StartLoc, EndLoc),
LParenLoc(LParenLoc), NumForLoops(Num), NumberOfLoops(NumLoops) {}
/// Build an empty clause.
explicit OMPOrderedClause(unsigned NumLoops)
: OMPClause(llvm::omp::OMPC_ordered, SourceLocation(), SourceLocation()),
NumberOfLoops(NumLoops) {}
/// Set the number of associated for-loops.
void setNumForLoops(Expr *Num) { NumForLoops = Num; }
public:
/// Build 'ordered' clause.
///
/// \param Num Expression, possibly associated with this clause.
/// \param NumLoops Number of loops, associated with this clause.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
static OMPOrderedClause *Create(const ASTContext &C, Expr *Num,
unsigned NumLoops, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Build an empty clause.
static OMPOrderedClause* CreateEmpty(const ASTContext &C, unsigned NumLoops);
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Return the number of associated for-loops.
Expr *getNumForLoops() const { return cast_or_null<Expr>(NumForLoops); }
/// Set number of iterations for the specified loop.
void setLoopNumIterations(unsigned NumLoop, Expr *NumIterations);
/// Get number of iterations for all the loops.
ArrayRef<Expr *> getLoopNumIterations() const;
/// Set loop counter for the specified loop.
void setLoopCounter(unsigned NumLoop, Expr *Counter);
/// Get loops counter for the specified loop.
Expr *getLoopCounter(unsigned NumLoop);
const Expr *getLoopCounter(unsigned NumLoop) const;
child_range children() { return child_range(&NumForLoops, &NumForLoops + 1); }
const_child_range children() const {
return const_child_range(&NumForLoops, &NumForLoops + 1);
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_ordered;
}
};
/// This represents 'nowait' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp for nowait
/// \endcode
/// In this example directive '#pragma omp for' has 'nowait' clause.
class OMPNowaitClause : public OMPClause {
public:
/// Build 'nowait' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_nowait, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPNowaitClause()
: OMPClause(llvm::omp::OMPC_nowait, SourceLocation(), SourceLocation()) {}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_nowait;
}
};
/// This represents 'untied' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp task untied
/// \endcode
/// In this example directive '#pragma omp task' has 'untied' clause.
class OMPUntiedClause : public OMPClause {
public:
/// Build 'untied' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_untied, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPUntiedClause()
: OMPClause(llvm::omp::OMPC_untied, SourceLocation(), SourceLocation()) {}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_untied;
}
};
/// This represents 'mergeable' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp task mergeable
/// \endcode
/// In this example directive '#pragma omp task' has 'mergeable' clause.
class OMPMergeableClause : public OMPClause {
public:
/// Build 'mergeable' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_mergeable, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPMergeableClause()
: OMPClause(llvm::omp::OMPC_mergeable, SourceLocation(),
SourceLocation()) {}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_mergeable;
}
};
/// This represents 'read' clause in the '#pragma omp atomic' directive.
///
/// \code
/// #pragma omp atomic read
/// \endcode
/// In this example directive '#pragma omp atomic' has 'read' clause.
class OMPReadClause : public OMPClause {
public:
/// Build 'read' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_read, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPReadClause()
: OMPClause(llvm::omp::OMPC_read, SourceLocation(), SourceLocation()) {}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_read;
}
};
/// This represents 'write' clause in the '#pragma omp atomic' directive.
///
/// \code
/// #pragma omp atomic write
/// \endcode
/// In this example directive '#pragma omp atomic' has 'write' clause.
class OMPWriteClause : public OMPClause {
public:
/// Build 'write' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_write, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPWriteClause()
: OMPClause(llvm::omp::OMPC_write, SourceLocation(), SourceLocation()) {}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_write;
}
};
/// This represents 'update' clause in the '#pragma omp atomic'
/// directive.
///
/// \code
/// #pragma omp atomic update
/// \endcode
/// In this example directive '#pragma omp atomic' has 'update' clause.
/// Also, this class represents 'update' clause in '#pragma omp depobj'
/// directive.
///
/// \code
/// #pragma omp depobj(a) update(in)
/// \endcode
/// In this example directive '#pragma omp depobj' has 'update' clause with 'in'
/// dependence kind.
class OMPUpdateClause final
: public OMPClause,
private llvm::TrailingObjects<OMPUpdateClause, SourceLocation,
OpenMPDependClauseKind> {
friend class OMPClauseReader;
friend TrailingObjects;
/// true if extended version of the clause for 'depobj' directive.
bool IsExtended = false;
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
size_t numTrailingObjects(OverloadToken<SourceLocation>) const {
// 2 locations: for '(' and argument location.
return IsExtended ? 2 : 0;
}
/// Sets the the location of '(' in clause for 'depobj' directive.
void setLParenLoc(SourceLocation Loc) {
assert(IsExtended && "Expected extended clause.");
*getTrailingObjects<SourceLocation>() = Loc;
}
/// Sets the the location of '(' in clause for 'depobj' directive.
void setArgumentLoc(SourceLocation Loc) {
assert(IsExtended && "Expected extended clause.");
*std::next(getTrailingObjects<SourceLocation>(), 1) = Loc;
}
/// Sets the dependence kind for the clause for 'depobj' directive.
void setDependencyKind(OpenMPDependClauseKind DK) {
assert(IsExtended && "Expected extended clause.");
*getTrailingObjects<OpenMPDependClauseKind>() = DK;
}
/// Build 'update' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc,
bool IsExtended)
: OMPClause(llvm::omp::OMPC_update, StartLoc, EndLoc),
IsExtended(IsExtended) {}
/// Build an empty clause.
OMPUpdateClause(bool IsExtended)
: OMPClause(llvm::omp::OMPC_update, SourceLocation(), SourceLocation()),
IsExtended(IsExtended) {}
public:
/// Creates clause for 'atomic' directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
static OMPUpdateClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Creates clause for 'depobj' directive.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ArgumentLoc Location of the argument.
/// \param DK Dependence kind.
/// \param EndLoc Ending location of the clause.
static OMPUpdateClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ArgumentLoc,
OpenMPDependClauseKind DK,
SourceLocation EndLoc);
/// Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param IsExtended true if extended clause for 'depobj' directive must be
/// created.
static OMPUpdateClause *CreateEmpty(const ASTContext &C, bool IsExtended);
/// Checks if the clause is the extended clauses for 'depobj' directive.
bool isExtended() const { return IsExtended; }
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
/// Gets the the location of '(' in clause for 'depobj' directive.
SourceLocation getLParenLoc() const {
assert(IsExtended && "Expected extended clause.");
return *getTrailingObjects<SourceLocation>();
}
/// Gets the the location of argument in clause for 'depobj' directive.
SourceLocation getArgumentLoc() const {
assert(IsExtended && "Expected extended clause.");
return *std::next(getTrailingObjects<SourceLocation>(), 1);
}
/// Gets the dependence kind in clause for 'depobj' directive.
OpenMPDependClauseKind getDependencyKind() const {
assert(IsExtended && "Expected extended clause.");
return *getTrailingObjects<OpenMPDependClauseKind>();
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_update;
}
};
/// This represents 'capture' clause in the '#pragma omp atomic'
/// directive.
///
/// \code
/// #pragma omp atomic capture
/// \endcode
/// In this example directive '#pragma omp atomic' has 'capture' clause.
class OMPCaptureClause : public OMPClause {
public:
/// Build 'capture' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_capture, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPCaptureClause()
: OMPClause(llvm::omp::OMPC_capture, SourceLocation(), SourceLocation()) {
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_capture;
}
};
/// This represents 'seq_cst' clause in the '#pragma omp atomic'
/// directive.
///
/// \code
/// #pragma omp atomic seq_cst
/// \endcode
/// In this example directive '#pragma omp atomic' has 'seq_cst' clause.
class OMPSeqCstClause : public OMPClause {
public:
/// Build 'seq_cst' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_seq_cst, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPSeqCstClause()
: OMPClause(llvm::omp::OMPC_seq_cst, SourceLocation(), SourceLocation()) {
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_seq_cst;
}
};
/// This represents 'acq_rel' clause in the '#pragma omp atomic|flush'
/// directives.
///
/// \code
/// #pragma omp flush acq_rel
/// \endcode
/// In this example directive '#pragma omp flush' has 'acq_rel' clause.
class OMPAcqRelClause final : public OMPClause {
public:
/// Build 'ack_rel' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPAcqRelClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_acq_rel, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPAcqRelClause()
: OMPClause(llvm::omp::OMPC_acq_rel, SourceLocation(), SourceLocation()) {
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_acq_rel;
}
};
/// This represents 'acquire' clause in the '#pragma omp atomic|flush'
/// directives.
///
/// \code
/// #pragma omp flush acquire
/// \endcode
/// In this example directive '#pragma omp flush' has 'acquire' clause.
class OMPAcquireClause final : public OMPClause {
public:
/// Build 'acquire' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPAcquireClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_acquire, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPAcquireClause()
: OMPClause(llvm::omp::OMPC_acquire, SourceLocation(), SourceLocation()) {
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_acquire;
}
};
/// This represents 'release' clause in the '#pragma omp atomic|flush'
/// directives.
///
/// \code
/// #pragma omp flush release
/// \endcode
/// In this example directive '#pragma omp flush' has 'release' clause.
class OMPReleaseClause final : public OMPClause {
public:
/// Build 'release' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPReleaseClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_release, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPReleaseClause()
: OMPClause(llvm::omp::OMPC_release, SourceLocation(), SourceLocation()) {
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_release;
}
};
/// This represents 'relaxed' clause in the '#pragma omp atomic'
/// directives.
///
/// \code
/// #pragma omp atomic relaxed
/// \endcode
/// In this example directive '#pragma omp atomic' has 'relaxed' clause.
class OMPRelaxedClause final : public OMPClause {
public:
/// Build 'relaxed' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPRelaxedClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_relaxed, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPRelaxedClause()
: OMPClause(llvm::omp::OMPC_relaxed, SourceLocation(), SourceLocation()) {
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_relaxed;
}
};
/// This represents clause 'private' in the '#pragma omp ...' directives.
///
/// \code
/// #pragma omp parallel private(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'private'
/// with the variables 'a' and 'b'.
class OMPPrivateClause final
: public OMPVarListClause<OMPPrivateClause>,
private llvm::TrailingObjects<OMPPrivateClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPPrivateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPPrivateClause>(llvm::omp::OMPC_private, StartLoc,
LParenLoc, EndLoc, N) {}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPPrivateClause(unsigned N)
: OMPVarListClause<OMPPrivateClause>(llvm::omp::OMPC_private,
SourceLocation(), SourceLocation(),
SourceLocation(), N) {}
/// Sets the list of references to private copies with initializers for
/// new private variables.
/// \param VL List of references.
void setPrivateCopies(ArrayRef<Expr *> VL);
/// Gets the list of references to private copies with initializers for
/// new private variables.
MutableArrayRef<Expr *> getPrivateCopies() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivateCopies() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
/// \param PrivateVL List of references to private copies with initializers.
static OMPPrivateClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL,
ArrayRef<Expr *> PrivateVL);
/// Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPPrivateClause *CreateEmpty(const ASTContext &C, unsigned N);
using private_copies_iterator = MutableArrayRef<Expr *>::iterator;
using private_copies_const_iterator = ArrayRef<const Expr *>::iterator;
using private_copies_range = llvm::iterator_range<private_copies_iterator>;
using private_copies_const_range =
llvm::iterator_range<private_copies_const_iterator>;
private_copies_range private_copies() {
return private_copies_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
private_copies_const_range private_copies() const {
return private_copies_const_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPPrivateClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_private;
}
};
/// This represents clause 'firstprivate' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp parallel firstprivate(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'firstprivate'
/// with the variables 'a' and 'b'.
class OMPFirstprivateClause final
: public OMPVarListClause<OMPFirstprivateClause>,
public OMPClauseWithPreInit,
private llvm::TrailingObjects<OMPFirstprivateClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPFirstprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPFirstprivateClause>(llvm::omp::OMPC_firstprivate,
StartLoc, LParenLoc, EndLoc, N),
OMPClauseWithPreInit(this) {}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPFirstprivateClause(unsigned N)
: OMPVarListClause<OMPFirstprivateClause>(
llvm::omp::OMPC_firstprivate, SourceLocation(), SourceLocation(),
SourceLocation(), N),
OMPClauseWithPreInit(this) {}
/// Sets the list of references to private copies with initializers for
/// new private variables.
/// \param VL List of references.
void setPrivateCopies(ArrayRef<Expr *> VL);
/// Gets the list of references to private copies with initializers for
/// new private variables.
MutableArrayRef<Expr *> getPrivateCopies() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivateCopies() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// Sets the list of references to initializer variables for new
/// private variables.
/// \param VL List of references.
void setInits(ArrayRef<Expr *> VL);
/// Gets the list of references to initializer variables for new
/// private variables.
MutableArrayRef<Expr *> getInits() {
return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size());
}
ArrayRef<const Expr *> getInits() const {
return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size());
}
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the original variables.
/// \param PrivateVL List of references to private copies with initializers.
/// \param InitVL List of references to auto generated variables used for
/// initialization of a single array element. Used if firstprivate variable is
/// of array type.
/// \param PreInit Statement that must be executed before entering the OpenMP
/// region with this clause.
static OMPFirstprivateClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PrivateVL,
ArrayRef<Expr *> InitVL, Stmt *PreInit);
/// Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPFirstprivateClause *CreateEmpty(const ASTContext &C, unsigned N);
using private_copies_iterator = MutableArrayRef<Expr *>::iterator;
using private_copies_const_iterator = ArrayRef<const Expr *>::iterator;
using private_copies_range = llvm::iterator_range<private_copies_iterator>;
using private_copies_const_range =
llvm::iterator_range<private_copies_const_iterator>;
private_copies_range private_copies() {
return private_copies_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
private_copies_const_range private_copies() const {
return private_copies_const_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
using inits_iterator = MutableArrayRef<Expr *>::iterator;
using inits_const_iterator = ArrayRef<const Expr *>::iterator;
using inits_range = llvm::iterator_range<inits_iterator>;
using inits_const_range = llvm::iterator_range<inits_const_iterator>;
inits_range inits() {
return inits_range(getInits().begin(), getInits().end());
}
inits_const_range inits() const {
return inits_const_range(getInits().begin(), getInits().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPFirstprivateClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range used_children() const {
auto Children = const_cast<OMPFirstprivateClause *>(this)->used_children();
return const_child_range(Children.begin(), Children.end());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_firstprivate;
}
};
/// This represents clause 'lastprivate' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp simd lastprivate(a,b)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'lastprivate'
/// with the variables 'a' and 'b'.
class OMPLastprivateClause final
: public OMPVarListClause<OMPLastprivateClause>,
public OMPClauseWithPostUpdate,
private llvm::TrailingObjects<OMPLastprivateClause, Expr *> {
// There are 4 additional tail-allocated arrays at the end of the class:
// 1. Contains list of pseudo variables with the default initialization for
// each non-firstprivate variables. Used in codegen for initialization of
// lastprivate copies.
// 2. List of helper expressions for proper generation of assignment operation
// required for lastprivate clause. This list represents private variables
// (for arrays, single array element).
// 3. List of helper expressions for proper generation of assignment operation
// required for lastprivate clause. This list represents original variables
// (for arrays, single array element).
// 4. List of helper expressions that represents assignment operation:
// \code
// DstExprs = SrcExprs;
// \endcode
// Required for proper codegen of final assignment performed by the
// lastprivate clause.
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Optional lastprivate kind, e.g. 'conditional', if specified by user.
OpenMPLastprivateModifier LPKind;
/// Optional location of the lasptrivate kind, if specified by user.
SourceLocation LPKindLoc;
/// Optional colon location, if specified by user.
SourceLocation ColonLoc;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPLastprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, OpenMPLastprivateModifier LPKind,
SourceLocation LPKindLoc, SourceLocation ColonLoc,
unsigned N)
: OMPVarListClause<OMPLastprivateClause>(llvm::omp::OMPC_lastprivate,
StartLoc, LParenLoc, EndLoc, N),
OMPClauseWithPostUpdate(this), LPKind(LPKind), LPKindLoc(LPKindLoc),
ColonLoc(ColonLoc) {}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPLastprivateClause(unsigned N)
: OMPVarListClause<OMPLastprivateClause>(
llvm::omp::OMPC_lastprivate, SourceLocation(), SourceLocation(),
SourceLocation(), N),
OMPClauseWithPostUpdate(this) {}
/// Get the list of helper expressions for initialization of private
/// copies for lastprivate variables.
MutableArrayRef<Expr *> getPrivateCopies() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivateCopies() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent private variables (for arrays, single
/// array element) in the final assignment statement performed by the
/// lastprivate clause.
void setSourceExprs(ArrayRef<Expr *> SrcExprs);
/// Get the list of helper source expressions.
MutableArrayRef<Expr *> getSourceExprs() {
return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size());
}
ArrayRef<const Expr *> getSourceExprs() const {
return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size());
}
/// Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent original variables (for arrays, single
/// array element) in the final assignment statement performed by the
/// lastprivate clause.
void setDestinationExprs(ArrayRef<Expr *> DstExprs);
/// Get the list of helper destination expressions.
MutableArrayRef<Expr *> getDestinationExprs() {
return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getDestinationExprs() const {
return llvm::makeArrayRef(getSourceExprs().end(), varlist_size());
}
/// Set list of helper assignment expressions, required for proper
/// codegen of the clause. These expressions are assignment expressions that
/// assign private copy of the variable to original variable.
void setAssignmentOps(ArrayRef<Expr *> AssignmentOps);
/// Get the list of helper assignment expressions.
MutableArrayRef<Expr *> getAssignmentOps() {
return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getAssignmentOps() const {
return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size());
}
/// Sets lastprivate kind.
void setKind(OpenMPLastprivateModifier Kind) { LPKind = Kind; }
/// Sets location of the lastprivate kind.
void setKindLoc(SourceLocation Loc) { LPKindLoc = Loc; }
/// Sets colon symbol location.
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
/// \param SrcExprs List of helper expressions for proper generation of
/// assignment operation required for lastprivate clause. This list represents
/// private variables (for arrays, single array element).
/// \param DstExprs List of helper expressions for proper generation of
/// assignment operation required for lastprivate clause. This list represents
/// original variables (for arrays, single array element).
/// \param AssignmentOps List of helper expressions that represents assignment
/// operation:
/// \code
/// DstExprs = SrcExprs;
/// \endcode
/// Required for proper codegen of final assignment performed by the
/// lastprivate clause.
/// \param LPKind Lastprivate kind, e.g. 'conditional'.
/// \param LPKindLoc Location of the lastprivate kind.
/// \param ColonLoc Location of the ':' symbol if lastprivate kind is used.
/// \param PreInit Statement that must be executed before entering the OpenMP
/// region with this clause.
/// \param PostUpdate Expression that must be executed after exit from the
/// OpenMP region with this clause.
static OMPLastprivateClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs,
ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps,
OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc,
SourceLocation ColonLoc, Stmt *PreInit, Expr *PostUpdate);
/// Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPLastprivateClause *CreateEmpty(const ASTContext &C, unsigned N);
/// Lastprivate kind.
OpenMPLastprivateModifier getKind() const { return LPKind; }
/// Returns the location of the lastprivate kind.
SourceLocation getKindLoc() const { return LPKindLoc; }
/// Returns the location of the ':' symbol, if any.
SourceLocation getColonLoc() const { return ColonLoc; }
using helper_expr_iterator = MutableArrayRef<Expr *>::iterator;
using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator;
using helper_expr_range = llvm::iterator_range<helper_expr_iterator>;
using helper_expr_const_range =
llvm::iterator_range<helper_expr_const_iterator>;
/// Set list of helper expressions, required for generation of private
/// copies of original lastprivate variables.
void setPrivateCopies(ArrayRef<Expr *> PrivateCopies);
helper_expr_const_range private_copies() const {
return helper_expr_const_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
helper_expr_range private_copies() {
return helper_expr_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
helper_expr_const_range source_exprs() const {
return helper_expr_const_range(getSourceExprs().begin(),
getSourceExprs().end());
}
helper_expr_range source_exprs() {
return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end());
}
helper_expr_const_range destination_exprs() const {
return helper_expr_const_range(getDestinationExprs().begin(),
getDestinationExprs().end());
}
helper_expr_range destination_exprs() {
return helper_expr_range(getDestinationExprs().begin(),
getDestinationExprs().end());
}
helper_expr_const_range assignment_ops() const {
return helper_expr_const_range(getAssignmentOps().begin(),
getAssignmentOps().end());
}
helper_expr_range assignment_ops() {
return helper_expr_range(getAssignmentOps().begin(),
getAssignmentOps().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPLastprivateClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_lastprivate;
}
};
/// This represents clause 'shared' in the '#pragma omp ...' directives.
///
/// \code
/// #pragma omp parallel shared(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'shared'
/// with the variables 'a' and 'b'.
class OMPSharedClause final
: public OMPVarListClause<OMPSharedClause>,
private llvm::TrailingObjects<OMPSharedClause, Expr *> {
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPSharedClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPSharedClause>(llvm::omp::OMPC_shared, StartLoc,
LParenLoc, EndLoc, N) {}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPSharedClause(unsigned N)
: OMPVarListClause<OMPSharedClause>(llvm::omp::OMPC_shared,
SourceLocation(), SourceLocation(),
SourceLocation(), N) {}
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
static OMPSharedClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL);
/// Creates an empty clause with \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPSharedClause *CreateEmpty(const ASTContext &C, unsigned N);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPSharedClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_shared;
}
};
/// This represents clause 'reduction' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp parallel reduction(+:a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'reduction'
/// with operator '+' and the variables 'a' and 'b'.
class OMPReductionClause final
: public OMPVarListClause<OMPReductionClause>,
public OMPClauseWithPostUpdate,
private llvm::TrailingObjects<OMPReductionClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Reduction modifier.
OpenMPReductionClauseModifier Modifier = OMPC_REDUCTION_unknown;
/// Reduction modifier location.
SourceLocation ModifierLoc;
/// Location of ':'.
SourceLocation ColonLoc;
/// Nested name specifier for C++.
NestedNameSpecifierLoc QualifierLoc;
/// Name of custom operator.
DeclarationNameInfo NameInfo;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ModifierLoc Modifier location.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
/// \param QualifierLoc The nested-name qualifier with location information
/// \param NameInfo The full name info for reduction identifier.
OMPReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ModifierLoc, SourceLocation ColonLoc,
SourceLocation EndLoc,
OpenMPReductionClauseModifier Modifier, unsigned N,
NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo)
: OMPVarListClause<OMPReductionClause>(llvm::omp::OMPC_reduction,
StartLoc, LParenLoc, EndLoc, N),
OMPClauseWithPostUpdate(this), Modifier(Modifier),
ModifierLoc(ModifierLoc), ColonLoc(ColonLoc),
QualifierLoc(QualifierLoc), NameInfo(NameInfo) {}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPReductionClause(unsigned N)
: OMPVarListClause<OMPReductionClause>(llvm::omp::OMPC_reduction,
SourceLocation(), SourceLocation(),
SourceLocation(), N),
OMPClauseWithPostUpdate(this) {}
/// Sets reduction modifier.
void setModifier(OpenMPReductionClauseModifier M) { Modifier = M; }
/// Sets location of the modifier.
void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; }
/// Sets location of ':' symbol in clause.
void setColonLoc(SourceLocation CL) { ColonLoc = CL; }
/// Sets the name info for specified reduction identifier.
void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; }
/// Sets the nested name specifier.
void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; }
/// Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent private copy of the reduction
/// variable.
void setPrivates(ArrayRef<Expr *> Privates);
/// Get the list of helper privates.
MutableArrayRef<Expr *> getPrivates() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivates() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent LHS expression in the final
/// reduction expression performed by the reduction clause.
void setLHSExprs(ArrayRef<Expr *> LHSExprs);
/// Get the list of helper LHS expressions.
MutableArrayRef<Expr *> getLHSExprs() {
return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size());
}
ArrayRef<const Expr *> getLHSExprs() const {
return llvm::makeArrayRef(getPrivates().end(), varlist_size());
}
/// Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent RHS expression in the final
/// reduction expression performed by the reduction clause.
/// Also, variables in these expressions are used for proper initialization of
/// reduction copies.
void setRHSExprs(ArrayRef<Expr *> RHSExprs);
/// Get the list of helper destination expressions.
MutableArrayRef<Expr *> getRHSExprs() {
return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getRHSExprs() const {
return llvm::makeArrayRef(getLHSExprs().end(), varlist_size());
}
/// Set list of helper reduction expressions, required for proper
/// codegen of the clause. These expressions are binary expressions or
/// operator/custom reduction call that calculates new value from source
/// helper expressions to destination helper expressions.
void setReductionOps(ArrayRef<Expr *> ReductionOps);
/// Get the list of helper reduction expressions.
MutableArrayRef<Expr *> getReductionOps() {
return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getReductionOps() const {
return llvm::makeArrayRef(getRHSExprs().end(), varlist_size());
}
public:
/// Creates clause with a list of variables \a VL.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ModifierLoc Modifier location.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param VL The variables in the clause.
/// \param QualifierLoc The nested-name qualifier with location information
/// \param NameInfo The full name info for reduction identifier.
/// \param Privates List of helper expressions for proper generation of
/// private copies.
/// \param LHSExprs List of helper expressions for proper generation of
/// assignment operation required for copyprivate clause. This list represents
/// LHSs of the reduction expressions.
/// \param RHSExprs List of helper expressions for proper generation of
/// assignment operation required for copyprivate clause. This list represents
/// RHSs of the reduction expressions.
/// Also, variables in these expressions are used for proper initialization of
/// reduction copies.
/// \param ReductionOps List of helper expressions that represents reduction
/// expressions:
/// \code
/// LHSExprs binop RHSExprs;
/// operator binop(LHSExpr, RHSExpr);
/// <CutomReduction>(LHSExpr, RHSExpr);
/// \endcode
/// Required for proper codegen of final reduction operation performed by the
/// reduction clause.
/// \param PreInit Statement that must be executed before entering the OpenMP
/// region with this clause.
/// \param PostUpdate Expression that must be executed after exit from the
/// OpenMP region with this clause.
static OMPReductionClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ModifierLoc, SourceLocation ColonLoc,
SourceLocation EndLoc, OpenMPReductionClauseModifier Modifier,
ArrayRef<Expr *> VL, NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates,
ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs,
ArrayRef<Expr *> ReductionOps, Stmt *PreInit, Expr *PostUpdate);
/// Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPReductionClause *CreateEmpty(const ASTContext &C, unsigned N);
/// Returns modifier.
OpenMPReductionClauseModifier getModifier() const { return Modifier; }
/// Returns modifier location.
SourceLocation getModifierLoc() const { return ModifierLoc; }
/// Gets location of ':' symbol in clause.
SourceLocation getColonLoc() const { return ColonLoc; }
/// Gets the name info for specified reduction identifier.
const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
/// Gets the nested name specifier.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
using helper_expr_iterator = MutableArrayRef<Expr *>::iterator;
using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator;
using helper_expr_range = llvm::iterator_range<helper_expr_iterator>;
using helper_expr_const_range =
llvm::iterator_range<helper_expr_const_iterator>;
helper_expr_const_range privates() const {
return helper_expr_const_range(getPrivates().begin(), getPrivates().end());
}
helper_expr_range privates() {
return helper_expr_range(getPrivates().begin(), getPrivates().end());
}
helper_expr_const_range lhs_exprs() const {
return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end());
}
helper_expr_range lhs_exprs() {
return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end());
}
helper_expr_const_range rhs_exprs() const {
return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end());
}
helper_expr_range rhs_exprs() {
return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end());
}
helper_expr_const_range reduction_ops() const {
return helper_expr_const_range(getReductionOps().begin(),
getReductionOps().end());
}
helper_expr_range reduction_ops() {
return helper_expr_range(getReductionOps().begin(),
getReductionOps().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPReductionClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range used_children() const {
auto Children = const_cast<OMPReductionClause *>(this)->used_children();
return const_child_range(Children.begin(), Children.end());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_reduction;
}
};
/// This represents clause 'task_reduction' in the '#pragma omp taskgroup'
/// directives.
///
/// \code
/// #pragma omp taskgroup task_reduction(+:a,b)
/// \endcode
/// In this example directive '#pragma omp taskgroup' has clause
/// 'task_reduction' with operator '+' and the variables 'a' and 'b'.
class OMPTaskReductionClause final
: public OMPVarListClause<OMPTaskReductionClause>,
public OMPClauseWithPostUpdate,
private llvm::TrailingObjects<OMPTaskReductionClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Location of ':'.
SourceLocation ColonLoc;
/// Nested name specifier for C++.
NestedNameSpecifierLoc QualifierLoc;
/// Name of custom operator.
DeclarationNameInfo NameInfo;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param ColonLoc Location of ':'.
/// \param N Number of the variables in the clause.
/// \param QualifierLoc The nested-name qualifier with location information
/// \param NameInfo The full name info for reduction identifier.
OMPTaskReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc,
unsigned N, NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo)
: OMPVarListClause<OMPTaskReductionClause>(
llvm::omp::OMPC_task_reduction, StartLoc, LParenLoc, EndLoc, N),
OMPClauseWithPostUpdate(this), ColonLoc(ColonLoc),
QualifierLoc(QualifierLoc), NameInfo(NameInfo) {}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPTaskReductionClause(unsigned N)
: OMPVarListClause<OMPTaskReductionClause>(
llvm::omp::OMPC_task_reduction, SourceLocation(), SourceLocation(),
SourceLocation(), N),
OMPClauseWithPostUpdate(this) {}
/// Sets location of ':' symbol in clause.
void setColonLoc(SourceLocation CL) { ColonLoc = CL; }
/// Sets the name info for specified reduction identifier.
void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; }
/// Sets the nested name specifier.
void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; }
/// Set list of helper expressions, required for proper codegen of the clause.
/// These expressions represent private copy of the reduction variable.
void setPrivates(ArrayRef<Expr *> Privates);
/// Get the list of helper privates.
MutableArrayRef<Expr *> getPrivates() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivates() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// Set list of helper expressions, required for proper codegen of the clause.
/// These expressions represent LHS expression in the final reduction
/// expression performed by the reduction clause.
void setLHSExprs(ArrayRef<Expr *> LHSExprs);
/// Get the list of helper LHS expressions.
MutableArrayRef<Expr *> getLHSExprs() {
return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size());
}
ArrayRef<const Expr *> getLHSExprs() const {
return llvm::makeArrayRef(getPrivates().end(), varlist_size());
}
/// Set list of helper expressions, required for proper codegen of the clause.
/// These expressions represent RHS expression in the final reduction
/// expression performed by the reduction clause. Also, variables in these
/// expressions are used for proper initialization of reduction copies.
void setRHSExprs(ArrayRef<Expr *> RHSExprs);
/// Get the list of helper destination expressions.
MutableArrayRef<Expr *> getRHSExprs() {
return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getRHSExprs() const {
return llvm::makeArrayRef(getLHSExprs().end(), varlist_size());
}
/// Set list of helper reduction expressions, required for proper
/// codegen of the clause. These expressions are binary expressions or
/// operator/custom reduction call that calculates new value from source
/// helper expressions to destination helper expressions.
void setReductionOps(ArrayRef<Expr *> ReductionOps);
/// Get the list of helper reduction expressions.
MutableArrayRef<Expr *> getReductionOps() {
return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getReductionOps() const {
return llvm::makeArrayRef(getRHSExprs().end(), varlist_size());
}
public:
/// Creates clause with a list of variables \a VL.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param VL The variables in the clause.
/// \param QualifierLoc The nested-name qualifier with location information
/// \param NameInfo The full name info for reduction identifier.
/// \param Privates List of helper expressions for proper generation of
/// private copies.
/// \param LHSExprs List of helper expressions for proper generation of
/// assignment operation required for copyprivate clause. This list represents
/// LHSs of the reduction expressions.
/// \param RHSExprs List of helper expressions for proper generation of
/// assignment operation required for copyprivate clause. This list represents
/// RHSs of the reduction expressions.
/// Also, variables in these expressions are used for proper initialization of
/// reduction copies.
/// \param ReductionOps List of helper expressions that represents reduction
/// expressions:
/// \code
/// LHSExprs binop RHSExprs;
/// operator binop(LHSExpr, RHSExpr);
/// <CutomReduction>(LHSExpr, RHSExpr);
/// \endcode
/// Required for proper codegen of final reduction operation performed by the
/// reduction clause.
/// \param PreInit Statement that must be executed before entering the OpenMP
/// region with this clause.
/// \param PostUpdate Expression that must be executed after exit from the
/// OpenMP region with this clause.
static OMPTaskReductionClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL,
NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates,
ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs,
ArrayRef<Expr *> ReductionOps, Stmt *PreInit, Expr *PostUpdate);
/// Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPTaskReductionClause *CreateEmpty(const ASTContext &C, unsigned N);
/// Gets location of ':' symbol in clause.
SourceLocation getColonLoc() const { return ColonLoc; }
/// Gets the name info for specified reduction identifier.
const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
/// Gets the nested name specifier.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
using helper_expr_iterator = MutableArrayRef<Expr *>::iterator;
using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator;
using helper_expr_range = llvm::iterator_range<helper_expr_iterator>;
using helper_expr_const_range =
llvm::iterator_range<helper_expr_const_iterator>;
helper_expr_const_range privates() const {
return helper_expr_const_range(getPrivates().begin(), getPrivates().end());
}
helper_expr_range privates() {
return helper_expr_range(getPrivates().begin(), getPrivates().end());
}
helper_expr_const_range lhs_exprs() const {
return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end());
}
helper_expr_range lhs_exprs() {
return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end());
}
helper_expr_const_range rhs_exprs() const {
return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end());
}
helper_expr_range rhs_exprs() {
return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end());
}
helper_expr_const_range reduction_ops() const {
return helper_expr_const_range(getReductionOps().begin(),
getReductionOps().end());
}
helper_expr_range reduction_ops() {
return helper_expr_range(getReductionOps().begin(),
getReductionOps().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPTaskReductionClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_task_reduction;
}
};
/// This represents clause 'in_reduction' in the '#pragma omp task' directives.
///
/// \code
/// #pragma omp task in_reduction(+:a,b)
/// \endcode
/// In this example directive '#pragma omp task' has clause 'in_reduction' with
/// operator '+' and the variables 'a' and 'b'.
class OMPInReductionClause final
: public OMPVarListClause<OMPInReductionClause>,
public OMPClauseWithPostUpdate,
private llvm::TrailingObjects<OMPInReductionClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Location of ':'.
SourceLocation ColonLoc;
/// Nested name specifier for C++.
NestedNameSpecifierLoc QualifierLoc;
/// Name of custom operator.
DeclarationNameInfo NameInfo;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param ColonLoc Location of ':'.
/// \param N Number of the variables in the clause.
/// \param QualifierLoc The nested-name qualifier with location information
/// \param NameInfo The full name info for reduction identifier.
OMPInReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc,
unsigned N, NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo)
: OMPVarListClause<OMPInReductionClause>(llvm::omp::OMPC_in_reduction,
StartLoc, LParenLoc, EndLoc, N),
OMPClauseWithPostUpdate(this), ColonLoc(ColonLoc),
QualifierLoc(QualifierLoc), NameInfo(NameInfo) {}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPInReductionClause(unsigned N)
: OMPVarListClause<OMPInReductionClause>(
llvm::omp::OMPC_in_reduction, SourceLocation(), SourceLocation(),
SourceLocation(), N),
OMPClauseWithPostUpdate(this) {}
/// Sets location of ':' symbol in clause.
void setColonLoc(SourceLocation CL) { ColonLoc = CL; }
/// Sets the name info for specified reduction identifier.
void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; }
/// Sets the nested name specifier.
void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; }
/// Set list of helper expressions, required for proper codegen of the clause.
/// These expressions represent private copy of the reduction variable.
void setPrivates(ArrayRef<Expr *> Privates);
/// Get the list of helper privates.
MutableArrayRef<Expr *> getPrivates() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivates() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// Set list of helper expressions, required for proper codegen of the clause.
/// These expressions represent LHS expression in the final reduction
/// expression performed by the reduction clause.
void setLHSExprs(ArrayRef<Expr *> LHSExprs);
/// Get the list of helper LHS expressions.
MutableArrayRef<Expr *> getLHSExprs() {
return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size());
}
ArrayRef<const Expr *> getLHSExprs() const {
return llvm::makeArrayRef(getPrivates().end(), varlist_size());
}
/// Set list of helper expressions, required for proper codegen of the clause.
/// These expressions represent RHS expression in the final reduction
/// expression performed by the reduction clause. Also, variables in these
/// expressions are used for proper initialization of reduction copies.
void setRHSExprs(ArrayRef<Expr *> RHSExprs);
/// Get the list of helper destination expressions.
MutableArrayRef<Expr *> getRHSExprs() {
return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getRHSExprs() const {
return llvm::makeArrayRef(getLHSExprs().end(), varlist_size());
}
/// Set list of helper reduction expressions, required for proper
/// codegen of the clause. These expressions are binary expressions or
/// operator/custom reduction call that calculates new value from source
/// helper expressions to destination helper expressions.
void setReductionOps(ArrayRef<Expr *> ReductionOps);
/// Get the list of helper reduction expressions.
MutableArrayRef<Expr *> getReductionOps() {
return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getReductionOps() const {
return llvm::makeArrayRef(getRHSExprs().end(), varlist_size());
}
/// Set list of helper reduction taskgroup descriptors.
void setTaskgroupDescriptors(ArrayRef<Expr *> ReductionOps);
/// Get the list of helper reduction taskgroup descriptors.
MutableArrayRef<Expr *> getTaskgroupDescriptors() {
return MutableArrayRef<Expr *>(getReductionOps().end(), varlist_size());
}
ArrayRef<const Expr *> getTaskgroupDescriptors() const {
return llvm::makeArrayRef(getReductionOps().end(), varlist_size());
}
public:
/// Creates clause with a list of variables \a VL.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param VL The variables in the clause.
/// \param QualifierLoc The nested-name qualifier with location information
/// \param NameInfo The full name info for reduction identifier.
/// \param Privates List of helper expressions for proper generation of
/// private copies.
/// \param LHSExprs List of helper expressions for proper generation of
/// assignment operation required for copyprivate clause. This list represents
/// LHSs of the reduction expressions.
/// \param RHSExprs List of helper expressions for proper generation of
/// assignment operation required for copyprivate clause. This list represents
/// RHSs of the reduction expressions.
/// Also, variables in these expressions are used for proper initialization of
/// reduction copies.
/// \param ReductionOps List of helper expressions that represents reduction
/// expressions:
/// \code
/// LHSExprs binop RHSExprs;
/// operator binop(LHSExpr, RHSExpr);
/// <CutomReduction>(LHSExpr, RHSExpr);
/// \endcode
/// Required for proper codegen of final reduction operation performed by the
/// reduction clause.
/// \param TaskgroupDescriptors List of helper taskgroup descriptors for
/// corresponding items in parent taskgroup task_reduction clause.
/// \param PreInit Statement that must be executed before entering the OpenMP
/// region with this clause.
/// \param PostUpdate Expression that must be executed after exit from the
/// OpenMP region with this clause.
static OMPInReductionClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL,
NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates,
ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs,
ArrayRef<Expr *> ReductionOps, ArrayRef<Expr *> TaskgroupDescriptors,
Stmt *PreInit, Expr *PostUpdate);
/// Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPInReductionClause *CreateEmpty(const ASTContext &C, unsigned N);
/// Gets location of ':' symbol in clause.
SourceLocation getColonLoc() const { return ColonLoc; }
/// Gets the name info for specified reduction identifier.
const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
/// Gets the nested name specifier.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
using helper_expr_iterator = MutableArrayRef<Expr *>::iterator;
using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator;
using helper_expr_range = llvm::iterator_range<helper_expr_iterator>;
using helper_expr_const_range =
llvm::iterator_range<helper_expr_const_iterator>;
helper_expr_const_range privates() const {
return helper_expr_const_range(getPrivates().begin(), getPrivates().end());
}
helper_expr_range privates() {
return helper_expr_range(getPrivates().begin(), getPrivates().end());
}
helper_expr_const_range lhs_exprs() const {
return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end());
}
helper_expr_range lhs_exprs() {
return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end());
}
helper_expr_const_range rhs_exprs() const {
return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end());
}
helper_expr_range rhs_exprs() {
return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end());
}
helper_expr_const_range reduction_ops() const {
return helper_expr_const_range(getReductionOps().begin(),
getReductionOps().end());
}
helper_expr_range reduction_ops() {
return helper_expr_range(getReductionOps().begin(),
getReductionOps().end());
}
helper_expr_const_range taskgroup_descriptors() const {
return helper_expr_const_range(getTaskgroupDescriptors().begin(),
getTaskgroupDescriptors().end());
}
helper_expr_range taskgroup_descriptors() {
return helper_expr_range(getTaskgroupDescriptors().begin(),
getTaskgroupDescriptors().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPInReductionClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_in_reduction;
}
};
/// This represents clause 'linear' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp simd linear(a,b : 2)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'linear'
/// with variables 'a', 'b' and linear step '2'.
class OMPLinearClause final
: public OMPVarListClause<OMPLinearClause>,
public OMPClauseWithPostUpdate,
private llvm::TrailingObjects<OMPLinearClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Modifier of 'linear' clause.
OpenMPLinearClauseKind Modifier = OMPC_LINEAR_val;
/// Location of linear modifier if any.
SourceLocation ModifierLoc;
/// Location of ':'.
SourceLocation ColonLoc;
/// Sets the linear step for clause.
void setStep(Expr *Step) { *(getFinals().end()) = Step; }
/// Sets the expression to calculate linear step for clause.
void setCalcStep(Expr *CalcStep) { *(getFinals().end() + 1) = CalcStep; }
/// Build 'linear' clause with given number of variables \a NumVars.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param NumVars Number of variables.
OMPLinearClause(SourceLocation StartLoc, SourceLocation LParenLoc,
OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc,
SourceLocation ColonLoc, SourceLocation EndLoc,
unsigned NumVars)
: OMPVarListClause<OMPLinearClause>(llvm::omp::OMPC_linear, StartLoc,
LParenLoc, EndLoc, NumVars),
OMPClauseWithPostUpdate(this), Modifier(Modifier),
ModifierLoc(ModifierLoc), ColonLoc(ColonLoc) {}
/// Build an empty clause.
///
/// \param NumVars Number of variables.
explicit OMPLinearClause(unsigned NumVars)
: OMPVarListClause<OMPLinearClause>(llvm::omp::OMPC_linear,
SourceLocation(), SourceLocation(),
SourceLocation(), NumVars),
OMPClauseWithPostUpdate(this) {}
/// Gets the list of initial values for linear variables.
///
/// There are NumVars expressions with initial values allocated after the
/// varlist, they are followed by NumVars update expressions (used to update
/// the linear variable's value on current iteration) and they are followed by
/// NumVars final expressions (used to calculate the linear variable's
/// value after the loop body). After these lists, there are 2 helper
/// expressions - linear step and a helper to calculate it before the
/// loop body (used when the linear step is not constant):
///
/// { Vars[] /* in OMPVarListClause */; Privates[]; Inits[]; Updates[];
/// Finals[]; Step; CalcStep; }
MutableArrayRef<Expr *> getPrivates() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivates() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
MutableArrayRef<Expr *> getInits() {
return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size());
}
ArrayRef<const Expr *> getInits() const {
return llvm::makeArrayRef(getPrivates().end(), varlist_size());
}
/// Sets the list of update expressions for linear variables.
MutableArrayRef<Expr *> getUpdates() {
return MutableArrayRef<Expr *>(getInits().end(), varlist_size());
}
ArrayRef<const Expr *> getUpdates() const {
return llvm::makeArrayRef(getInits().end(), varlist_size());
}
/// Sets the list of final update expressions for linear variables.
MutableArrayRef<Expr *> getFinals() {
return MutableArrayRef<Expr *>(getUpdates().end(), varlist_size());
}
ArrayRef<const Expr *> getFinals() const {
return llvm::makeArrayRef(getUpdates().end(), varlist_size());
}
/// Gets the list of used expressions for linear variables.
MutableArrayRef<Expr *> getUsedExprs() {
return MutableArrayRef<Expr *>(getFinals().end() + 2, varlist_size() + 1);
}
ArrayRef<const Expr *> getUsedExprs() const {
return llvm::makeArrayRef(getFinals().end() + 2, varlist_size() + 1);
}
/// Sets the list of the copies of original linear variables.
/// \param PL List of expressions.
void setPrivates(ArrayRef<Expr *> PL);
/// Sets the list of the initial values for linear variables.
/// \param IL List of expressions.
void setInits(ArrayRef<Expr *> IL);
public:
/// Creates clause with a list of variables \a VL and a linear step
/// \a Step.
///
/// \param C AST Context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param Modifier Modifier of 'linear' clause.
/// \param ModifierLoc Modifier location.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
/// \param PL List of private copies of original variables.
/// \param IL List of initial values for the variables.
/// \param Step Linear step.
/// \param CalcStep Calculation of the linear step.
/// \param PreInit Statement that must be executed before entering the OpenMP
/// region with this clause.
/// \param PostUpdate Expression that must be executed after exit from the
/// OpenMP region with this clause.
static OMPLinearClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc,
SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL,
ArrayRef<Expr *> PL, ArrayRef<Expr *> IL, Expr *Step, Expr *CalcStep,
Stmt *PreInit, Expr *PostUpdate);
/// Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param NumVars Number of variables.
static OMPLinearClause *CreateEmpty(const ASTContext &C, unsigned NumVars);
/// Set modifier.
void setModifier(OpenMPLinearClauseKind Kind) { Modifier = Kind; }
/// Return modifier.
OpenMPLinearClauseKind getModifier() const { return Modifier; }
/// Set modifier location.
void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; }
/// Return modifier location.
SourceLocation getModifierLoc() const { return ModifierLoc; }
/// Sets the location of ':'.
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
/// Returns the location of ':'.
SourceLocation getColonLoc() const { return ColonLoc; }
/// Returns linear step.
Expr *getStep() { return *(getFinals().end()); }
/// Returns linear step.
const Expr *getStep() const { return *(getFinals().end()); }
/// Returns expression to calculate linear step.
Expr *getCalcStep() { return *(getFinals().end() + 1); }
/// Returns expression to calculate linear step.
const Expr *getCalcStep() const { return *(getFinals().end() + 1); }
/// Sets the list of update expressions for linear variables.
/// \param UL List of expressions.
void setUpdates(ArrayRef<Expr *> UL);
/// Sets the list of final update expressions for linear variables.
/// \param FL List of expressions.
void setFinals(ArrayRef<Expr *> FL);
/// Sets the list of used expressions for the linear clause.
void setUsedExprs(ArrayRef<Expr *> UE);
using privates_iterator = MutableArrayRef<Expr *>::iterator;
using privates_const_iterator = ArrayRef<const Expr *>::iterator;
using privates_range = llvm::iterator_range<privates_iterator>;
using privates_const_range = llvm::iterator_range<privates_const_iterator>;
privates_range privates() {
return privates_range(getPrivates().begin(), getPrivates().end());
}
privates_const_range privates() const {
return privates_const_range(getPrivates().begin(), getPrivates().end());
}
using inits_iterator = MutableArrayRef<Expr *>::iterator;
using inits_const_iterator = ArrayRef<const Expr *>::iterator;
using inits_range = llvm::iterator_range<inits_iterator>;
using inits_const_range = llvm::iterator_range<inits_const_iterator>;
inits_range inits() {
return inits_range(getInits().begin(), getInits().end());
}
inits_const_range inits() const {
return inits_const_range(getInits().begin(), getInits().end());
}
using updates_iterator = MutableArrayRef<Expr *>::iterator;
using updates_const_iterator = ArrayRef<const Expr *>::iterator;
using updates_range = llvm::iterator_range<updates_iterator>;
using updates_const_range = llvm::iterator_range<updates_const_iterator>;
updates_range updates() {
return updates_range(getUpdates().begin(), getUpdates().end());
}
updates_const_range updates() const {
return updates_const_range(getUpdates().begin(), getUpdates().end());
}
using finals_iterator = MutableArrayRef<Expr *>::iterator;
using finals_const_iterator = ArrayRef<const Expr *>::iterator;
using finals_range = llvm::iterator_range<finals_iterator>;
using finals_const_range = llvm::iterator_range<finals_const_iterator>;
finals_range finals() {
return finals_range(getFinals().begin(), getFinals().end());
}
finals_const_range finals() const {
return finals_const_range(getFinals().begin(), getFinals().end());
}
using used_expressions_iterator = MutableArrayRef<Expr *>::iterator;
using used_expressions_const_iterator = ArrayRef<const Expr *>::iterator;
using used_expressions_range =
llvm::iterator_range<used_expressions_iterator>;
using used_expressions_const_range =
llvm::iterator_range<used_expressions_const_iterator>;
used_expressions_range used_expressions() {
return finals_range(getUsedExprs().begin(), getUsedExprs().end());
}
used_expressions_const_range used_expressions() const {
return finals_const_range(getUsedExprs().begin(), getUsedExprs().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPLinearClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children();
const_child_range used_children() const {
auto Children = const_cast<OMPLinearClause *>(this)->used_children();
return const_child_range(Children.begin(), Children.end());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_linear;
}
};
/// This represents clause 'aligned' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp simd aligned(a,b : 8)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'aligned'
/// with variables 'a', 'b' and alignment '8'.
class OMPAlignedClause final
: public OMPVarListClause<OMPAlignedClause>,
private llvm::TrailingObjects<OMPAlignedClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Location of ':'.
SourceLocation ColonLoc;
/// Sets the alignment for clause.
void setAlignment(Expr *A) { *varlist_end() = A; }
/// Build 'aligned' clause with given number of variables \a NumVars.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param NumVars Number of variables.
OMPAlignedClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc,
unsigned NumVars)
: OMPVarListClause<OMPAlignedClause>(llvm::omp::OMPC_aligned, StartLoc,
LParenLoc, EndLoc, NumVars),
ColonLoc(ColonLoc) {}
/// Build an empty clause.
///
/// \param NumVars Number of variables.
explicit OMPAlignedClause(unsigned NumVars)
: OMPVarListClause<OMPAlignedClause>(llvm::omp::OMPC_aligned,
SourceLocation(), SourceLocation(),
SourceLocation(), NumVars) {}
public:
/// Creates clause with a list of variables \a VL and alignment \a A.
///
/// \param C AST Context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
/// \param A Alignment.
static OMPAlignedClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL,
Expr *A);
/// Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param NumVars Number of variables.
static OMPAlignedClause *CreateEmpty(const ASTContext &C, unsigned NumVars);
/// Sets the location of ':'.
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
/// Returns the location of ':'.
SourceLocation getColonLoc() const { return ColonLoc; }
/// Returns alignment.
Expr *getAlignment() { return *varlist_end(); }
/// Returns alignment.
const Expr *getAlignment() const { return *varlist_end(); }
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPAlignedClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_aligned;
}
};
/// This represents clause 'copyin' in the '#pragma omp ...' directives.
///
/// \code
/// #pragma omp parallel copyin(a,b)
/// \endcode
/// In this example directive '#pragma omp parallel' has clause 'copyin'
/// with the variables 'a' and 'b'.
class OMPCopyinClause final
: public OMPVarListClause<OMPCopyinClause>,
private llvm::TrailingObjects<OMPCopyinClause, Expr *> {
// Class has 3 additional tail allocated arrays:
// 1. List of helper expressions for proper generation of assignment operation
// required for copyin clause. This list represents sources.
// 2. List of helper expressions for proper generation of assignment operation
// required for copyin clause. This list represents destinations.
// 3. List of helper expressions that represents assignment operation:
// \code
// DstExprs = SrcExprs;
// \endcode
// Required for proper codegen of propagation of master's thread values of
// threadprivate variables to local instances of that variables in other
// implicit threads.
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPCopyinClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPCopyinClause>(llvm::omp::OMPC_copyin, StartLoc,
LParenLoc, EndLoc, N) {}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPCopyinClause(unsigned N)
: OMPVarListClause<OMPCopyinClause>(llvm::omp::OMPC_copyin,
SourceLocation(), SourceLocation(),
SourceLocation(), N) {}
/// Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent source expression in the final
/// assignment statement performed by the copyin clause.
void setSourceExprs(ArrayRef<Expr *> SrcExprs);
/// Get the list of helper source expressions.
MutableArrayRef<Expr *> getSourceExprs() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getSourceExprs() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent destination expression in the final
/// assignment statement performed by the copyin clause.
void setDestinationExprs(ArrayRef<Expr *> DstExprs);
/// Get the list of helper destination expressions.
MutableArrayRef<Expr *> getDestinationExprs() {
return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getDestinationExprs() const {
return llvm::makeArrayRef(getSourceExprs().end(), varlist_size());
}
/// Set list of helper assignment expressions, required for proper
/// codegen of the clause. These expressions are assignment expressions that
/// assign source helper expressions to destination helper expressions
/// correspondingly.
void setAssignmentOps(ArrayRef<Expr *> AssignmentOps);
/// Get the list of helper assignment expressions.
MutableArrayRef<Expr *> getAssignmentOps() {
return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getAssignmentOps() const {
return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size());
}
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
/// \param SrcExprs List of helper expressions for proper generation of
/// assignment operation required for copyin clause. This list represents
/// sources.
/// \param DstExprs List of helper expressions for proper generation of
/// assignment operation required for copyin clause. This list represents
/// destinations.
/// \param AssignmentOps List of helper expressions that represents assignment
/// operation:
/// \code
/// DstExprs = SrcExprs;
/// \endcode
/// Required for proper codegen of propagation of master's thread values of
/// threadprivate variables to local instances of that variables in other
/// implicit threads.
static OMPCopyinClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs,
ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps);
/// Creates an empty clause with \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPCopyinClause *CreateEmpty(const ASTContext &C, unsigned N);
using helper_expr_iterator = MutableArrayRef<Expr *>::iterator;
using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator;
using helper_expr_range = llvm::iterator_range<helper_expr_iterator>;
using helper_expr_const_range =
llvm::iterator_range<helper_expr_const_iterator>;
helper_expr_const_range source_exprs() const {
return helper_expr_const_range(getSourceExprs().begin(),
getSourceExprs().end());
}
helper_expr_range source_exprs() {
return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end());
}
helper_expr_const_range destination_exprs() const {
return helper_expr_const_range(getDestinationExprs().begin(),
getDestinationExprs().end());
}
helper_expr_range destination_exprs() {
return helper_expr_range(getDestinationExprs().begin(),
getDestinationExprs().end());
}
helper_expr_const_range assignment_ops() const {
return helper_expr_const_range(getAssignmentOps().begin(),
getAssignmentOps().end());
}
helper_expr_range assignment_ops() {
return helper_expr_range(getAssignmentOps().begin(),
getAssignmentOps().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPCopyinClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_copyin;
}
};
/// This represents clause 'copyprivate' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp single copyprivate(a,b)
/// \endcode
/// In this example directive '#pragma omp single' has clause 'copyprivate'
/// with the variables 'a' and 'b'.
class OMPCopyprivateClause final
: public OMPVarListClause<OMPCopyprivateClause>,
private llvm::TrailingObjects<OMPCopyprivateClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPCopyprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPCopyprivateClause>(llvm::omp::OMPC_copyprivate,
StartLoc, LParenLoc, EndLoc, N) {
}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPCopyprivateClause(unsigned N)
: OMPVarListClause<OMPCopyprivateClause>(
llvm::omp::OMPC_copyprivate, SourceLocation(), SourceLocation(),
SourceLocation(), N) {}
/// Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent source expression in the final
/// assignment statement performed by the copyprivate clause.
void setSourceExprs(ArrayRef<Expr *> SrcExprs);
/// Get the list of helper source expressions.
MutableArrayRef<Expr *> getSourceExprs() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getSourceExprs() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// Set list of helper expressions, required for proper codegen of the
/// clause. These expressions represent destination expression in the final
/// assignment statement performed by the copyprivate clause.
void setDestinationExprs(ArrayRef<Expr *> DstExprs);
/// Get the list of helper destination expressions.
MutableArrayRef<Expr *> getDestinationExprs() {
return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getDestinationExprs() const {
return llvm::makeArrayRef(getSourceExprs().end(), varlist_size());
}
/// Set list of helper assignment expressions, required for proper
/// codegen of the clause. These expressions are assignment expressions that
/// assign source helper expressions to destination helper expressions
/// correspondingly.
void setAssignmentOps(ArrayRef<Expr *> AssignmentOps);
/// Get the list of helper assignment expressions.
MutableArrayRef<Expr *> getAssignmentOps() {
return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size());
}
ArrayRef<const Expr *> getAssignmentOps() const {
return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size());
}
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
/// \param SrcExprs List of helper expressions for proper generation of
/// assignment operation required for copyprivate clause. This list represents
/// sources.
/// \param DstExprs List of helper expressions for proper generation of
/// assignment operation required for copyprivate clause. This list represents
/// destinations.
/// \param AssignmentOps List of helper expressions that represents assignment
/// operation:
/// \code
/// DstExprs = SrcExprs;
/// \endcode
/// Required for proper codegen of final assignment performed by the
/// copyprivate clause.
static OMPCopyprivateClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs,
ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps);
/// Creates an empty clause with \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPCopyprivateClause *CreateEmpty(const ASTContext &C, unsigned N);
using helper_expr_iterator = MutableArrayRef<Expr *>::iterator;
using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator;
using helper_expr_range = llvm::iterator_range<helper_expr_iterator>;
using helper_expr_const_range =
llvm::iterator_range<helper_expr_const_iterator>;
helper_expr_const_range source_exprs() const {
return helper_expr_const_range(getSourceExprs().begin(),
getSourceExprs().end());
}
helper_expr_range source_exprs() {
return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end());
}
helper_expr_const_range destination_exprs() const {
return helper_expr_const_range(getDestinationExprs().begin(),
getDestinationExprs().end());
}
helper_expr_range destination_exprs() {
return helper_expr_range(getDestinationExprs().begin(),
getDestinationExprs().end());
}
helper_expr_const_range assignment_ops() const {
return helper_expr_const_range(getAssignmentOps().begin(),
getAssignmentOps().end());
}
helper_expr_range assignment_ops() {
return helper_expr_range(getAssignmentOps().begin(),
getAssignmentOps().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPCopyprivateClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_copyprivate;
}
};
/// This represents implicit clause 'flush' for the '#pragma omp flush'
/// directive.
/// This clause does not exist by itself, it can be only as a part of 'omp
/// flush' directive. This clause is introduced to keep the original structure
/// of \a OMPExecutableDirective class and its derivatives and to use the
/// existing infrastructure of clauses with the list of variables.
///
/// \code
/// #pragma omp flush(a,b)
/// \endcode
/// In this example directive '#pragma omp flush' has implicit clause 'flush'
/// with the variables 'a' and 'b'.
class OMPFlushClause final
: public OMPVarListClause<OMPFlushClause>,
private llvm::TrailingObjects<OMPFlushClause, Expr *> {
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPFlushClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPFlushClause>(llvm::omp::OMPC_flush, StartLoc,
LParenLoc, EndLoc, N) {}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPFlushClause(unsigned N)
: OMPVarListClause<OMPFlushClause>(llvm::omp::OMPC_flush,
SourceLocation(), SourceLocation(),
SourceLocation(), N) {}
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
static OMPFlushClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc,
ArrayRef<Expr *> VL);
/// Creates an empty clause with \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPFlushClause *CreateEmpty(const ASTContext &C, unsigned N);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPFlushClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_flush;
}
};
/// This represents implicit clause 'depobj' for the '#pragma omp depobj'
/// directive.
/// This clause does not exist by itself, it can be only as a part of 'omp
/// depobj' directive. This clause is introduced to keep the original structure
/// of \a OMPExecutableDirective class and its derivatives and to use the
/// existing infrastructure of clauses with the list of variables.
///
/// \code
/// #pragma omp depobj(a) destroy
/// \endcode
/// In this example directive '#pragma omp depobj' has implicit clause 'depobj'
/// with the depobj 'a'.
class OMPDepobjClause final : public OMPClause {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Chunk size.
Expr *Depobj = nullptr;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPDepobjClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_depobj, StartLoc, EndLoc),
LParenLoc(LParenLoc) {}
/// Build an empty clause.
///
explicit OMPDepobjClause()
: OMPClause(llvm::omp::OMPC_depobj, SourceLocation(), SourceLocation()) {}
void setDepobj(Expr *E) { Depobj = E; }
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
public:
/// Creates clause.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param Depobj depobj expression associated with the 'depobj' directive.
static OMPDepobjClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc, Expr *Depobj);
/// Creates an empty clause.
///
/// \param C AST context.
static OMPDepobjClause *CreateEmpty(const ASTContext &C);
/// Returns depobj expression associated with the clause.
Expr *getDepobj() { return Depobj; }
const Expr *getDepobj() const { return Depobj; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
child_range children() {
return child_range(reinterpret_cast<Stmt **>(&Depobj),
reinterpret_cast<Stmt **>(&Depobj) + 1);
}
const_child_range children() const {
auto Children = const_cast<OMPDepobjClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_depobj;
}
};
/// This represents implicit clause 'depend' for the '#pragma omp task'
/// directive.
///
/// \code
/// #pragma omp task depend(in:a,b)
/// \endcode
/// In this example directive '#pragma omp task' with clause 'depend' with the
/// variables 'a' and 'b' with dependency 'in'.
class OMPDependClause final
: public OMPVarListClause<OMPDependClause>,
private llvm::TrailingObjects<OMPDependClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Dependency type (one of in, out, inout).
OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
/// Dependency type location.
SourceLocation DepLoc;
/// Colon location.
SourceLocation ColonLoc;
/// Number of loops, associated with the depend clause.
unsigned NumLoops = 0;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
/// \param NumLoops Number of loops that is associated with this depend
/// clause.
OMPDependClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N, unsigned NumLoops)
: OMPVarListClause<OMPDependClause>(llvm::omp::OMPC_depend, StartLoc,
LParenLoc, EndLoc, N),
NumLoops(NumLoops) {}
/// Build an empty clause.
///
/// \param N Number of variables.
/// \param NumLoops Number of loops that is associated with this depend
/// clause.
explicit OMPDependClause(unsigned N, unsigned NumLoops)
: OMPVarListClause<OMPDependClause>(llvm::omp::OMPC_depend,
SourceLocation(), SourceLocation(),
SourceLocation(), N),
NumLoops(NumLoops) {}
/// Set dependency kind.
void setDependencyKind(OpenMPDependClauseKind K) { DepKind = K; }
/// Set dependency kind and its location.
void setDependencyLoc(SourceLocation Loc) { DepLoc = Loc; }
/// Set colon location.
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
/// Sets optional dependency modifier.
void setModifier(Expr *DepModifier);
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param DepKind Dependency type.
/// \param DepLoc Location of the dependency type.
/// \param ColonLoc Colon location.
/// \param VL List of references to the variables.
/// \param NumLoops Number of loops that is associated with this depend
/// clause.
static OMPDependClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc, Expr *DepModifier,
OpenMPDependClauseKind DepKind,
SourceLocation DepLoc, SourceLocation ColonLoc,
ArrayRef<Expr *> VL, unsigned NumLoops);
/// Creates an empty clause with \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
/// \param NumLoops Number of loops that is associated with this depend
/// clause.
static OMPDependClause *CreateEmpty(const ASTContext &C, unsigned N,
unsigned NumLoops);
/// Get dependency type.
OpenMPDependClauseKind getDependencyKind() const { return DepKind; }
/// Return optional depend modifier.
Expr *getModifier();
const Expr *getModifier() const {
return const_cast<OMPDependClause *>(this)->getModifier();
}
/// Get dependency type location.
SourceLocation getDependencyLoc() const { return DepLoc; }
/// Get colon location.
SourceLocation getColonLoc() const { return ColonLoc; }
/// Get number of loops associated with the clause.
unsigned getNumLoops() const { return NumLoops; }
/// Set the loop data for the depend clauses with 'sink|source' kind of
/// dependency.
void setLoopData(unsigned NumLoop, Expr *Cnt);
/// Get the loop data.
Expr *getLoopData(unsigned NumLoop);
const Expr *getLoopData(unsigned NumLoop) const;
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPDependClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_depend;
}
};
/// This represents 'device' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp target device(a)
/// \endcode
/// In this example directive '#pragma omp target' has clause 'device'
/// with single expression 'a'.
class OMPDeviceClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Device clause modifier.
OpenMPDeviceClauseModifier Modifier = OMPC_DEVICE_unknown;
/// Location of the modifier.
SourceLocation ModifierLoc;
/// Device number.
Stmt *Device = nullptr;
/// Set the device number.
///
/// \param E Device number.
void setDevice(Expr *E) { Device = E; }
/// Sets modifier.
void setModifier(OpenMPDeviceClauseModifier M) { Modifier = M; }
/// Setst modifier location.
void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; }
public:
/// Build 'device' clause.
///
/// \param Modifier Clause modifier.
/// \param E Expression associated with this clause.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param ModifierLoc Modifier location.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPDeviceClause(OpenMPDeviceClauseModifier Modifier, Expr *E, Stmt *HelperE,
OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ModifierLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_device, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Modifier(Modifier),
ModifierLoc(ModifierLoc), Device(E) {
setPreInitStmt(HelperE, CaptureRegion);
}
/// Build an empty clause.
OMPDeviceClause()
: OMPClause(llvm::omp::OMPC_device, SourceLocation(), SourceLocation()),
OMPClauseWithPreInit(this) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Return device number.
Expr *getDevice() { return cast<Expr>(Device); }
/// Return device number.
Expr *getDevice() const { return cast<Expr>(Device); }
/// Gets modifier.
OpenMPDeviceClauseModifier getModifier() const { return Modifier; }
/// Gets modifier location.
SourceLocation getModifierLoc() const { return ModifierLoc; }
child_range children() { return child_range(&Device, &Device + 1); }
const_child_range children() const {
return const_child_range(&Device, &Device + 1);
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_device;
}
};
/// This represents 'threads' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp ordered threads
/// \endcode
/// In this example directive '#pragma omp ordered' has simple 'threads' clause.
class OMPThreadsClause : public OMPClause {
public:
/// Build 'threads' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_threads, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPThreadsClause()
: OMPClause(llvm::omp::OMPC_threads, SourceLocation(), SourceLocation()) {
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_threads;
}
};
/// This represents 'simd' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp ordered simd
/// \endcode
/// In this example directive '#pragma omp ordered' has simple 'simd' clause.
class OMPSIMDClause : public OMPClause {
public:
/// Build 'simd' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_simd, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPSIMDClause()
: OMPClause(llvm::omp::OMPC_simd, SourceLocation(), SourceLocation()) {}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_simd;
}
};
/// Struct that defines common infrastructure to handle mappable
/// expressions used in OpenMP clauses.
class OMPClauseMappableExprCommon {
public:
/// Class that represents a component of a mappable expression. E.g.
/// for an expression S.a, the first component is a declaration reference
/// expression associated with 'S' and the second is a member expression
/// associated with the field declaration 'a'. If the expression is an array
/// subscript it may not have any associated declaration. In that case the
/// associated declaration is set to nullptr.
class MappableComponent {
/// Expression associated with the component.
Expr *AssociatedExpression = nullptr;
/// Declaration associated with the declaration. If the component does
/// not have a declaration (e.g. array subscripts or section), this is set
/// to nullptr.
ValueDecl *AssociatedDeclaration = nullptr;
public:
explicit MappableComponent() = default;
explicit MappableComponent(Expr *AssociatedExpression,
ValueDecl *AssociatedDeclaration)
: AssociatedExpression(AssociatedExpression),
AssociatedDeclaration(
AssociatedDeclaration
? cast<ValueDecl>(AssociatedDeclaration->getCanonicalDecl())
: nullptr) {}
Expr *getAssociatedExpression() const { return AssociatedExpression; }
ValueDecl *getAssociatedDeclaration() const {
return AssociatedDeclaration;
}
};
// List of components of an expression. This first one is the whole
// expression and the last one is the base expression.
using MappableExprComponentList = SmallVector<MappableComponent, 8>;
using MappableExprComponentListRef = ArrayRef<MappableComponent>;
// List of all component lists associated to the same base declaration.
// E.g. if both 'S.a' and 'S.b' are a mappable expressions, each will have
// their component list but the same base declaration 'S'.
using MappableExprComponentLists = SmallVector<MappableExprComponentList, 8>;
using MappableExprComponentListsRef = ArrayRef<MappableExprComponentList>;
protected:
// Return the total number of elements in a list of component lists.
static unsigned
getComponentsTotalNumber(MappableExprComponentListsRef ComponentLists);
// Return the total number of elements in a list of declarations. All
// declarations are expected to be canonical.
static unsigned
getUniqueDeclarationsTotalNumber(ArrayRef<const ValueDecl *> Declarations);
};
/// This structure contains all sizes needed for by an
/// OMPMappableExprListClause.
struct OMPMappableExprListSizeTy {
/// Number of expressions listed.
unsigned NumVars;
/// Number of unique base declarations.
unsigned NumUniqueDeclarations;
/// Number of component lists.
unsigned NumComponentLists;
/// Total number of expression components.
unsigned NumComponents;
OMPMappableExprListSizeTy() = default;
OMPMappableExprListSizeTy(unsigned NumVars, unsigned NumUniqueDeclarations,
unsigned NumComponentLists, unsigned NumComponents)
: NumVars(NumVars), NumUniqueDeclarations(NumUniqueDeclarations),
NumComponentLists(NumComponentLists), NumComponents(NumComponents) {}
};
/// This represents clauses with a list of expressions that are mappable.
/// Examples of these clauses are 'map' in
/// '#pragma omp target [enter|exit] [data]...' directives, and 'to' and 'from
/// in '#pragma omp target update...' directives.
template <class T>
class OMPMappableExprListClause : public OMPVarListClause<T>,
public OMPClauseMappableExprCommon {
friend class OMPClauseReader;
/// Number of unique declarations in this clause.
unsigned NumUniqueDeclarations;
/// Number of component lists in this clause.
unsigned NumComponentLists;
/// Total number of components in this clause.
unsigned NumComponents;
/// C++ nested name specifier for the associated user-defined mapper.
NestedNameSpecifierLoc MapperQualifierLoc;
/// The associated user-defined mapper identifier information.
DeclarationNameInfo MapperIdInfo;
protected:
/// Build a clause for \a NumUniqueDeclarations declarations, \a
/// NumComponentLists total component lists, and \a NumComponents total
/// components.
///
/// \param K Kind of the clause.
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
/// \param MapperQualifierLocPtr C++ nested name specifier for the associated
/// user-defined mapper.
/// \param MapperIdInfoPtr The identifier of associated user-defined mapper.
OMPMappableExprListClause(
OpenMPClauseKind K, const OMPVarListLocTy &Locs,
const OMPMappableExprListSizeTy &Sizes,
NestedNameSpecifierLoc *MapperQualifierLocPtr = nullptr,
DeclarationNameInfo *MapperIdInfoPtr = nullptr)
: OMPVarListClause<T>(K, Locs.StartLoc, Locs.LParenLoc, Locs.EndLoc,
Sizes.NumVars),
NumUniqueDeclarations(Sizes.NumUniqueDeclarations),
NumComponentLists(Sizes.NumComponentLists),
NumComponents(Sizes.NumComponents) {
if (MapperQualifierLocPtr)
MapperQualifierLoc = *MapperQualifierLocPtr;
if (MapperIdInfoPtr)
MapperIdInfo = *MapperIdInfoPtr;
}
/// Get the unique declarations that are in the trailing objects of the
/// class.
MutableArrayRef<ValueDecl *> getUniqueDeclsRef() {
return MutableArrayRef<ValueDecl *>(
static_cast<T *>(this)->template getTrailingObjects<ValueDecl *>(),
NumUniqueDeclarations);
}
/// Get the unique declarations that are in the trailing objects of the
/// class.
ArrayRef<ValueDecl *> getUniqueDeclsRef() const {
return ArrayRef<ValueDecl *>(
static_cast<const T *>(this)
->template getTrailingObjects<ValueDecl *>(),
NumUniqueDeclarations);
}
/// Set the unique declarations that are in the trailing objects of the
/// class.
void setUniqueDecls(ArrayRef<ValueDecl *> UDs) {
assert(UDs.size() == NumUniqueDeclarations &&
"Unexpected amount of unique declarations.");
std::copy(UDs.begin(), UDs.end(), getUniqueDeclsRef().begin());
}
/// Get the number of lists per declaration that are in the trailing
/// objects of the class.
MutableArrayRef<unsigned> getDeclNumListsRef() {
return MutableArrayRef<unsigned>(
static_cast<T *>(this)->template getTrailingObjects<unsigned>(),
NumUniqueDeclarations);
}
/// Get the number of lists per declaration that are in the trailing
/// objects of the class.
ArrayRef<unsigned> getDeclNumListsRef() const {
return ArrayRef<unsigned>(
static_cast<const T *>(this)->template getTrailingObjects<unsigned>(),
NumUniqueDeclarations);
}
/// Set the number of lists per declaration that are in the trailing
/// objects of the class.
void setDeclNumLists(ArrayRef<unsigned> DNLs) {
assert(DNLs.size() == NumUniqueDeclarations &&
"Unexpected amount of list numbers.");
std::copy(DNLs.begin(), DNLs.end(), getDeclNumListsRef().begin());
}
/// Get the cumulative component lists sizes that are in the trailing
/// objects of the class. They are appended after the number of lists.
MutableArrayRef<unsigned> getComponentListSizesRef() {
return MutableArrayRef<unsigned>(
static_cast<T *>(this)->template getTrailingObjects<unsigned>() +
NumUniqueDeclarations,
NumComponentLists);
}
/// Get the cumulative component lists sizes that are in the trailing
/// objects of the class. They are appended after the number of lists.
ArrayRef<unsigned> getComponentListSizesRef() const {
return ArrayRef<unsigned>(
static_cast<const T *>(this)->template getTrailingObjects<unsigned>() +
NumUniqueDeclarations,
NumComponentLists);
}
/// Set the cumulative component lists sizes that are in the trailing
/// objects of the class.
void setComponentListSizes(ArrayRef<unsigned> CLSs) {
assert(CLSs.size() == NumComponentLists &&
"Unexpected amount of component lists.");
std::copy(CLSs.begin(), CLSs.end(), getComponentListSizesRef().begin());
}
/// Get the components that are in the trailing objects of the class.
MutableArrayRef<MappableComponent> getComponentsRef() {
return MutableArrayRef<MappableComponent>(
static_cast<T *>(this)
->template getTrailingObjects<MappableComponent>(),
NumComponents);
}
/// Get the components that are in the trailing objects of the class.
ArrayRef<MappableComponent> getComponentsRef() const {
return ArrayRef<MappableComponent>(
static_cast<const T *>(this)
->template getTrailingObjects<MappableComponent>(),
NumComponents);
}
/// Set the components that are in the trailing objects of the class.
/// This requires the list sizes so that it can also fill the original
/// expressions, which are the first component of each list.
void setComponents(ArrayRef<MappableComponent> Components,
ArrayRef<unsigned> CLSs) {
assert(Components.size() == NumComponents &&
"Unexpected amount of component lists.");
assert(CLSs.size() == NumComponentLists &&
"Unexpected amount of list sizes.");
std::copy(Components.begin(), Components.end(), getComponentsRef().begin());
}
/// Fill the clause information from the list of declarations and
/// associated component lists.
void setClauseInfo(ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists) {
// Perform some checks to make sure the data sizes are consistent with the
// information available when the clause was created.
assert(getUniqueDeclarationsTotalNumber(Declarations) ==
NumUniqueDeclarations &&
"Unexpected number of mappable expression info entries!");
assert(getComponentsTotalNumber(ComponentLists) == NumComponents &&
"Unexpected total number of components!");
assert(Declarations.size() == ComponentLists.size() &&
"Declaration and component lists size is not consistent!");
assert(Declarations.size() == NumComponentLists &&
"Unexpected declaration and component lists size!");
// Organize the components by declaration and retrieve the original
// expression. Original expressions are always the first component of the
// mappable component list.
llvm::MapVector<ValueDecl *, SmallVector<MappableExprComponentListRef, 8>>
ComponentListMap;
{
auto CI = ComponentLists.begin();
for (auto DI = Declarations.begin(), DE = Declarations.end(); DI != DE;
++DI, ++CI) {
assert(!CI->empty() && "Invalid component list!");
ComponentListMap[*DI].push_back(*CI);
}
}
// Iterators of the target storage.
auto UniqueDeclarations = getUniqueDeclsRef();
auto UDI = UniqueDeclarations.begin();
auto DeclNumLists = getDeclNumListsRef();
auto DNLI = DeclNumLists.begin();
auto ComponentListSizes = getComponentListSizesRef();
auto CLSI = ComponentListSizes.begin();
auto Components = getComponentsRef();
auto CI = Components.begin();
// Variable to compute the accumulation of the number of components.
unsigned PrevSize = 0u;
// Scan all the declarations and associated component lists.
for (auto &M : ComponentListMap) {
// The declaration.
auto *D = M.first;
// The component lists.
auto CL = M.second;
// Initialize the entry.
*UDI = D;
++UDI;
*DNLI = CL.size();
++DNLI;
// Obtain the cumulative sizes and concatenate all the components in the
// reserved storage.
for (auto C : CL) {
// Accumulate with the previous size.
PrevSize += C.size();
// Save the size.
*CLSI = PrevSize;
++CLSI;
// Append components after the current components iterator.
CI = std::copy(C.begin(), C.end(), CI);
}
}
}
/// Set the nested name specifier of associated user-defined mapper.
void setMapperQualifierLoc(NestedNameSpecifierLoc NNSL) {
MapperQualifierLoc = NNSL;
}
/// Set the name of associated user-defined mapper.
void setMapperIdInfo(DeclarationNameInfo MapperId) {
MapperIdInfo = MapperId;
}
/// Get the user-defined mapper references that are in the trailing objects of
/// the class.
MutableArrayRef<Expr *> getUDMapperRefs() {
return llvm::makeMutableArrayRef<Expr *>(
static_cast<T *>(this)->template getTrailingObjects<Expr *>() +
OMPVarListClause<T>::varlist_size(),
OMPVarListClause<T>::varlist_size());
}
/// Get the user-defined mappers references that are in the trailing objects
/// of the class.
ArrayRef<Expr *> getUDMapperRefs() const {
return llvm::makeArrayRef<Expr *>(
static_cast<T *>(this)->template getTrailingObjects<Expr *>() +
OMPVarListClause<T>::varlist_size(),
OMPVarListClause<T>::varlist_size());
}
/// Set the user-defined mappers that are in the trailing objects of the
/// class.
void setUDMapperRefs(ArrayRef<Expr *> DMDs) {
assert(DMDs.size() == OMPVarListClause<T>::varlist_size() &&
"Unexpected number of user-defined mappers.");
std::copy(DMDs.begin(), DMDs.end(), getUDMapperRefs().begin());
}
public:
/// Return the number of unique base declarations in this clause.
unsigned getUniqueDeclarationsNum() const { return NumUniqueDeclarations; }
/// Return the number of lists derived from the clause expressions.
unsigned getTotalComponentListNum() const { return NumComponentLists; }
/// Return the total number of components in all lists derived from the
/// clause.
unsigned getTotalComponentsNum() const { return NumComponents; }
/// Gets the nested name specifier for associated user-defined mapper.
NestedNameSpecifierLoc getMapperQualifierLoc() const {
return MapperQualifierLoc;
}
/// Gets the name info for associated user-defined mapper.
const DeclarationNameInfo &getMapperIdInfo() const { return MapperIdInfo; }
/// Iterator that browse the components by lists. It also allows
/// browsing components of a single declaration.
class const_component_lists_iterator
: public llvm::iterator_adaptor_base<
const_component_lists_iterator,
MappableExprComponentListRef::const_iterator,
std::forward_iterator_tag, MappableComponent, ptrdiff_t,
MappableComponent, MappableComponent> {
// The declaration the iterator currently refers to.
ArrayRef<ValueDecl *>::iterator DeclCur;
// The list number associated with the current declaration.
ArrayRef<unsigned>::iterator NumListsCur;
// Remaining lists for the current declaration.
unsigned RemainingLists = 0;
// The cumulative size of the previous list, or zero if there is no previous
// list.
unsigned PrevListSize = 0;
// The cumulative sizes of the current list - it will delimit the remaining
// range of interest.
ArrayRef<unsigned>::const_iterator ListSizeCur;
ArrayRef<unsigned>::const_iterator ListSizeEnd;
// Iterator to the end of the components storage.
MappableExprComponentListRef::const_iterator End;
public:
/// Construct an iterator that scans all lists.
explicit const_component_lists_iterator(
ArrayRef<ValueDecl *> UniqueDecls, ArrayRef<unsigned> DeclsListNum,
ArrayRef<unsigned> CumulativeListSizes,
MappableExprComponentListRef Components)
: const_component_lists_iterator::iterator_adaptor_base(
Components.begin()),
DeclCur(UniqueDecls.begin()), NumListsCur(DeclsListNum.begin()),
ListSizeCur(CumulativeListSizes.begin()),
ListSizeEnd(CumulativeListSizes.end()), End(Components.end()) {
assert(UniqueDecls.size() == DeclsListNum.size() &&
"Inconsistent number of declarations and list sizes!");
if (!DeclsListNum.empty())
RemainingLists = *NumListsCur;
}
/// Construct an iterator that scan lists for a given declaration \a
/// Declaration.
explicit const_component_lists_iterator(
const ValueDecl *Declaration, ArrayRef<ValueDecl *> UniqueDecls,
ArrayRef<unsigned> DeclsListNum, ArrayRef<unsigned> CumulativeListSizes,
MappableExprComponentListRef Components)
: const_component_lists_iterator(UniqueDecls, DeclsListNum,
CumulativeListSizes, Components) {
// Look for the desired declaration. While we are looking for it, we
// update the state so that we know the component where a given list
// starts.
for (; DeclCur != UniqueDecls.end(); ++DeclCur, ++NumListsCur) {
if (*DeclCur == Declaration)
break;
assert(*NumListsCur > 0 && "No lists associated with declaration??");
// Skip the lists associated with the current declaration, but save the
// last list size that was skipped.
std::advance(ListSizeCur, *NumListsCur - 1);
PrevListSize = *ListSizeCur;
++ListSizeCur;
}
// If we didn't find any declaration, advance the iterator to after the
// last component and set remaining lists to zero.
if (ListSizeCur == CumulativeListSizes.end()) {
this->I = End;
RemainingLists = 0u;
return;
}
// Set the remaining lists with the total number of lists of the current
// declaration.
RemainingLists = *NumListsCur;
// Adjust the list size end iterator to the end of the relevant range.
ListSizeEnd = ListSizeCur;
std::advance(ListSizeEnd, RemainingLists);
// Given that the list sizes are cumulative, the index of the component
// that start the list is the size of the previous list.
std::advance(this->I, PrevListSize);
}
// Return the array with the current list. The sizes are cumulative, so the
// array size is the difference between the current size and previous one.
std::pair<const ValueDecl *, MappableExprComponentListRef>
operator*() const {
assert(ListSizeCur != ListSizeEnd && "Invalid iterator!");
return std::make_pair(
*DeclCur,
MappableExprComponentListRef(&*this->I, *ListSizeCur - PrevListSize));
}
std::pair<const ValueDecl *, MappableExprComponentListRef>
operator->() const {
return **this;
}
// Skip the components of the current list.
const_component_lists_iterator &operator++() {
assert(ListSizeCur != ListSizeEnd && RemainingLists &&
"Invalid iterator!");
// If we don't have more lists just skip all the components. Otherwise,
// advance the iterator by the number of components in the current list.
if (std::next(ListSizeCur) == ListSizeEnd) {
this->I = End;
RemainingLists = 0;
} else {
std::advance(this->I, *ListSizeCur - PrevListSize);
PrevListSize = *ListSizeCur;
// We are done with a declaration, move to the next one.
if (!(--RemainingLists)) {
++DeclCur;
++NumListsCur;
RemainingLists = *NumListsCur;
assert(RemainingLists && "No lists in the following declaration??");
}
}
++ListSizeCur;
return *this;
}
};
using const_component_lists_range =
llvm::iterator_range<const_component_lists_iterator>;
/// Iterators for all component lists.
const_component_lists_iterator component_lists_begin() const {
return const_component_lists_iterator(
getUniqueDeclsRef(), getDeclNumListsRef(), getComponentListSizesRef(),
getComponentsRef());
}
const_component_lists_iterator component_lists_end() const {
return const_component_lists_iterator(
ArrayRef<ValueDecl *>(), ArrayRef<unsigned>(), ArrayRef<unsigned>(),
MappableExprComponentListRef(getComponentsRef().end(),
getComponentsRef().end()));
}
const_component_lists_range component_lists() const {
return {component_lists_begin(), component_lists_end()};
}
/// Iterators for component lists associated with the provided
/// declaration.
const_component_lists_iterator
decl_component_lists_begin(const ValueDecl *VD) const {
return const_component_lists_iterator(
VD, getUniqueDeclsRef(), getDeclNumListsRef(),
getComponentListSizesRef(), getComponentsRef());
}
const_component_lists_iterator decl_component_lists_end() const {
return component_lists_end();
}
const_component_lists_range decl_component_lists(const ValueDecl *VD) const {
return {decl_component_lists_begin(VD), decl_component_lists_end()};
}
/// Iterators to access all the declarations, number of lists, list sizes, and
/// components.
using const_all_decls_iterator = ArrayRef<ValueDecl *>::iterator;
using const_all_decls_range = llvm::iterator_range<const_all_decls_iterator>;
const_all_decls_range all_decls() const {
auto A = getUniqueDeclsRef();
return const_all_decls_range(A.begin(), A.end());
}
using const_all_num_lists_iterator = ArrayRef<unsigned>::iterator;
using const_all_num_lists_range =
llvm::iterator_range<const_all_num_lists_iterator>;
const_all_num_lists_range all_num_lists() const {
auto A = getDeclNumListsRef();
return const_all_num_lists_range(A.begin(), A.end());
}
using const_all_lists_sizes_iterator = ArrayRef<unsigned>::iterator;
using const_all_lists_sizes_range =
llvm::iterator_range<const_all_lists_sizes_iterator>;
const_all_lists_sizes_range all_lists_sizes() const {
auto A = getComponentListSizesRef();
return const_all_lists_sizes_range(A.begin(), A.end());
}
using const_all_components_iterator = ArrayRef<MappableComponent>::iterator;
using const_all_components_range =
llvm::iterator_range<const_all_components_iterator>;
const_all_components_range all_components() const {
auto A = getComponentsRef();
return const_all_components_range(A.begin(), A.end());
}
using mapperlist_iterator = MutableArrayRef<Expr *>::iterator;
using mapperlist_const_iterator = ArrayRef<const Expr *>::iterator;
using mapperlist_range = llvm::iterator_range<mapperlist_iterator>;
using mapperlist_const_range =
llvm::iterator_range<mapperlist_const_iterator>;
mapperlist_iterator mapperlist_begin() { return getUDMapperRefs().begin(); }
mapperlist_iterator mapperlist_end() { return getUDMapperRefs().end(); }
mapperlist_const_iterator mapperlist_begin() const {
return getUDMapperRefs().begin();
}
mapperlist_const_iterator mapperlist_end() const {
return getUDMapperRefs().end();
}
mapperlist_range mapperlists() {
return mapperlist_range(mapperlist_begin(), mapperlist_end());
}
mapperlist_const_range mapperlists() const {
return mapperlist_const_range(mapperlist_begin(), mapperlist_end());
}
};
/// This represents clause 'map' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp target map(a,b)
/// \endcode
/// In this example directive '#pragma omp target' has clause 'map'
/// with the variables 'a' and 'b'.
class OMPMapClause final : public OMPMappableExprListClause<OMPMapClause>,
private llvm::TrailingObjects<
OMPMapClause, Expr *, ValueDecl *, unsigned,
OMPClauseMappableExprCommon::MappableComponent> {
friend class OMPClauseReader;
friend OMPMappableExprListClause;
friend OMPVarListClause;
friend TrailingObjects;
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
size_t numTrailingObjects(OverloadToken<Expr *>) const {
// There are varlist_size() of expressions, and varlist_size() of
// user-defined mappers.
return 2 * varlist_size();
}
size_t numTrailingObjects(OverloadToken<ValueDecl *>) const {
return getUniqueDeclarationsNum();
}
size_t numTrailingObjects(OverloadToken<unsigned>) const {
return getUniqueDeclarationsNum() + getTotalComponentListNum();
}
private:
/// Map-type-modifiers for the 'map' clause.
OpenMPMapModifierKind MapTypeModifiers[NumberOfOMPMapClauseModifiers] = {
OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
OMPC_MAP_MODIFIER_unknown};
/// Location of map-type-modifiers for the 'map' clause.
SourceLocation MapTypeModifiersLoc[NumberOfOMPMapClauseModifiers];
/// Map type for the 'map' clause.
OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
/// Is this an implicit map type or not.
bool MapTypeIsImplicit = false;
/// Location of the map type.
SourceLocation MapLoc;
/// Colon location.
SourceLocation ColonLoc;
/// Build a clause for \a NumVars listed expressions, \a
/// NumUniqueDeclarations declarations, \a NumComponentLists total component
/// lists, and \a NumComponents total expression components.
///
/// \param MapModifiers Map-type-modifiers.
/// \param MapModifiersLoc Locations of map-type-modifiers.
/// \param MapperQualifierLoc C++ nested name specifier for the associated
/// user-defined mapper.
/// \param MapperIdInfo The identifier of associated user-defined mapper.
/// \param MapType Map type.
/// \param MapTypeIsImplicit Map type is inferred implicitly.
/// \param MapLoc Location of the map type.
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPMapClause(ArrayRef<OpenMPMapModifierKind> MapModifiers,
ArrayRef<SourceLocation> MapModifiersLoc,
NestedNameSpecifierLoc MapperQualifierLoc,
DeclarationNameInfo MapperIdInfo,
OpenMPMapClauseKind MapType, bool MapTypeIsImplicit,
SourceLocation MapLoc, const OMPVarListLocTy &Locs,
const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_map, Locs, Sizes,
&MapperQualifierLoc, &MapperIdInfo),
MapType(MapType), MapTypeIsImplicit(MapTypeIsImplicit), MapLoc(MapLoc) {
assert(llvm::array_lengthof(MapTypeModifiers) == MapModifiers.size() &&
"Unexpected number of map type modifiers.");
llvm::copy(MapModifiers, std::begin(MapTypeModifiers));
assert(llvm::array_lengthof(MapTypeModifiersLoc) ==
MapModifiersLoc.size() &&
"Unexpected number of map type modifier locations.");
llvm::copy(MapModifiersLoc, std::begin(MapTypeModifiersLoc));
}
/// Build an empty clause.
///
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPMapClause(const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_map, OMPVarListLocTy(),
Sizes) {}
/// Set map-type-modifier for the clause.
///
/// \param I index for map-type-modifier.
/// \param T map-type-modifier for the clause.
void setMapTypeModifier(unsigned I, OpenMPMapModifierKind T) {
assert(I < NumberOfOMPMapClauseModifiers &&
"Unexpected index to store map type modifier, exceeds array size.");
MapTypeModifiers[I] = T;
}
/// Set location for the map-type-modifier.
///
/// \param I index for map-type-modifier location.
/// \param TLoc map-type-modifier location.
void setMapTypeModifierLoc(unsigned I, SourceLocation TLoc) {
assert(I < NumberOfOMPMapClauseModifiers &&
"Index to store map type modifier location exceeds array size.");
MapTypeModifiersLoc[I] = TLoc;
}
/// Set type for the clause.
///
/// \param T Type for the clause.
void setMapType(OpenMPMapClauseKind T) { MapType = T; }
/// Set type location.
///
/// \param TLoc Type location.
void setMapLoc(SourceLocation TLoc) { MapLoc = TLoc; }
/// Set colon location.
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Vars The original expression used in the clause.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
/// \param UDMapperRefs References to user-defined mappers associated with
/// expressions used in the clause.
/// \param MapModifiers Map-type-modifiers.
/// \param MapModifiersLoc Location of map-type-modifiers.
/// \param UDMQualifierLoc C++ nested name specifier for the associated
/// user-defined mapper.
/// \param MapperId The identifier of associated user-defined mapper.
/// \param Type Map type.
/// \param TypeIsImplicit Map type is inferred implicitly.
/// \param TypeLoc Location of the map type.
static OMPMapClause *
Create(const ASTContext &C, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists,
ArrayRef<Expr *> UDMapperRefs,
ArrayRef<OpenMPMapModifierKind> MapModifiers,
ArrayRef<SourceLocation> MapModifiersLoc,
NestedNameSpecifierLoc UDMQualifierLoc, DeclarationNameInfo MapperId,
OpenMPMapClauseKind Type, bool TypeIsImplicit, SourceLocation TypeLoc);
/// Creates an empty clause with the place for \a NumVars original
/// expressions, \a NumUniqueDeclarations declarations, \NumComponentLists
/// lists, and \a NumComponents expression components.
///
/// \param C AST context.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
static OMPMapClause *CreateEmpty(const ASTContext &C,
const OMPMappableExprListSizeTy &Sizes);
/// Fetches mapping kind for the clause.
OpenMPMapClauseKind getMapType() const LLVM_READONLY { return MapType; }
/// Is this an implicit map type?
/// We have to capture 'IsMapTypeImplicit' from the parser for more
/// informative error messages. It helps distinguish map(r) from
/// map(tofrom: r), which is important to print more helpful error
/// messages for some target directives.
bool isImplicitMapType() const LLVM_READONLY { return MapTypeIsImplicit; }
/// Fetches the map-type-modifier at 'Cnt' index of array of modifiers.
///
/// \param Cnt index for map-type-modifier.
OpenMPMapModifierKind getMapTypeModifier(unsigned Cnt) const LLVM_READONLY {
assert(Cnt < NumberOfOMPMapClauseModifiers &&
"Requested modifier exceeds the total number of modifiers.");
return MapTypeModifiers[Cnt];
}
/// Fetches the map-type-modifier location at 'Cnt' index of array of
/// modifiers' locations.
///
/// \param Cnt index for map-type-modifier location.
SourceLocation getMapTypeModifierLoc(unsigned Cnt) const LLVM_READONLY {
assert(Cnt < NumberOfOMPMapClauseModifiers &&
"Requested modifier location exceeds total number of modifiers.");
return MapTypeModifiersLoc[Cnt];
}
/// Fetches ArrayRef of map-type-modifiers.
ArrayRef<OpenMPMapModifierKind> getMapTypeModifiers() const LLVM_READONLY {
return llvm::makeArrayRef(MapTypeModifiers);
}
/// Fetches ArrayRef of location of map-type-modifiers.
ArrayRef<SourceLocation> getMapTypeModifiersLoc() const LLVM_READONLY {
return llvm::makeArrayRef(MapTypeModifiersLoc);
}
/// Fetches location of clause mapping kind.
SourceLocation getMapLoc() const LLVM_READONLY { return MapLoc; }
/// Get colon location.
SourceLocation getColonLoc() const { return ColonLoc; }
child_range children() {
return child_range(
reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPMapClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
if (MapType == OMPC_MAP_to || MapType == OMPC_MAP_tofrom)
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
auto Children = const_cast<OMPMapClause *>(this)->used_children();
return const_child_range(Children.begin(), Children.end());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_map;
}
};
/// This represents 'num_teams' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp teams num_teams(n)
/// \endcode
/// In this example directive '#pragma omp teams' has clause 'num_teams'
/// with single expression 'n'.
class OMPNumTeamsClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// NumTeams number.
Stmt *NumTeams = nullptr;
/// Set the NumTeams number.
///
/// \param E NumTeams number.
void setNumTeams(Expr *E) { NumTeams = E; }
public:
/// Build 'num_teams' clause.
///
/// \param E Expression associated with this clause.
/// \param HelperE Helper Expression associated with this clause.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPNumTeamsClause(Expr *E, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_num_teams, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumTeams(E) {
setPreInitStmt(HelperE, CaptureRegion);
}
/// Build an empty clause.
OMPNumTeamsClause()
: OMPClause(llvm::omp::OMPC_num_teams, SourceLocation(),
SourceLocation()),
OMPClauseWithPreInit(this) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Return NumTeams number.
Expr *getNumTeams() { return cast<Expr>(NumTeams); }
/// Return NumTeams number.
Expr *getNumTeams() const { return cast<Expr>(NumTeams); }
child_range children() { return child_range(&NumTeams, &NumTeams + 1); }
const_child_range children() const {
return const_child_range(&NumTeams, &NumTeams + 1);
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_num_teams;
}
};
/// This represents 'thread_limit' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp teams thread_limit(n)
/// \endcode
/// In this example directive '#pragma omp teams' has clause 'thread_limit'
/// with single expression 'n'.
class OMPThreadLimitClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// ThreadLimit number.
Stmt *ThreadLimit = nullptr;
/// Set the ThreadLimit number.
///
/// \param E ThreadLimit number.
void setThreadLimit(Expr *E) { ThreadLimit = E; }
public:
/// Build 'thread_limit' clause.
///
/// \param E Expression associated with this clause.
/// \param HelperE Helper Expression associated with this clause.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPThreadLimitClause(Expr *E, Stmt *HelperE,
OpenMPDirectiveKind CaptureRegion,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_thread_limit, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc), ThreadLimit(E) {
setPreInitStmt(HelperE, CaptureRegion);
}
/// Build an empty clause.
OMPThreadLimitClause()
: OMPClause(llvm::omp::OMPC_thread_limit, SourceLocation(),
SourceLocation()),
OMPClauseWithPreInit(this) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Return ThreadLimit number.
Expr *getThreadLimit() { return cast<Expr>(ThreadLimit); }
/// Return ThreadLimit number.
Expr *getThreadLimit() const { return cast<Expr>(ThreadLimit); }
child_range children() { return child_range(&ThreadLimit, &ThreadLimit + 1); }
const_child_range children() const {
return const_child_range(&ThreadLimit, &ThreadLimit + 1);
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_thread_limit;
}
};
/// This represents 'priority' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp task priority(n)
/// \endcode
/// In this example directive '#pragma omp teams' has clause 'priority' with
/// single expression 'n'.
class OMPPriorityClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Priority number.
Stmt *Priority = nullptr;
/// Set the Priority number.
///
/// \param E Priority number.
void setPriority(Expr *E) { Priority = E; }
public:
/// Build 'priority' clause.
///
/// \param Priority Expression associated with this clause.
/// \param HelperPriority Helper priority for the construct.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPPriorityClause(Expr *Priority, Stmt *HelperPriority,
OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_priority, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Priority(Priority) {
setPreInitStmt(HelperPriority, CaptureRegion);
}
/// Build an empty clause.
OMPPriorityClause()
: OMPClause(llvm::omp::OMPC_priority, SourceLocation(), SourceLocation()),
OMPClauseWithPreInit(this) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Return Priority number.
Expr *getPriority() { return cast<Expr>(Priority); }
/// Return Priority number.
Expr *getPriority() const { return cast<Expr>(Priority); }
child_range children() { return child_range(&Priority, &Priority + 1); }
const_child_range children() const {
return const_child_range(&Priority, &Priority + 1);
}
child_range used_children();
const_child_range used_children() const {
auto Children = const_cast<OMPPriorityClause *>(this)->used_children();
return const_child_range(Children.begin(), Children.end());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_priority;
}
};
/// This represents 'grainsize' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp taskloop grainsize(4)
/// \endcode
/// In this example directive '#pragma omp taskloop' has clause 'grainsize'
/// with single expression '4'.
class OMPGrainsizeClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Safe iteration space distance.
Stmt *Grainsize = nullptr;
/// Set safelen.
void setGrainsize(Expr *Size) { Grainsize = Size; }
public:
/// Build 'grainsize' clause.
///
/// \param Size Expression associated with this clause.
/// \param HelperSize Helper grainsize for the construct.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPGrainsizeClause(Expr *Size, Stmt *HelperSize,
OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_grainsize, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Grainsize(Size) {
setPreInitStmt(HelperSize, CaptureRegion);
}
/// Build an empty clause.
explicit OMPGrainsizeClause()
: OMPClause(llvm::omp::OMPC_grainsize, SourceLocation(),
SourceLocation()),
OMPClauseWithPreInit(this) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Return safe iteration space distance.
Expr *getGrainsize() const { return cast_or_null<Expr>(Grainsize); }
child_range children() { return child_range(&Grainsize, &Grainsize + 1); }
const_child_range children() const {
return const_child_range(&Grainsize, &Grainsize + 1);
}
child_range used_children();
const_child_range used_children() const {
auto Children = const_cast<OMPGrainsizeClause *>(this)->used_children();
return const_child_range(Children.begin(), Children.end());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_grainsize;
}
};
/// This represents 'nogroup' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp taskloop nogroup
/// \endcode
/// In this example directive '#pragma omp taskloop' has 'nogroup' clause.
class OMPNogroupClause : public OMPClause {
public:
/// Build 'nogroup' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_nogroup, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPNogroupClause()
: OMPClause(llvm::omp::OMPC_nogroup, SourceLocation(), SourceLocation()) {
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_nogroup;
}
};
/// This represents 'num_tasks' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp taskloop num_tasks(4)
/// \endcode
/// In this example directive '#pragma omp taskloop' has clause 'num_tasks'
/// with single expression '4'.
class OMPNumTasksClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Safe iteration space distance.
Stmt *NumTasks = nullptr;
/// Set safelen.
void setNumTasks(Expr *Size) { NumTasks = Size; }
public:
/// Build 'num_tasks' clause.
///
/// \param Size Expression associated with this clause.
/// \param HelperSize Helper grainsize for the construct.
/// \param CaptureRegion Innermost OpenMP region where expressions in this
/// clause must be captured.
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPNumTasksClause(Expr *Size, Stmt *HelperSize,
OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_num_tasks, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumTasks(Size) {
setPreInitStmt(HelperSize, CaptureRegion);
}
/// Build an empty clause.
explicit OMPNumTasksClause()
: OMPClause(llvm::omp::OMPC_num_tasks, SourceLocation(),
SourceLocation()),
OMPClauseWithPreInit(this) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Return safe iteration space distance.
Expr *getNumTasks() const { return cast_or_null<Expr>(NumTasks); }
child_range children() { return child_range(&NumTasks, &NumTasks + 1); }
const_child_range children() const {
return const_child_range(&NumTasks, &NumTasks + 1);
}
child_range used_children();
const_child_range used_children() const {
auto Children = const_cast<OMPNumTasksClause *>(this)->used_children();
return const_child_range(Children.begin(), Children.end());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_num_tasks;
}
};
/// This represents 'hint' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp critical (name) hint(6)
/// \endcode
/// In this example directive '#pragma omp critical' has name 'name' and clause
/// 'hint' with argument '6'.
class OMPHintClause : public OMPClause {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Hint expression of the 'hint' clause.
Stmt *Hint = nullptr;
/// Set hint expression.
void setHint(Expr *H) { Hint = H; }
public:
/// Build 'hint' clause with expression \a Hint.
///
/// \param Hint Hint expression.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_hint, StartLoc, EndLoc), LParenLoc(LParenLoc),
Hint(Hint) {}
/// Build an empty clause.
OMPHintClause()
: OMPClause(llvm::omp::OMPC_hint, SourceLocation(), SourceLocation()) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Returns number of threads.
Expr *getHint() const { return cast_or_null<Expr>(Hint); }
child_range children() { return child_range(&Hint, &Hint + 1); }
const_child_range children() const {
return const_child_range(&Hint, &Hint + 1);
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_hint;
}
};
/// This represents 'dist_schedule' clause in the '#pragma omp ...'
/// directive.
///
/// \code
/// #pragma omp distribute dist_schedule(static, 3)
/// \endcode
/// In this example directive '#pragma omp distribute' has 'dist_schedule'
/// clause with arguments 'static' and '3'.
class OMPDistScheduleClause : public OMPClause, public OMPClauseWithPreInit {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// A kind of the 'schedule' clause.
OpenMPDistScheduleClauseKind Kind = OMPC_DIST_SCHEDULE_unknown;
/// Start location of the schedule kind in source code.
SourceLocation KindLoc;
/// Location of ',' (if any).
SourceLocation CommaLoc;
/// Chunk size.
Expr *ChunkSize = nullptr;
/// Set schedule kind.
///
/// \param K Schedule kind.
void setDistScheduleKind(OpenMPDistScheduleClauseKind K) { Kind = K; }
/// Sets the location of '('.
///
/// \param Loc Location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Set schedule kind start location.
///
/// \param KLoc Schedule kind location.
void setDistScheduleKindLoc(SourceLocation KLoc) { KindLoc = KLoc; }
/// Set location of ','.
///
/// \param Loc Location of ','.
void setCommaLoc(SourceLocation Loc) { CommaLoc = Loc; }
/// Set chunk size.
///
/// \param E Chunk size.
void setChunkSize(Expr *E) { ChunkSize = E; }
public:
/// Build 'dist_schedule' clause with schedule kind \a Kind and chunk
/// size expression \a ChunkSize.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param KLoc Starting location of the argument.
/// \param CommaLoc Location of ','.
/// \param EndLoc Ending location of the clause.
/// \param Kind DistSchedule kind.
/// \param ChunkSize Chunk size.
/// \param HelperChunkSize Helper chunk size for combined directives.
OMPDistScheduleClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation KLoc, SourceLocation CommaLoc,
SourceLocation EndLoc,
OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
Stmt *HelperChunkSize)
: OMPClause(llvm::omp::OMPC_dist_schedule, StartLoc, EndLoc),
OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Kind(Kind),
KindLoc(KLoc), CommaLoc(CommaLoc), ChunkSize(ChunkSize) {
setPreInitStmt(HelperChunkSize);
}
/// Build an empty clause.
explicit OMPDistScheduleClause()
: OMPClause(llvm::omp::OMPC_dist_schedule, SourceLocation(),
SourceLocation()),
OMPClauseWithPreInit(this) {}
/// Get kind of the clause.
OpenMPDistScheduleClauseKind getDistScheduleKind() const { return Kind; }
/// Get location of '('.
SourceLocation getLParenLoc() { return LParenLoc; }
/// Get kind location.
SourceLocation getDistScheduleKindLoc() { return KindLoc; }
/// Get location of ','.
SourceLocation getCommaLoc() { return CommaLoc; }
/// Get chunk size.
Expr *getChunkSize() { return ChunkSize; }
/// Get chunk size.
const Expr *getChunkSize() const { return ChunkSize; }
child_range children() {
return child_range(reinterpret_cast<Stmt **>(&ChunkSize),
reinterpret_cast<Stmt **>(&ChunkSize) + 1);
}
const_child_range children() const {
auto Children = const_cast<OMPDistScheduleClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_dist_schedule;
}
};
/// This represents 'defaultmap' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp target defaultmap(tofrom: scalar)
/// \endcode
/// In this example directive '#pragma omp target' has 'defaultmap' clause of kind
/// 'scalar' with modifier 'tofrom'.
class OMPDefaultmapClause : public OMPClause {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Modifiers for 'defaultmap' clause.
OpenMPDefaultmapClauseModifier Modifier = OMPC_DEFAULTMAP_MODIFIER_unknown;
/// Locations of modifiers.
SourceLocation ModifierLoc;
/// A kind of the 'defaultmap' clause.
OpenMPDefaultmapClauseKind Kind = OMPC_DEFAULTMAP_unknown;
/// Start location of the defaultmap kind in source code.
SourceLocation KindLoc;
/// Set defaultmap kind.
///
/// \param K Defaultmap kind.
void setDefaultmapKind(OpenMPDefaultmapClauseKind K) { Kind = K; }
/// Set the defaultmap modifier.
///
/// \param M Defaultmap modifier.
void setDefaultmapModifier(OpenMPDefaultmapClauseModifier M) {
Modifier = M;
}
/// Set location of the defaultmap modifier.
void setDefaultmapModifierLoc(SourceLocation Loc) {
ModifierLoc = Loc;
}
/// Sets the location of '('.
///
/// \param Loc Location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Set defaultmap kind start location.
///
/// \param KLoc Defaultmap kind location.
void setDefaultmapKindLoc(SourceLocation KLoc) { KindLoc = KLoc; }
public:
/// Build 'defaultmap' clause with defaultmap kind \a Kind
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param KLoc Starting location of the argument.
/// \param EndLoc Ending location of the clause.
/// \param Kind Defaultmap kind.
/// \param M The modifier applied to 'defaultmap' clause.
/// \param MLoc Location of the modifier
OMPDefaultmapClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation MLoc, SourceLocation KLoc,
SourceLocation EndLoc, OpenMPDefaultmapClauseKind Kind,
OpenMPDefaultmapClauseModifier M)
: OMPClause(llvm::omp::OMPC_defaultmap, StartLoc, EndLoc),
LParenLoc(LParenLoc), Modifier(M), ModifierLoc(MLoc), Kind(Kind),
KindLoc(KLoc) {}
/// Build an empty clause.
explicit OMPDefaultmapClause()
: OMPClause(llvm::omp::OMPC_defaultmap, SourceLocation(),
SourceLocation()) {}
/// Get kind of the clause.
OpenMPDefaultmapClauseKind getDefaultmapKind() const { return Kind; }
/// Get the modifier of the clause.
OpenMPDefaultmapClauseModifier getDefaultmapModifier() const {
return Modifier;
}
/// Get location of '('.
SourceLocation getLParenLoc() { return LParenLoc; }
/// Get kind location.
SourceLocation getDefaultmapKindLoc() { return KindLoc; }
/// Get the modifier location.
SourceLocation getDefaultmapModifierLoc() const {
return ModifierLoc;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_defaultmap;
}
};
/// This represents clause 'to' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp target update to(a,b)
/// \endcode
/// In this example directive '#pragma omp target update' has clause 'to'
/// with the variables 'a' and 'b'.
class OMPToClause final : public OMPMappableExprListClause<OMPToClause>,
private llvm::TrailingObjects<
OMPToClause, Expr *, ValueDecl *, unsigned,
OMPClauseMappableExprCommon::MappableComponent> {
friend class OMPClauseReader;
friend OMPMappableExprListClause;
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a NumVars.
///
/// \param MapperQualifierLoc C++ nested name specifier for the associated
/// user-defined mapper.
/// \param MapperIdInfo The identifier of associated user-defined mapper.
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPToClause(NestedNameSpecifierLoc MapperQualifierLoc,
DeclarationNameInfo MapperIdInfo,
const OMPVarListLocTy &Locs,
const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_to, Locs, Sizes,
&MapperQualifierLoc, &MapperIdInfo) {}
/// Build an empty clause.
///
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPToClause(const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_to, OMPVarListLocTy(),
Sizes) {}
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
size_t numTrailingObjects(OverloadToken<Expr *>) const {
// There are varlist_size() of expressions, and varlist_size() of
// user-defined mappers.
return 2 * varlist_size();
}
size_t numTrailingObjects(OverloadToken<ValueDecl *>) const {
return getUniqueDeclarationsNum();
}
size_t numTrailingObjects(OverloadToken<unsigned>) const {
return getUniqueDeclarationsNum() + getTotalComponentListNum();
}
public:
/// Creates clause with a list of variables \a Vars.
///
/// \param C AST context.
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Vars The original expression used in the clause.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
/// \param UDMapperRefs References to user-defined mappers associated with
/// expressions used in the clause.
/// \param UDMQualifierLoc C++ nested name specifier for the associated
/// user-defined mapper.
/// \param MapperId The identifier of associated user-defined mapper.
static OMPToClause *Create(const ASTContext &C, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> Vars,
ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists,
ArrayRef<Expr *> UDMapperRefs,
NestedNameSpecifierLoc UDMQualifierLoc,
DeclarationNameInfo MapperId);
/// Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
static OMPToClause *CreateEmpty(const ASTContext &C,
const OMPMappableExprListSizeTy &Sizes);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPToClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_to;
}
};
/// This represents clause 'from' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp target update from(a,b)
/// \endcode
/// In this example directive '#pragma omp target update' has clause 'from'
/// with the variables 'a' and 'b'.
class OMPFromClause final
: public OMPMappableExprListClause<OMPFromClause>,
private llvm::TrailingObjects<
OMPFromClause, Expr *, ValueDecl *, unsigned,
OMPClauseMappableExprCommon::MappableComponent> {
friend class OMPClauseReader;
friend OMPMappableExprListClause;
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a NumVars.
///
/// \param MapperQualifierLoc C++ nested name specifier for the associated
/// user-defined mapper.
/// \param MapperIdInfo The identifier of associated user-defined mapper.
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPFromClause(NestedNameSpecifierLoc MapperQualifierLoc,
DeclarationNameInfo MapperIdInfo,
const OMPVarListLocTy &Locs,
const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_from, Locs, Sizes,
&MapperQualifierLoc, &MapperIdInfo) {}
/// Build an empty clause.
///
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPFromClause(const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_from, OMPVarListLocTy(),
Sizes) {}
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
size_t numTrailingObjects(OverloadToken<Expr *>) const {
// There are varlist_size() of expressions, and varlist_size() of
// user-defined mappers.
return 2 * varlist_size();
}
size_t numTrailingObjects(OverloadToken<ValueDecl *>) const {
return getUniqueDeclarationsNum();
}
size_t numTrailingObjects(OverloadToken<unsigned>) const {
return getUniqueDeclarationsNum() + getTotalComponentListNum();
}
public:
/// Creates clause with a list of variables \a Vars.
///
/// \param C AST context.
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Vars The original expression used in the clause.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
/// \param UDMapperRefs References to user-defined mappers associated with
/// expressions used in the clause.
/// \param UDMQualifierLoc C++ nested name specifier for the associated
/// user-defined mapper.
/// \param MapperId The identifier of associated user-defined mapper.
static OMPFromClause *Create(const ASTContext &C, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> Vars,
ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists,
ArrayRef<Expr *> UDMapperRefs,
NestedNameSpecifierLoc UDMQualifierLoc,
DeclarationNameInfo MapperId);
/// Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
static OMPFromClause *CreateEmpty(const ASTContext &C,
const OMPMappableExprListSizeTy &Sizes);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPFromClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_from;
}
};
/// This represents clause 'use_device_ptr' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp target data use_device_ptr(a,b)
/// \endcode
/// In this example directive '#pragma omp target data' has clause
/// 'use_device_ptr' with the variables 'a' and 'b'.
class OMPUseDevicePtrClause final
: public OMPMappableExprListClause<OMPUseDevicePtrClause>,
private llvm::TrailingObjects<
OMPUseDevicePtrClause, Expr *, ValueDecl *, unsigned,
OMPClauseMappableExprCommon::MappableComponent> {
friend class OMPClauseReader;
friend OMPMappableExprListClause;
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a NumVars.
///
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPUseDevicePtrClause(const OMPVarListLocTy &Locs,
const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_use_device_ptr, Locs, Sizes) {
}
/// Build an empty clause.
///
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPUseDevicePtrClause(const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_use_device_ptr,
OMPVarListLocTy(), Sizes) {}
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
size_t numTrailingObjects(OverloadToken<Expr *>) const {
return 3 * varlist_size();
}
size_t numTrailingObjects(OverloadToken<ValueDecl *>) const {
return getUniqueDeclarationsNum();
}
size_t numTrailingObjects(OverloadToken<unsigned>) const {
return getUniqueDeclarationsNum() + getTotalComponentListNum();
}
/// Sets the list of references to private copies with initializers for new
/// private variables.
/// \param VL List of references.
void setPrivateCopies(ArrayRef<Expr *> VL);
/// Gets the list of references to private copies with initializers for new
/// private variables.
MutableArrayRef<Expr *> getPrivateCopies() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivateCopies() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
/// Sets the list of references to initializer variables for new private
/// variables.
/// \param VL List of references.
void setInits(ArrayRef<Expr *> VL);
/// Gets the list of references to initializer variables for new private
/// variables.
MutableArrayRef<Expr *> getInits() {
return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size());
}
ArrayRef<const Expr *> getInits() const {
return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size());
}
public:
/// Creates clause with a list of variables \a Vars.
///
/// \param C AST context.
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Vars The original expression used in the clause.
/// \param PrivateVars Expressions referring to private copies.
/// \param Inits Expressions referring to private copy initializers.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
static OMPUseDevicePtrClause *
Create(const ASTContext &C, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> Vars, ArrayRef<Expr *> PrivateVars,
ArrayRef<Expr *> Inits, ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists);
/// Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
static OMPUseDevicePtrClause *
CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes);
using private_copies_iterator = MutableArrayRef<Expr *>::iterator;
using private_copies_const_iterator = ArrayRef<const Expr *>::iterator;
using private_copies_range = llvm::iterator_range<private_copies_iterator>;
using private_copies_const_range =
llvm::iterator_range<private_copies_const_iterator>;
private_copies_range private_copies() {
return private_copies_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
private_copies_const_range private_copies() const {
return private_copies_const_range(getPrivateCopies().begin(),
getPrivateCopies().end());
}
using inits_iterator = MutableArrayRef<Expr *>::iterator;
using inits_const_iterator = ArrayRef<const Expr *>::iterator;
using inits_range = llvm::iterator_range<inits_iterator>;
using inits_const_range = llvm::iterator_range<inits_const_iterator>;
inits_range inits() {
return inits_range(getInits().begin(), getInits().end());
}
inits_const_range inits() const {
return inits_const_range(getInits().begin(), getInits().end());
}
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPUseDevicePtrClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_use_device_ptr;
}
};
/// This represents clause 'use_device_addr' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp target data use_device_addr(a,b)
/// \endcode
/// In this example directive '#pragma omp target data' has clause
/// 'use_device_addr' with the variables 'a' and 'b'.
class OMPUseDeviceAddrClause final
: public OMPMappableExprListClause<OMPUseDeviceAddrClause>,
private llvm::TrailingObjects<
OMPUseDeviceAddrClause, Expr *, ValueDecl *, unsigned,
OMPClauseMappableExprCommon::MappableComponent> {
friend class OMPClauseReader;
friend OMPMappableExprListClause;
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a NumVars.
///
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPUseDeviceAddrClause(const OMPVarListLocTy &Locs,
const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_use_device_addr, Locs,
Sizes) {}
/// Build an empty clause.
///
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPUseDeviceAddrClause(const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_use_device_addr,
OMPVarListLocTy(), Sizes) {}
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
size_t numTrailingObjects(OverloadToken<Expr *>) const {
return varlist_size();
}
size_t numTrailingObjects(OverloadToken<ValueDecl *>) const {
return getUniqueDeclarationsNum();
}
size_t numTrailingObjects(OverloadToken<unsigned>) const {
return getUniqueDeclarationsNum() + getTotalComponentListNum();
}
public:
/// Creates clause with a list of variables \a Vars.
///
/// \param C AST context.
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Vars The original expression used in the clause.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
static OMPUseDeviceAddrClause *
Create(const ASTContext &C, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists);
/// Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
static OMPUseDeviceAddrClause *
CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPUseDeviceAddrClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_use_device_addr;
}
};
/// This represents clause 'is_device_ptr' in the '#pragma omp ...'
/// directives.
///
/// \code
/// #pragma omp target is_device_ptr(a,b)
/// \endcode
/// In this example directive '#pragma omp target' has clause
/// 'is_device_ptr' with the variables 'a' and 'b'.
class OMPIsDevicePtrClause final
: public OMPMappableExprListClause<OMPIsDevicePtrClause>,
private llvm::TrailingObjects<
OMPIsDevicePtrClause, Expr *, ValueDecl *, unsigned,
OMPClauseMappableExprCommon::MappableComponent> {
friend class OMPClauseReader;
friend OMPMappableExprListClause;
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a NumVars.
///
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPIsDevicePtrClause(const OMPVarListLocTy &Locs,
const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_is_device_ptr, Locs, Sizes) {}
/// Build an empty clause.
///
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
explicit OMPIsDevicePtrClause(const OMPMappableExprListSizeTy &Sizes)
: OMPMappableExprListClause(llvm::omp::OMPC_is_device_ptr,
OMPVarListLocTy(), Sizes) {}
/// Define the sizes of each trailing object array except the last one. This
/// is required for TrailingObjects to work properly.
size_t numTrailingObjects(OverloadToken<Expr *>) const {
return varlist_size();
}
size_t numTrailingObjects(OverloadToken<ValueDecl *>) const {
return getUniqueDeclarationsNum();
}
size_t numTrailingObjects(OverloadToken<unsigned>) const {
return getUniqueDeclarationsNum() + getTotalComponentListNum();
}
public:
/// Creates clause with a list of variables \a Vars.
///
/// \param C AST context.
/// \param Locs Locations needed to build a mappable clause. It includes 1)
/// StartLoc: starting location of the clause (the clause keyword); 2)
/// LParenLoc: location of '('; 3) EndLoc: ending location of the clause.
/// \param Vars The original expression used in the clause.
/// \param Declarations Declarations used in the clause.
/// \param ComponentLists Component lists used in the clause.
static OMPIsDevicePtrClause *
Create(const ASTContext &C, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations,
MappableExprComponentListsRef ComponentLists);
/// Creates an empty clause with the place for \a NumVars variables.
///
/// \param C AST context.
/// \param Sizes All required sizes to build a mappable clause. It includes 1)
/// NumVars: number of expressions listed in this clause; 2)
/// NumUniqueDeclarations: number of unique base declarations in this clause;
/// 3) NumComponentLists: number of component lists in this clause; and 4)
/// NumComponents: total number of expression components in the clause.
static OMPIsDevicePtrClause *
CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPIsDevicePtrClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_is_device_ptr;
}
};
/// This represents clause 'nontemporal' in the '#pragma omp ...' directives.
///
/// \code
/// #pragma omp simd nontemporal(a)
/// \endcode
/// In this example directive '#pragma omp simd' has clause 'nontemporal' for
/// the variable 'a'.
class OMPNontemporalClause final
: public OMPVarListClause<OMPNontemporalClause>,
private llvm::TrailingObjects<OMPNontemporalClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPNontemporalClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPNontemporalClause>(llvm::omp::OMPC_nontemporal,
StartLoc, LParenLoc, EndLoc, N) {
}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPNontemporalClause(unsigned N)
: OMPVarListClause<OMPNontemporalClause>(
llvm::omp::OMPC_nontemporal, SourceLocation(), SourceLocation(),
SourceLocation(), N) {}
/// Get the list of privatied copies if the member expression was captured by
/// one of the privatization clauses.
MutableArrayRef<Expr *> getPrivateRefs() {
return MutableArrayRef<Expr *>(varlist_end(), varlist_size());
}
ArrayRef<const Expr *> getPrivateRefs() const {
return llvm::makeArrayRef(varlist_end(), varlist_size());
}
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the variables.
static OMPNontemporalClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL);
/// Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPNontemporalClause *CreateEmpty(const ASTContext &C, unsigned N);
/// Sets the list of references to private copies created in private clauses.
/// \param VL List of references.
void setPrivateRefs(ArrayRef<Expr *> VL);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPNontemporalClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range private_refs() {
return child_range(reinterpret_cast<Stmt **>(getPrivateRefs().begin()),
reinterpret_cast<Stmt **>(getPrivateRefs().end()));
}
const_child_range private_refs() const {
auto Children = const_cast<OMPNontemporalClause *>(this)->private_refs();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_nontemporal;
}
};
/// This represents 'order' clause in the '#pragma omp ...' directive.
///
/// \code
/// #pragma omp simd order(concurrent)
/// \endcode
/// In this example directive '#pragma omp parallel' has simple 'order'
/// clause with kind 'concurrent'.
class OMPOrderClause final : public OMPClause {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// A kind of the 'default' clause.
OpenMPOrderClauseKind Kind = OMPC_ORDER_unknown;
/// Start location of the kind in source code.
SourceLocation KindKwLoc;
/// Set kind of the clause.
///
/// \param K Argument of clause.
void setKind(OpenMPOrderClauseKind K) { Kind = K; }
/// Set argument location.
///
/// \param KLoc Argument location.
void setKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; }
public:
/// Build 'order' clause with argument \p A ('concurrent').
///
/// \param A Argument of the clause ('concurrent').
/// \param ALoc Starting location of the argument.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPOrderClause(OpenMPOrderClauseKind A, SourceLocation ALoc,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_order, StartLoc, EndLoc),
LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {}
/// Build an empty clause.
OMPOrderClause()
: OMPClause(llvm::omp::OMPC_order, SourceLocation(), SourceLocation()) {}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Returns kind of the clause.
OpenMPOrderClauseKind getKind() const { return Kind; }
/// Returns location of clause kind.
SourceLocation getKindKwLoc() const { return KindKwLoc; }
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_order;
}
};
/// This represents 'destroy' clause in the '#pragma omp depobj'
/// directive.
///
/// \code
/// #pragma omp depobj(a) destroy
/// \endcode
/// In this example directive '#pragma omp depobj' has 'destroy' clause.
class OMPDestroyClause final : public OMPClause {
public:
/// Build 'destroy' clause.
///
/// \param StartLoc Starting location of the clause.
/// \param EndLoc Ending location of the clause.
OMPDestroyClause(SourceLocation StartLoc, SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_destroy, StartLoc, EndLoc) {}
/// Build an empty clause.
OMPDestroyClause()
: OMPClause(llvm::omp::OMPC_destroy, SourceLocation(), SourceLocation()) {
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_destroy;
}
};
/// This represents 'detach' clause in the '#pragma omp task' directive.
///
/// \code
/// #pragma omp task detach(evt)
/// \endcode
/// In this example directive '#pragma omp detach' has simple 'detach' clause
/// with the variable 'evt'.
class OMPDetachClause final : public OMPClause {
friend class OMPClauseReader;
/// Location of '('.
SourceLocation LParenLoc;
/// Expression of the 'detach' clause.
Stmt *Evt = nullptr;
/// Set condition.
void setEventHandler(Expr *E) { Evt = E; }
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
public:
/// Build 'detach' clause with event-handler \a Evt.
///
/// \param Evt Event handler expression.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
OMPDetachClause(Expr *Evt, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc)
: OMPClause(llvm::omp::OMPC_detach, StartLoc, EndLoc),
LParenLoc(LParenLoc), Evt(Evt) {}
/// Build an empty clause.
OMPDetachClause()
: OMPClause(llvm::omp::OMPC_detach, SourceLocation(), SourceLocation()) {}
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Returns event-handler expression.
Expr *getEventHandler() const { return cast_or_null<Expr>(Evt); }
child_range children() { return child_range(&Evt, &Evt + 1); }
const_child_range children() const {
return const_child_range(&Evt, &Evt + 1);
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_detach;
}
};
/// This represents clause 'inclusive' in the '#pragma omp scan' directive.
///
/// \code
/// #pragma omp scan inclusive(a,b)
/// \endcode
/// In this example directive '#pragma omp scan' has clause 'inclusive'
/// with the variables 'a' and 'b'.
class OMPInclusiveClause final
: public OMPVarListClause<OMPInclusiveClause>,
private llvm::TrailingObjects<OMPInclusiveClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPInclusiveClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPInclusiveClause>(llvm::omp::OMPC_inclusive,
StartLoc, LParenLoc, EndLoc, N) {}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPInclusiveClause(unsigned N)
: OMPVarListClause<OMPInclusiveClause>(llvm::omp::OMPC_inclusive,
SourceLocation(), SourceLocation(),
SourceLocation(), N) {}
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the original variables.
static OMPInclusiveClause *Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL);
/// Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPInclusiveClause *CreateEmpty(const ASTContext &C, unsigned N);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPInclusiveClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_inclusive;
}
};
/// This represents clause 'exclusive' in the '#pragma omp scan' directive.
///
/// \code
/// #pragma omp scan exclusive(a,b)
/// \endcode
/// In this example directive '#pragma omp scan' has clause 'exclusive'
/// with the variables 'a' and 'b'.
class OMPExclusiveClause final
: public OMPVarListClause<OMPExclusiveClause>,
private llvm::TrailingObjects<OMPExclusiveClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Build clause with number of variables \a N.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of the variables in the clause.
OMPExclusiveClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPExclusiveClause>(llvm::omp::OMPC_exclusive,
StartLoc, LParenLoc, EndLoc, N) {}
/// Build an empty clause.
///
/// \param N Number of variables.
explicit OMPExclusiveClause(unsigned N)
: OMPVarListClause<OMPExclusiveClause>(llvm::omp::OMPC_exclusive,
SourceLocation(), SourceLocation(),
SourceLocation(), N) {}
public:
/// Creates clause with a list of variables \a VL.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param VL List of references to the original variables.
static OMPExclusiveClause *Create(const ASTContext &C,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<Expr *> VL);
/// Creates an empty clause with the place for \a N variables.
///
/// \param C AST context.
/// \param N The number of variables.
static OMPExclusiveClause *CreateEmpty(const ASTContext &C, unsigned N);
child_range children() {
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end()));
}
const_child_range children() const {
auto Children = const_cast<OMPExclusiveClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_exclusive;
}
};
/// This represents clause 'uses_allocators' in the '#pragma omp target'-based
/// directives.
///
/// \code
/// #pragma omp target uses_allocators(default_allocator, my_allocator(traits))
/// \endcode
/// In this example directive '#pragma omp target' has clause 'uses_allocators'
/// with the allocators 'default_allocator' and user-defined 'my_allocator'.
class OMPUsesAllocatorsClause final
: public OMPClause,
private llvm::TrailingObjects<OMPUsesAllocatorsClause, Expr *,
SourceLocation> {
public:
/// Data for list of allocators.
struct Data {
/// Allocator.
Expr *Allocator = nullptr;
/// Allocator traits.
Expr *AllocatorTraits = nullptr;
/// Locations of '(' and ')' symbols.
SourceLocation LParenLoc, RParenLoc;
};
private:
friend class OMPClauseReader;
friend TrailingObjects;
enum class ExprOffsets {
Allocator,
AllocatorTraits,
Total,
};
enum class ParenLocsOffsets {
LParen,
RParen,
Total,
};
/// Location of '('.
SourceLocation LParenLoc;
/// Total number of allocators in the clause.
unsigned NumOfAllocators = 0;
/// Build clause.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param N Number of allocators asssociated with the clause.
OMPUsesAllocatorsClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, unsigned N)
: OMPClause(llvm::omp::OMPC_uses_allocators, StartLoc, EndLoc),
LParenLoc(LParenLoc), NumOfAllocators(N) {}
/// Build an empty clause.
/// \param N Number of allocators asssociated with the clause.
///
explicit OMPUsesAllocatorsClause(unsigned N)
: OMPClause(llvm::omp::OMPC_uses_allocators, SourceLocation(),
SourceLocation()),
NumOfAllocators(N) {}
unsigned numTrailingObjects(OverloadToken<Expr *>) const {
return NumOfAllocators * static_cast<int>(ExprOffsets::Total);
}
/// Sets the location of '('.
void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
/// Sets the allocators data for the clause.
void setAllocatorsData(ArrayRef<OMPUsesAllocatorsClause::Data> Data);
public:
/// Creates clause with a list of allocators \p Data.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param EndLoc Ending location of the clause.
/// \param Data List of allocators.
static OMPUsesAllocatorsClause *
Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc, ArrayRef<OMPUsesAllocatorsClause::Data> Data);
/// Creates an empty clause with the place for \p N allocators.
///
/// \param C AST context.
/// \param N The number of allocators.
static OMPUsesAllocatorsClause *CreateEmpty(const ASTContext &C, unsigned N);
/// Returns the location of '('.
SourceLocation getLParenLoc() const { return LParenLoc; }
/// Returns number of allocators associated with the clause.
unsigned getNumberOfAllocators() const { return NumOfAllocators; }
/// Returns data for the specified allocator.
OMPUsesAllocatorsClause::Data getAllocatorData(unsigned I) const;
// Iterators
child_range children() {
Stmt **Begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
return child_range(Begin, Begin + NumOfAllocators *
static_cast<int>(ExprOffsets::Total));
}
const_child_range children() const {
Stmt *const *Begin =
reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
return const_child_range(
Begin, Begin + NumOfAllocators * static_cast<int>(ExprOffsets::Total));
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_uses_allocators;
}
};
/// This represents clause 'affinity' in the '#pragma omp task'-based
/// directives.
///
/// \code
/// #pragma omp task affinity(iterator(i = 0:n) : ([3][n])a, b[:n], c[i])
/// \endcode
/// In this example directive '#pragma omp task' has clause 'affinity' with the
/// affinity modifer 'iterator(i = 0:n)' and locator items '([3][n])a', 'b[:n]'
/// and 'c[i]'.
class OMPAffinityClause final
: public OMPVarListClause<OMPAffinityClause>,
private llvm::TrailingObjects<OMPAffinityClause, Expr *> {
friend class OMPClauseReader;
friend OMPVarListClause;
friend TrailingObjects;
/// Location of ':' symbol.
SourceLocation ColonLoc;
/// Build clause.
///
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param N Number of locators asssociated with the clause.
OMPAffinityClause(SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N)
: OMPVarListClause<OMPAffinityClause>(llvm::omp::OMPC_affinity, StartLoc,
LParenLoc, EndLoc, N) {}
/// Build an empty clause.
/// \param N Number of locators asssociated with the clause.
///
explicit OMPAffinityClause(unsigned N)
: OMPVarListClause<OMPAffinityClause>(llvm::omp::OMPC_affinity,
SourceLocation(), SourceLocation(),
SourceLocation(), N) {}
/// Sets the affinity modifier for the clause, if any.
void setModifier(Expr *E) {
getTrailingObjects<Expr *>()[varlist_size()] = E;
}
/// Sets the location of ':' symbol.
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
public:
/// Creates clause with a modifier a list of locator items.
///
/// \param C AST context.
/// \param StartLoc Starting location of the clause.
/// \param LParenLoc Location of '('.
/// \param ColonLoc Location of ':'.
/// \param EndLoc Ending location of the clause.
/// \param Locators List of locator items.
static OMPAffinityClause *Create(const ASTContext &C, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc, Expr *Modifier,
ArrayRef<Expr *> Locators);
/// Creates an empty clause with the place for \p N locator items.
///
/// \param C AST context.
/// \param N The number of locator items.
static OMPAffinityClause *CreateEmpty(const ASTContext &C, unsigned N);
/// Gets affinity modifier.
Expr *getModifier() { return getTrailingObjects<Expr *>()[varlist_size()]; }
Expr *getModifier() const {
return getTrailingObjects<Expr *>()[varlist_size()];
}
/// Gets the location of ':' symbol.
SourceLocation getColonLoc() const { return ColonLoc; }
// Iterators
child_range children() {
int Offset = getModifier() ? 1 : 0;
return child_range(reinterpret_cast<Stmt **>(varlist_begin()),
reinterpret_cast<Stmt **>(varlist_end() + Offset));
}
const_child_range children() const {
auto Children = const_cast<OMPAffinityClause *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_range used_children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range used_children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
static bool classof(const OMPClause *T) {
return T->getClauseKind() == llvm::omp::OMPC_affinity;
}
};
/// This class implements a simple visitor for OMPClause
/// subclasses.
template<class ImplClass, template <typename> class Ptr, typename RetTy>
class OMPClauseVisitorBase {
public:
#define PTR(CLASS) Ptr<CLASS>
#define DISPATCH(CLASS) \
return static_cast<ImplClass*>(this)->Visit##CLASS(static_cast<PTR(CLASS)>(S))
#define OMP_CLAUSE_CLASS(Enum, Str, Class) \
RetTy Visit ## Class (PTR(Class) S) { DISPATCH(Class); }
#include "llvm/Frontend/OpenMP/OMPKinds.def"
RetTy Visit(PTR(OMPClause) S) {
// Top switch clause: visit each OMPClause.
switch (S->getClauseKind()) {
#define OMP_CLAUSE_CLASS(Enum, Str, Class) \
case llvm::omp::Clause::Enum: \
return Visit##Class(static_cast<PTR(Class)>(S));
#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
case llvm::omp::Clause::Enum: \
break;
#include "llvm/Frontend/OpenMP/OMPKinds.def"
}
}
// Base case, ignore it. :)
RetTy VisitOMPClause(PTR(OMPClause) Node) { return RetTy(); }
#undef PTR
#undef DISPATCH
};
template <typename T> using const_ptr = std::add_pointer_t<std::add_const_t<T>>;
template <class ImplClass, typename RetTy = void>
class OMPClauseVisitor
: public OMPClauseVisitorBase<ImplClass, std::add_pointer_t, RetTy> {};
template<class ImplClass, typename RetTy = void>
class ConstOMPClauseVisitor :
public OMPClauseVisitorBase <ImplClass, const_ptr, RetTy> {};
class OMPClausePrinter final : public OMPClauseVisitor<OMPClausePrinter> {
raw_ostream &OS;
const PrintingPolicy &Policy;
/// Process clauses with list of variables.
template <typename T> void VisitOMPClauseList(T *Node, char StartSym);
public:
OMPClausePrinter(raw_ostream &OS, const PrintingPolicy &Policy)
: OS(OS), Policy(Policy) {}
#define OMP_CLAUSE_CLASS(Enum, Str, Class) \
void Visit##Class(Class *S);
#include "llvm/Frontend/OpenMP/OMPKinds.def"
};
struct OMPTraitProperty {
llvm::omp::TraitProperty Kind = llvm::omp::TraitProperty::invalid;
};
struct OMPTraitSelector {
Expr *ScoreOrCondition = nullptr;
llvm::omp::TraitSelector Kind = llvm::omp::TraitSelector::invalid;
llvm::SmallVector<OMPTraitProperty, 1> Properties;
};
struct OMPTraitSet {
llvm::omp::TraitSet Kind = llvm::omp::TraitSet::invalid;
llvm::SmallVector<OMPTraitSelector, 2> Selectors;
};
/// Helper data structure representing the traits in a match clause of an
/// `declare variant` or `metadirective`. The outer level is an ordered
/// collection of selector sets, each with an associated kind and an ordered
/// collection of selectors. A selector has a kind, an optional score/condition,
/// and an ordered collection of properties.
class OMPTraitInfo {
/// Private constructor accesible only by ASTContext.
OMPTraitInfo() {}
friend class ASTContext;
public:
/// Reconstruct a (partial) OMPTraitInfo object from a mangled name.
OMPTraitInfo(StringRef MangledName);
/// The outermost level of selector sets.
llvm::SmallVector<OMPTraitSet, 2> Sets;
bool anyScoreOrCondition(
llvm::function_ref<bool(Expr *&, bool /* IsScore */)> Cond) {
return llvm::any_of(Sets, [&](OMPTraitSet &Set) {
return llvm::any_of(
Set.Selectors, [&](OMPTraitSelector &Selector) {
return Cond(Selector.ScoreOrCondition,
/* IsScore */ Selector.Kind !=
llvm::omp::TraitSelector::user_condition);
});
});
}
/// Create a variant match info object from this trait info object. While the
/// former is a flat representation the actual main difference is that the
/// latter uses clang::Expr to store the score/condition while the former is
/// independent of clang. Thus, expressions and conditions are evaluated in
/// this method.
void getAsVariantMatchInfo(ASTContext &ASTCtx,
llvm::omp::VariantMatchInfo &VMI) const;
/// Return a string representation identifying this context selector.
std::string getMangledName() const;
/// Print a human readable representation into \p OS.
void print(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const;
};
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const OMPTraitInfo &TI);
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const OMPTraitInfo *TI);
} // namespace clang
#endif // LLVM_CLANG_AST_OPENMPCLAUSE_H
|
rose_jacobi_avx512.c | #include "rex_kmp.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/timeb.h>
#include <malloc.h>
#include <immintrin.h>
#include <immintrin.h>
#define REAL float
static double read_timer_ms()
{
struct timeb tm;
ftime(&tm);
return ((double )tm . time) * 1000.0 + ((double )tm . millitm);
}
/************************************************************
* program to solve a finite difference
* discretization of Helmholtz equation :
* (d2/dx2)u + (d2/dy2)u - alpha u = f
* using Jacobi iterative method.
*
* Modified: Sanjiv Shah, Kuck and Associates, Inc. (KAI), 1998
* Author: Joseph Robicheaux, Kuck and Associates, Inc. (KAI), 1998
*
* This c version program is translated by
* Chunhua Liao, University of Houston, Jan, 2005
*
* Directives are used in this code to achieve parallelism.
* All do loops are parallelized with default 'static' scheduling.
*
* Input : n - grid dimension in x direction
* m - grid dimension in y direction
* alpha - Helmholtz constant (always greater than 0.0)
* tol - error tolerance for iterative solver
* relax - Successice over relaxation parameter
* mits - Maximum iterations for iterative solver
*
* On output
* : u(n,m) - Dependent variable (solutions)
* : f(n,m) - Right hand side function
*************************************************************/
#define DEFAULT_DIMSIZE 256
void print_array(char *title,char *name,float *A,int n,int m)
{
printf("%s:\n",title);
int i;
int j;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
printf("%s[%d][%d]:%f ",name,i,j,A[i * m + j]);
}
printf("\n");
}
printf("\n");
}
/* subroutine initialize (n,m,alpha,dx,dy,u,f)
******************************************************
* Initializes data
* Assumes exact solution is u(x,y) = (1-x^2)*(1-y^2)
*
******************************************************/
void initialize(int n,int m,float alpha,float *dx,float *dy,float *u_p,float *f_p)
{
int i;
int j;
int xx;
int yy;
float (*u)[m] = ((float (*)[m])u_p);
float (*f)[m] = ((float (*)[m])f_p);
//double PI=3.1415926;
*dx = (2.0 / (n - 1));
*dy = (2.0 / (m - 1));
/* Initialize initial condition and RHS */
//#pragma omp parallel for private(xx,yy,j,i)
for (i = 0; i < n; i++)
for (j = 0; j < m; j++) {
xx = ((int )(- 1.0 + ( *dx * (i - 1))));
yy = ((int )(- 1.0 + ( *dy * (j - 1))));
u[i][j] = 0.0;
f[i][j] = (- 1.0 * alpha * (1.0 - (xx * xx)) * (1.0 - (yy * yy)) - 2.0 * (1.0 - (xx * xx)) - 2.0 * (1.0 - (yy * yy)));
}
}
/* subroutine error_check (n,m,alpha,dx,dy,u,f)
implicit none
************************************************************
* Checks error between numerical and exact solution
*
************************************************************/
void error_check(int n,int m,float alpha,float dx,float dy,float *u_p,float *f_p)
{
int i;
int j;
float xx;
float yy;
float temp;
float error;
error = 0.0;
float (*u)[m] = ((float (*)[m])u_p);
float (*f)[m] = ((float (*)[m])f_p);
//#pragma omp parallel for private(xx,yy,temp,j,i) reduction(+:error)
for (i = 0; i < n; i++)
for (j = 0; j < m; j++) {
xx = (- 1.0 + (dx * (i - 1)));
yy = (- 1.0 + (dy * (j - 1)));
temp = (u[i][j] - (1.0 - (xx * xx)) * (1.0 - (yy * yy)));
error = error + temp * temp;
}
error = (sqrt(error) / (n * m));
printf("Solution Error: %2.6g\n",error);
}
void jacobi_seq(int n,int m,float dx,float dy,float alpha,float relax,float *u_p,float *f_p,float tol,int mits);
void jacobi_omp(int n,int m,float dx,float dy,float alpha,float relax,float *u_p,float *f_p,float tol,int mits);
int main(int argc,char *argv[])
{
int status = 0;
int n = 256;
int m = 256;
float alpha = 0.0543;
float tol = 0.0000000001;
float relax = 1.0;
int mits = 5000;
/*fprintf(stderr, "Usage: jacobi [<n> <m> <alpha> <tol> <relax> <mits>]\n");
fprintf(stderr, "\tn - grid dimension in x direction, default: %d\n", n);
fprintf(stderr, "\tm - grid dimension in y direction, default: n if provided or %d\n", m);
fprintf(stderr, "\talpha - Helmholtz constant (always greater than 0.0), default: %g\n", alpha);
fprintf(stderr, "\ttol - error tolerance for iterative solver, default: %g\n", tol);
fprintf(stderr, "\trelax - Successice over relaxation parameter, default: %g\n", relax);
fprintf(stderr, "\tmits - Maximum iterations for iterative solver, default: %d\n", mits);*/
if (argc == 2) {
sscanf(argv[1],"%d",&n);
m = n;
}
else if (argc == 3) {
sscanf(argv[1],"%d",&n);
sscanf(argv[2],"%d",&m);
}
else if (argc == 4) {
sscanf(argv[1],"%d",&n);
sscanf(argv[2],"%d",&m);
sscanf(argv[3],"%g",&alpha);
}
else if (argc == 5) {
sscanf(argv[1],"%d",&n);
sscanf(argv[2],"%d",&m);
sscanf(argv[3],"%g",&alpha);
sscanf(argv[4],"%g",&tol);
}
else if (argc == 6) {
sscanf(argv[1],"%d",&n);
sscanf(argv[2],"%d",&m);
sscanf(argv[3],"%g",&alpha);
sscanf(argv[4],"%g",&tol);
sscanf(argv[5],"%g",&relax);
}
else if (argc == 7) {
sscanf(argv[1],"%d",&n);
sscanf(argv[2],"%d",&m);
sscanf(argv[3],"%g",&alpha);
sscanf(argv[4],"%g",&tol);
sscanf(argv[5],"%g",&relax);
sscanf(argv[6],"%d",&mits);
}
else {
/* the rest of arg ignored */
}
printf("jacobi %d %d %g %g %g %d\n",n,m,alpha,tol,relax,mits);
printf("------------------------------------------------------------------------------------------------------\n");
/** init the array */
float *u = (float *)(malloc(sizeof(float ) * n * m));
float *uomp = (float *)(malloc(sizeof(float ) * n * m));
float *f = (float *)(malloc(sizeof(float ) * n * m));
float dx;
/* grid spacing in x direction */
float dy;
/* grid spacing in y direction */
initialize(n,m,alpha,&dx,&dy,u,f);
memcpy(uomp,u,sizeof(float ) * n * m);
double elapsed = read_timer_ms();
jacobi_seq(n,m,dx,dy,alpha,relax,u,f,tol,mits);
elapsed = read_timer_ms() - elapsed;
printf("seq elasped time(ms): %4f\n",elapsed);
double mflops = 0.001 * mits * (n - 2) * (m - 2) * 13 / elapsed;
printf("MFLOPS: %12.6g\n",mflops);
puts("================");
elapsed = read_timer_ms();
jacobi_omp(n,m,dx,dy,alpha,relax,uomp,f,tol,mits);
elapsed = read_timer_ms() - elapsed;
printf("OpenMP elasped time(ms): %4f\n",elapsed);
mflops = 0.001 * mits * (n - 2) * (m - 2) * 13 / elapsed;
printf("MFLOPS: %12.6g\n",mflops);
//print_array("Sequential Run", "u",(REAL*)u, n, m);
error_check(n,m,alpha,dx,dy,u,f);
free(u);
free(f);
free(uomp);
return 0;
}
/* subroutine jacobi (n,m,dx,dy,alpha,omega,u,f,tol,mits)
******************************************************************
* Subroutine HelmholtzJ
* Solves poisson equation on rectangular grid assuming :
* (1) Uniform discretization in each direction, and
* (2) Dirichlect boundary conditions
*
* Jacobi method is used in this routine
*
* Input : n,m Number of grid points in the X/Y directions
* dx,dy Grid spacing in the X/Y directions
* alpha Helmholtz eqn. coefficient
* omega Relaxation factor
* f(n,m) Right hand side function
* u(n,m) Dependent variable/Solution
* tol Tolerance for iterative solver
* mits Maximum number of iterations
*
* Output : u(n,m) - Solution
*****************************************************************/
void jacobi_seq(int n,int m,float dx,float dy,float alpha,float omega,float *u_p,float *f_p,float tol,int mits)
{
int i;
int j;
int k;
float error;
float ax;
float ay;
float b;
float resid;
float uold[n][m];
float (*u)[m] = ((float (*)[m])u_p);
float (*f)[m] = ((float (*)[m])f_p);
/*
* Initialize coefficients */
/* X-direction coef */
ax = (1.0 / (dx * dx));
/* Y-direction coef */
ay = (1.0 / (dy * dy));
/* Central coeff */
b = (- 2.0 / (dx * dx) - 2.0 / (dy * dy) - alpha);
error = (10.0 * tol);
k = 1;
while(k <= mits && error > tol){
error = 0.0;
/* Copy new solution into old */
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
uold[i][j] = u[i][j];
for (i = 1; i < n - 1; i++)
for (j = 1; j < m - 1; j++) {
resid = (ax * (uold[i - 1][j] + uold[i + 1][j]) + ay * (uold[i][j - 1] + uold[i][j + 1]) + b * uold[i][j] - f[i][j]) / b;
//printf("i: %d, j: %d, resid: %f\n", i, j, resid);
u[i][j] = uold[i][j] - omega * resid;
error = error + resid * resid;
}
/* Error check */
//if (k % 500 == 0)
// printf("Finished %d iteration with error: %g\n", k, error);
error = (sqrt(error) / (n * m));
k = k + 1;
/* End iteration loop */
}
printf("Total Number of Iterations: %d\n",k);
printf("Residual: %.15g\n",error);
}
void jacobi_omp(int n,int m,float dx,float dy,float alpha,float omega,float *u_p,float *f_p,float tol,int mits)
{
int i;
int j;
int k;
float error;
float ax;
float ay;
float b;
float resid;
float *tmp = (float *)(malloc(sizeof(float ) * n * m));
float (*uold)[m] = ((float (*)[m])tmp);
float (*u)[m] = ((float (*)[m])u_p);
float (*f)[m] = ((float (*)[m])f_p);
/*
* Initialize coefficients */
/* X-direction coef */
ax = (1.0 / (dx * dx));
/* Y-direction coef */
ay = (1.0 / (dy * dy));
/* Central coeff */
b = (- 2.0 / (dx * dx) - 2.0 / (dy * dy) - alpha);
error = (10.0 * tol);
k = 1;
while(k <= mits && error > tol){
error = 0.0;
//printf("===================== iteration %d ===========================\n", k);
/* Copy new solution into old */
for (i = 0; i < n; i++) {
for (j = 0; j <= m - 1; j += 16) {
float *__ptr39 = uold[i];
float *__ptr40 = u[i];
__m512 __vec41 = _mm512_loadu_ps(&__ptr40[j]);
_mm512_storeu_ps(&__ptr39[j],__vec41);
}
}
for (i = 1; i < n - 1; i++) {
__m512 __vec0 = _mm512_set1_ps(ax);
__m512 __vec7 = _mm512_set1_ps(ay);
__m512 __vec15 = _mm512_set1_ps(b);
__m512 __vec23 = _mm512_set1_ps(b);
__m512 __part25 = _mm512_setzero_ps();
__m512 __vec29 = _mm512_set1_ps(omega);
__m512 __vec30 = _mm512_set1_ps(resid);
__m512 __vec33 = _mm512_set1_ps(error);
__m512 __vec34 = _mm512_set1_ps(resid);
__m512 __vec35 = _mm512_set1_ps(resid);
__m512 __part38 = _mm512_setzero_ps();
for (j = 1; j <= m - 1 - 1; j += 16) {
float *__ptr1 = uold[i - 1];
__m512 __vec2 = _mm512_loadu_ps(&__ptr1[j]);
float *__ptr3 = uold[i + 1];
__m512 __vec4 = _mm512_loadu_ps(&__ptr3[j]);
__m512 __vec5 = _mm512_add_ps(__vec4,__vec2);
__m512 __vec6 = _mm512_mul_ps(__vec5,__vec0);
float *__ptr8 = uold[i];
__m512 __vec9 = _mm512_loadu_ps(&__ptr8[j - 1]);
float *__ptr10 = uold[i];
__m512 __vec11 = _mm512_loadu_ps(&__ptr10[j + 1]);
__m512 __vec12 = _mm512_add_ps(__vec11,__vec9);
__m512 __vec13 = _mm512_mul_ps(__vec12,__vec7);
__m512 __vec14 = _mm512_add_ps(__vec13,__vec6);
float *__ptr16 = uold[i];
__m512 __vec17 = _mm512_loadu_ps(&__ptr16[j]);
__m512 __vec18 = _mm512_mul_ps(__vec17,__vec15);
__m512 __vec19 = _mm512_add_ps(__vec18,__vec14);
float *__ptr20 = f[i];
__m512 __vec21 = _mm512_loadu_ps(&__ptr20[j]);
__m512 __vec22 = _mm512_sub_ps(__vec21,__vec19);
__m512 __vec24 = _mm512_div_ps(__vec23,__vec22);
__part25 = _mm512_add_ps(__part25,__vec24);
float *__ptr26 = u[i];
float *__ptr27 = uold[i];
__m512 __vec28 = _mm512_loadu_ps(&__ptr27[j]);
__m512 __vec31 = _mm512_mul_ps(__vec30,__vec29);
__m512 __vec32 = _mm512_sub_ps(__vec31,__vec28);
_mm512_storeu_ps(&__ptr26[j],__vec32);
__m512 __vec36 = _mm512_mul_ps(__vec35,__vec34);
__m512 __vec37 = _mm512_add_ps(__vec36,__vec33);
__part38 = _mm512_add_ps(__part38,__vec37);
}
__m256 __buf3 = _mm512_extractf32x8_ps(__part38,0);
__m256 __buf4 = _mm512_extractf32x8_ps(__part38,1);
__buf4 = _mm256_add_ps(__buf3,__buf4);
__buf4 = _mm256_hadd_ps(__buf4,__buf4);
__buf4 = _mm256_hadd_ps(__buf4,__buf4);
float __buf5[8];
_mm256_storeu_ps(&__buf5,__buf4);
error = __buf5[0] + __buf5[6];
__m256 __buf0 = _mm512_extractf32x8_ps(__part25,0);
__m256 __buf1 = _mm512_extractf32x8_ps(__part25,1);
__buf1 = _mm256_add_ps(__buf0,__buf1);
__buf1 = _mm256_hadd_ps(__buf1,__buf1);
__buf1 = _mm256_hadd_ps(__buf1,__buf1);
float __buf2[8];
_mm256_storeu_ps(&__buf2,__buf1);
resid = __buf2[0] + __buf2[6];
}
/* Error check */
//if (k % 500 == 0)
// printf("Finished %d iteration with error: %g\n", k, error);
error = (sqrt(error) / (n * m));
k = k + 1;
/* End iteration loop */
}
printf("Total Number of Iterations: %d\n",k);
printf("Residual: %.15g\n",error);
free(tmp);
}
|
openmp_eigen_static.c | #include <stdlib.h>
#include <stdio.h>
#include <mkl.h>
#include <omp.h>
#include <sys/time.h>
/*
This program demonstrates the OpenMP parallelization of a
computationally intensive loop where the work per iteration is allowed
to vary. Within the main loop, matrix is generated, the eigenvalue
solver DYSEV is called and the largest eigenvalue is saved.
DYSEV documentation can be found here:
http://www.netlib.org/lapack/explore-html/dd/d4c/dsyev_8f.html
Note that this is not necessarily the preferred way to calculate
eigenvalues and was used purely as a time consuming example for which
the work per iteration could be easily varied.
To compile using Intel C++ compiler and linking MKL routine
icpc openmp_eigen_static.c -mkl -openmp
To run
export OMP_NUM_THREADS=N; ./a.out X Y Z
where
N = number of OpenMP threads
X = dimension of array
Y = number of iterations (number of eigenvalue problems solved)
Z = 'E' for even amount of work per iteration
'U' for uneven amount of work per iteration
*/
int main(int argc, char **argv) {
char choice;
int n, niter;
double elapsed, *eigmax;
struct timeval tv_start, tv_end;
// Make sure we use serial version of Intel MKL routine
mkl_set_num_threads(1);
// Process command line arguments
if (argc < 4) {
printf("\nThree command line arguments required\n");
printf(" Dimension of array\n");
printf(" Number of iterations\n");
printf(" Choice: 'E' for even / 'U' for uneven work per iteration\n\n");
return(0);
}
n = atoi(argv[1]);
niter = atoi(argv[2]);
choice = argv[3][0];
if (choice != 'E' && choice != 'U') {
printf("\nThird argument must be 'E' or 'U' for even or uneven\n");
printf("work per iteration, respectively\n\n");
return(0);
}
// Allocate vector to store results
eigmax = (double *) malloc(niter * sizeof(double));
// Solve eigenvalue problem for "niter" random matrices and print largest eigenvector
// Get timestamp at start of loop
gettimeofday(&tv_start, NULL);
#pragma omp parallel for
for (int j = 0; j < niter; j++) {
int m, lda, info, lwork;
double wkopt, *a, *w, *work;
// Define the problem size. If choice set to uneven, allow problem
// to grow for later iterations
if (choice == 'E') {
m = n;
} else {
m = n + j/5;
}
// Setup work space
lda = m;
lwork = -1;
dsyev("Vectors", "Upper", &m, a, &lda, w, &wkopt, &lwork, &info);
lwork = (int)wkopt;
// Allocate arrays
a = (double *) malloc(m * m * sizeof(double));
w = (double *) malloc(m * sizeof(double));
work = (double*)malloc( lwork*sizeof(double) );
// Initialize array for eigenvalue problem
for (int i=0; i< m*m; i++) {
a[i] = (double) ((i+j)%17) / (2.0 + j);
}
// Calculate eigenvalues and save the largest value
dsyev("Vectors", "Upper", &m, a, &lda, w, work, &lwork, &info);
eigmax[j] = w[m-1];
// Free memory
free(a);
free(w);
free(work);
}
// Get timestamp at end of loop
gettimeofday(&tv_end, NULL);
// Calculate elapsed time
elapsed = (tv_end.tv_sec - tv_start.tv_sec) +
(tv_end.tv_usec - tv_start.tv_usec) / 1000000.0;
printf("array dimension = %d\n", n);
printf("number of iterations = %d\n", niter);
printf("wall time = %f\n", elapsed);
// Following code is included to prevent compiler from optimizing
// away the eigenvalue calculations. Provides the possibility that the
// results will be used.
if (choice == 'A') {
for (int j = 0; j < niter; j++) {
printf("%f\n", eigmax[j]);
}
}
free(eigmax);
}
|
GB_unaryop__lnot_uint32_int64.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_uint32_int64
// op(A') function: GB_tran__lnot_uint32_int64
// C type: uint32_t
// A type: int64_t
// cast: uint32_t cij = (uint32_t) aij
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
int64_t
#define GB_CTYPE \
uint32_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 != 0) ;
// casting
#define GB_CASTING(z, aij) \
uint32_t z = (uint32_t) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_UINT32 || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_uint32_int64
(
uint32_t *Cx, // Cx and Ax may be aliased
int64_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_uint32_int64
(
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
|
Misc.h | //########################################################################
//## Copyright 2019 Da Yan http://www.cs.uab.edu/yanda
//##
//## 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.
//########################################################################
//########################################################################
//## Contributors
//## * Wenwen Qu
//## * Da Yan
//########################################################################
#ifndef __sleuth_misc_h
#define __sleuth_misc_h
#include "Hashtable.h"
#include "assert.h"
FreqHT FK;
#define ChildrenT map<Element*, vector<Element*> >
struct TransBlock{
int st1;
int st2;
int end1;
int end2;
bool ins_flag; // whether inside or outside
bool f2;
TransBlock(int i1, int i2, int e1, int e2, int flag, int _f2): st1(i1), st2(i2), end1(e1), end2(e2), ins_flag(flag), f2(_f2){}
};
//check where a element is frequent
bool notfrequent(Element &n, int iter) {
if(mine_induced && n.isup >= minsup) return false;
else if(!mine_induced && n.sup >= minsup) return false;
return true;
}
/*if a tree if canonical, each level of the tree follows certain orders.
* cand is the full tree, tpos is pos of root of current rightmost subtree
*/
bool check_canonical(vector<int> &cand, int tpos) {
if (mine_ordered)
return true;
//only have to check subtrees on rightmost path, with their immediate siblings to the left, and make sure code is smaller or equal
bool first;
int i, parent = 0, sibling;
int scnt = 0;
//base condition for stopping recursion, the root has no sibling
if (tpos == 0) {
return true;
}
//find the pos of parent and immediate left sibling of tpos under parent
first = true;
sibling = -1; //not found!
for (i = tpos - 1; i >= 0; i--) {
if (cand[i] == BranchIt)
scnt++;
else
scnt--;
if (first && scnt == 0) {
sibling = i;
first = false;
}
if (scnt < 0) { // parent is before all siblings
parent = i;
break;
}
}
if (sibling == -1) { // not found!
return check_canonical(cand, parent);
} else {
//compare the two subtrees rooted at tpos and sibling
int j;
for (i = tpos, j = sibling; i < cand.size() && j < tpos; i++, j++) {
if (cand[i] > cand[j])
return check_canonical(cand, parent);
else if (cand[i] < cand[j]) {
return false;
}
}
}
return true;
}
bool lexsmaller(vector<int> &subtree, vector<int> &cand)
{
int i,j;
for (i=0, j=0; i < subtree.size() && j < cand.size();){
if (subtree[i] > cand[j]){
if (cand[j] != BranchIt) return false;
else{
while (cand[j] == BranchIt) j++;
if (subtree[i] > cand[j]) return false;
else if (subtree[i] < cand[j]) return true;
else return false;
}
}
else if (subtree[i] < cand[j]){
if (subtree[i] != BranchIt) return true;
else{
while(subtree[i] == BranchIt) i++;
if (subtree[i] > cand[j]) return false;
else if (subtree[i] < cand[j]) return true;
else return true;
}
}
else{
i++;
j++;
}
}
return false;
}
/*return a new node to previous prefix pattern. the new node with "val" will appends to the node in "pos"
* we also can prune new node if one of new pattern's parent if not frequent.
*/
Element* test_node(int iter, SleuthPattern *eq, int val, int pos) {
Element *eqn = NULL;
//if noprune, return with a new Eqnode
if (prune_type == noprune) {
eqn = new Element(val, pos);
return eqn;
}
assert(false); // the pruning logic below does not work for DFS, should be disabled
//perform pruning
//prune based on frequent subtree
vector<int> cand;
vector<int> subtree;
int hval;
int scope, scnt;
//form the candidate preifx
cand = eq->prefix();
scnt = eq->get_scope(pos, scope); //what is the scope of node.pos
while (scnt > scope) {
cand.push_back(BranchIt);
scnt--;
}
cand.push_back(val);
bool res = true;
//check subtrees
int omita, omitb;
res = true;
//omit i-th item (omita) and associated BranchIt (omitb)
int i, j, k;
for (i = iter - 3; i >= 0; i--) {
//find pos for i-th item
for (j = 0, k = 0; j < cand.size(); j++) {
if (cand[j] != BranchIt) {
if (k == i) {
omita = j;
break;
} else
k++;
}
}
//find pos for associated BranchIt
scnt = 0;
for (j++; j < cand.size() && scnt >= 0; j++) {
if (cand[j] == BranchIt)
scnt--;
else
scnt++;
}
if (scnt >= 0)
omitb = cand.size();
else
omitb = j - 1;
hval = 0;
subtree.clear();
bool rootless = false;
scnt = 0;
for (k = 0; k < cand.size() && !rootless; k++) {
if (k != omita && k != omitb) {
subtree.push_back(cand[k]);
if (cand[k] != BranchIt) {
hval += cand[k];
scnt++;
} else
scnt--;
if (scnt <= 0)
rootless = true;
}
}
//skip a rootless subtree
if (!rootless && lexsmaller(subtree, cand)) {
res = FK.find(iter - 1, subtree, hval);
if (!res)
return NULL; //subtree not found!
}
}
if (res)
eqn = new Element(val, pos);
else
eqn = NULL;
return eqn;
}
/* After we generate a new child extension eqnode, update the projected database of the new eqnode.
* @l1 : the projected database for pattern A
* @l2 : the projected database for pattern B
* @ins : the new eqnode
* @st1, end1 : the begin and end position in l1
* @st2, end2 : the begin and end position in l2
*/
void check_ins(vector<SleuthProjTrans> *l1, vector<SleuthProjTrans> *l2, Element *ins, // inside
int st1, int st2, int en1, int en2, bool f2, vector<SleuthProjTrans>* output_tlist) {
SleuthProjTrans *n1, *n2;
ival_type cmpval;
bool found_flg = false; // child extension found?
bool induced = false; // induced projected instance found for a join output?
bool induced_flg = false; // induced projected instance found for the current transaction?
int pos1 = st1; //temporary position holder for n1 ival
bool next2; //should we go to next n2 ival? // once child find a parent enty, other entries can be skipped
int depth; // if depth == 1, (child, parent) is an induced pattern
while (st2 < en2) {
n1 = &(*l1)[pos1];
n2 = &(*l2)[st2];
next2 = true; //by default we go to next n2 ival
cmpval = ival::compare(n1->itscope, n2->itscope);
switch (cmpval) {
case sup:
//n2 was under some n1, then such a extension is valid
depth = n2->depth - n1->depth;
if (depth >= 1 && n1->path_equal(*n2)) {
if (depth == 1 && n1->induced)
induced = true;
else
induced = false;
if (!f2)
depth = n2->depth;
//construct new projected transaction and push it into the projected database of new child
if (en1 - st1 > 1 || use_fullpath) {
// project parent path into new projected transaction
if(output_tlist)
output_tlist->emplace_back(n2->tid, n1->parscope, n1->itscope.lb,
n2->itscope, depth, induced);
else
ins->add_list(n2->tid, n1->parscope, n1->itscope.lb,
n2->itscope, depth, induced);
}
else {
if(output_tlist)
output_tlist->emplace_back(n2->tid, n2->itscope, depth, induced);
else
ins->add_list(n2->tid, n2->itscope, depth, induced);
}
if (!count_unique)
ins->sup++;
found_flg = true;
if (induced)
induced_flg = true;
}
next2 = false;
break;
case before:
//check next n1 ival for same n2 ival
next2 = false;
break;
}
if (next2 || pos1 + 1 == en1) { //go to next n2 ival
pos1 = st1;
st2++;
} else
pos1++; //go to next n1 ival
}
if (found_flg && count_unique)
ins->sup++;
if (induced_flg)
ins->isup++;
}
/* After we generate a new cousin extension eqnode, update the projected database of the new eqnode
* @l1 : the projected database for pattern A
* @l2 : the projected database for pattern B
* @ins : the new eqnode
* @st1, end1 : the begin and end position in l1
* @st2, end2 : the begin and edn position in l2
*/
void check_outs(vector<SleuthProjTrans> *l1, vector<SleuthProjTrans> *l2, Element *outs,
int st1, int st2, int en1, int en2, vector<SleuthProjTrans>* output_tlist) {
SleuthProjTrans *n1, *n2;
ival_type cmpval;
bool found_flg = false;
bool induced, induced_flg = false;
bool next2;
int pos1 = st1;
while (st2 < en2) {
n1 = &(*l1)[pos1];
n2 = &(*l2)[st2];
cmpval = ival::compare(n1->itscope, n2->itscope);
switch (cmpval) {
case sup:
break;
//if they have no intersect, then valid
case before:
case after:
if (mine_ordered && cmpval == after)
break;
//n1 is before n2. Check if n1.par is subset of or equal to n2.par
if (n1->path_equal(*n2)) {
if (n1->induced && n2->induced)
induced = true;
else
induced = false;
//construct new projected transaction and push it into the projected database of new child
if (en1 - st1 > 1 || use_fullpath) {
// project parent path into new projected transaction
if(output_tlist)
output_tlist->emplace_back(n2->tid, n1->parscope, n1->itscope.lb,
n2->itscope, n2->depth, induced);
else
outs->add_list(n2->tid, n1->parscope, n1->itscope.lb,
n2->itscope, n2->depth, induced);
}
else {
if(output_tlist)
output_tlist->emplace_back(n2->tid, n2->itscope, n2->depth, induced);
else
outs->add_list(n2->tid, n2->itscope, n2->depth, induced);
}
if (!count_unique)
outs->sup++;
found_flg = true;
if (induced)
induced_flg = true;
}
break;
case sub:
break;
}
if (pos1 + 1 == en1) { //go to next n2 ival
pos1 = st1;
st2++;
} else
pos1++; //go to next n1 ival
}
if (found_flg && count_unique)
outs->sup++;
if (induced_flg)
outs->isup++;
}
//do "scope list join" to get "inside" node and "outside" node's projected database, which is mentioned in zaki's sleuth work.
//l1 and l2 are two project database to join
//f2 means this function is called by getF2()
// the new generate projected database after join will store in ins->tlist and outs->tlist
void get_intersect(vector<SleuthProjTrans> *l1, vector<SleuthProjTrans> *l2, Element *ins,
Element *outs, bool f2 = false) { //f2 is true only when we compute F2, set to false for Fk
SleuthProjTrans *n1, *n2; //in Sleuth paper Fig 3 Vertical Format, n1 points to a row of a rectangle
vector<TransBlock> tbs; // store all projected transaction ready to join
// join the projected instances of the same transaction
//i1 and i2 is the position where tid match begins, e1 and e2 is the position where tid match ends. The join operator will do in [i1, e1] and [i2, e2]
int i1 = 0, i2 = 0;
//
int e1, e2;
while (i1 < l1->size() && i2 < l2->size()) { // join
n1 = &(*l1)[i1];
n2 = &(*l2)[i2];
//look for matching tids
if (n1->tid < n2->tid)
i1++;
else if (n1->tid > n2->tid)
i2++;
else {
//cids match
e1 = i1;
e2 = i2;
//check the cid end positions in it1 and it2
while (e1 < l1->size() && (*l1)[e1].tid == n1->tid)
e1++;
while (e2 < l2->size() && (*l2)[e2].tid == n2->tid)
e2++;
//generate projecetd transaction if candidate found
if (ins) // child extension
//we use + since the join is merge-like
if((l1->size() + l2->size()) <= tauDB_omp)
check_ins(l1, l2, ins, i1, i2, e1, e2, f2, 0); // in Sleuth paper Fig 3 Vertical Format, each range [i1, e1) denotes the rows for a transaction with some tid
else tbs.emplace_back(i1, i2, e1, e2, true, f2);
if (outs) // cousin extension
//we use + since the join is merge-like
if((l1->size() + l2->size()) <= tauDB_omp)
check_outs(l1, l2, outs, i1, i2, e1, e2, 0); // in Sleuth paper Fig 3 Vertical Format, each range [i1, e1) denotes the rows for a transaction with some tid
else tbs.emplace_back(i1, i2, e1, e2, false, f2);
//restore index to end of cids
i1 = e1;
i2 = e2;
}
}
//we use + since the join is merge-like
if((l1->size() + l2->size()) > tauDB_omp){
//do parallel join
vector<vector<SleuthProjTrans> > ins_tlistOfThread(THREADS);
vector<vector<SleuthProjTrans> > outs_tlistOfThread(THREADS);
#pragma omp parallel for schedule(dynamic, CHUNK) num_threads(THREADS)
for(int i = 0; i < tbs.size(); i++){
TransBlock& cur = tbs[i];
int thread_id = omp_get_thread_num();
if(tbs[i].ins_flag) {
check_ins(l1, l2, ins, cur.st1, cur.st2, cur.end1, cur.end2, cur.f2, &ins_tlistOfThread[thread_id]);
}
else {
check_outs(l1, l2, outs, cur.st1, cur.st2, cur.end1, cur.end2, &outs_tlistOfThread[thread_id]);
}
}
if(ins){
for(int i = 0; i < THREADS; i++){
vector<SleuthProjTrans>& tlist_i = ins_tlistOfThread[i];
if(ins->tlist.empty()) ins->tlist.swap(tlist_i);
else{
ins->tlist.insert(ins->tlist.end(), tlist_i.begin(), tlist_i.end());
}
}
sort(ins->tlist.begin(), ins->tlist.end(), projTrans_cmp);
}
if(outs) {
for(int i = 0; i < THREADS; i++){
vector<SleuthProjTrans>& tlist_i = outs_tlistOfThread[i];
if(outs->tlist.empty()) outs->tlist.swap(tlist_i);
else{
outs->tlist.insert(outs->tlist.end(), tlist_i.begin(), tlist_i.end());
}
}
sort(outs->tlist.begin(), outs->tlist.end(), projTrans_cmp);
}
}
}
#endif
|
kmeans.c | #include "kmeans.h"
#include "kmeans_utils.h"
#include "../../utils/matrix/csr_matrix/csr_to_vector_list.h"
#include "../../utils/matrix/vector_list/vector_list_math.h"
#include "../../utils/matrix/csr_matrix/csr_math.h"
#include "../../utils/vector/common/common_vector_math.h"
#include "../../utils/vector/sparse/sparse_vector_math.h"
#include "../../utils/fcl_logging.h"
#include <math.h>
#include <unistd.h>
#include <float.h>
struct kmeans_result* bv_kmeans(struct csr_matrix* samples, struct kmeans_params *prms) {
uint32_t i;
uint64_t j;
uint64_t keys_per_block;
uint64_t block_vectors_dim; /* size of block vectors */
VALUE_TYPE desired_bv_annz; /* desired size of the block vectors */
struct csr_matrix block_vectors_samples; /* block vector matrix of samples */
struct sparse_vector* block_vectors_clusters; /* block vector matrix of clusters */
struct kmeans_result* res;
uint32_t disable_optimizations;
/* bv_kmeans: contains all samples which are eligible for the cluster
* no change optimization.
*/
uint32_t *eligible_for_cluster_no_change_optimization;
struct general_kmeans_context ctx;
initialize_general_context(prms, &ctx, samples);
desired_bv_annz = d_get_subfloat_default(&(prms->tr)
, "additional_params", "bv_annz", 0.3);
block_vectors_dim = 0;
keys_per_block = 0;
disable_optimizations = prms->kmeans_algorithm_id == ALGORITHM_KMEANS;
if (!disable_optimizations) {
initialize_csr_matrix_zero(&block_vectors_samples);
if (prms->kmeans_algorithm_id == ALGORITHM_BV_KMEANS) {
/* search for a suitable size of the block vectors for the input samples and create them */
search_samples_block_vectors(prms, ctx.samples, desired_bv_annz
, &block_vectors_samples
, &block_vectors_dim);
}
if (prms->kmeans_algorithm_id == ALGORITHM_BV_KMEANS_ONDEMAND) {
block_vectors_dim = search_block_vector_size(ctx.samples, desired_bv_annz, prms->verbose);
keys_per_block = ctx.samples->dim / block_vectors_dim;
if (ctx.samples->dim % block_vectors_dim > 0) keys_per_block++;
}
/* create block vectors for the clusters */
create_block_vectors_list_from_vector_list(ctx.cluster_vectors
, block_vectors_dim
, ctx.no_clusters
, ctx.samples->dim
, &block_vectors_clusters);
}
eligible_for_cluster_no_change_optimization = (uint32_t*) calloc(ctx.samples->sample_count, sizeof(uint32_t));
for (i = 0; i < prms->iteration_limit && !ctx.converged && !prms->stop; i++) {
/* track how many blockvector calculations were made / saved */
uint64_t saved_calculations_bv, saved_calculations_prev_cluster;
uint64_t done_blockvector_calcs, saved_calculations_cauchy;
/* reset all calculation counters */
done_blockvector_calcs = 0;
saved_calculations_cauchy = 0;
saved_calculations_prev_cluster = 0;
saved_calculations_bv = 0;
/* initialize data needed for the iteration */
pre_process_iteration(&ctx);
#pragma omp parallel for schedule(dynamic, 1000)
for (j = 0; j < ctx.samples->sample_count; j++) {
/* iterate over all samples */
VALUE_TYPE dist;
uint64_t cluster_id, sample_id;
struct sparse_vector bv;
bv.nnz = 0;
bv.keys = NULL;
bv.values = NULL;
if (omp_get_thread_num() == 0) check_signals(&(prms->stop));
if (!prms->stop) {
sample_id = j;
for (cluster_id = 0; cluster_id < ctx.no_clusters; cluster_id++) {
/* iterate over all cluster centers */
/* if we are not in the first iteration and this cluster is empty, continue to next cluster */
if (i != 0 && ctx.cluster_counts[cluster_id] == 0) continue;
if (!disable_optimizations) {
/* bv_kmeans */
/* we already know the distance to the cluster from last iteration */
if (cluster_id == ctx.previous_cluster_assignments[sample_id]) continue;
/* clusters which did not move in the last iteration can be skipped if the sample is eligible */
if (eligible_for_cluster_no_change_optimization[sample_id] && ctx.clusters_not_changed[cluster_id]) {
/* cluster did not move and sample was eligible for this check. distance to this cluster can not be less than to our best from last iteration */
saved_calculations_prev_cluster += 1;
goto end;
}
/* evaluate cauchy approximation. fast but not good */
dist = lower_bound_euclid(ctx.vector_lengths_clusters[cluster_id]
, ctx.vector_lengths_samples[sample_id]);
if (dist >= ctx.cluster_distances[sample_id]) {
/* approximated distance is larger than current best distance. skip full distance calculation */
saved_calculations_cauchy += 1;
goto end;
}
if (prms->kmeans_algorithm_id == ALGORITHM_BV_KMEANS) {
/* evaluate block vector approximation. */
dist = euclid_vector_list(&block_vectors_samples, sample_id
, block_vectors_clusters, cluster_id
, ctx.vector_lengths_samples
, ctx.vector_lengths_clusters);
} else {
if (bv.keys == NULL) {
create_block_vector_from_csr_matrix_vector(ctx.samples
, sample_id
, keys_per_block
, &bv);
}
dist = euclid_vector(bv.keys, bv.values, bv.nnz
, block_vectors_clusters[cluster_id].keys
, block_vectors_clusters[cluster_id].values
, block_vectors_clusters[cluster_id].nnz
, ctx.vector_lengths_samples[sample_id]
, ctx.vector_lengths_clusters[cluster_id]);
}
done_blockvector_calcs += 1;
if (dist >= ctx.cluster_distances[sample_id] && fabs(dist - ctx.cluster_distances[sample_id]) >= 1e-6) {
/* approximated distance is larger than current best distance. skip full distance calculation */
saved_calculations_bv += 1;
goto end;
}
}
/* if we reached this point we need to calculate a full euclidean distance */
dist = euclid_vector_list(ctx.samples, sample_id, ctx.cluster_vectors, cluster_id
, ctx.vector_lengths_samples, ctx.vector_lengths_clusters);
ctx.done_calculations += 1;
if (dist < ctx.cluster_distances[sample_id]) {
/* replace current best distance with new distance */
ctx.cluster_distances[sample_id] = dist;
ctx.cluster_assignments[sample_id] = cluster_id;
}
end:;
}
}
if (!disable_optimizations) {
free_null(bv.keys);
free_null(bv.values);
}
}
post_process_iteration(&ctx, prms);
/* shift clusters to new position */
calculate_shifted_clusters(&ctx);
switch_to_shifted_clusters(&ctx);
if (!disable_optimizations) {
/* update only block vectors for cluster that shifted */
update_changed_blockvectors(ctx.cluster_vectors
, block_vectors_dim
, ctx.no_clusters
, ctx.samples->dim
, ctx.clusters_not_changed
, block_vectors_clusters);
d_add_ilist(&(prms->tr), "iteration_bv_calcs", done_blockvector_calcs);
d_add_ilist(&(prms->tr), "iteration_bv_calcs_success", saved_calculations_bv + saved_calculations_cauchy);
#pragma omp parallel for
for (j = 0; j < ctx.samples->sample_count; j++) {
/* iterate over all samples */
VALUE_TYPE previous_distance;
previous_distance = ctx.cluster_distances[j];
/* if the cluster did move. calculate the new distance to this sample */
if (ctx.clusters_not_changed[ctx.cluster_assignments[j]] == 0) {
ctx.cluster_distances[j]
= euclid_vector_list(ctx.samples, j
, ctx.cluster_vectors, ctx.cluster_assignments[j]
, ctx.vector_lengths_samples
, ctx.vector_lengths_clusters);
/*#pragma omp critical*/
ctx.done_calculations += 1;
ctx.total_no_calcs += 1;
}
/* if the cluster moved towards this sample,
* then this sample is eligible to skip calculations to centers which
* did not move in the last iteration
*/
if (ctx.cluster_distances[j] <= previous_distance) {
eligible_for_cluster_no_change_optimization[j] = 1;
} else {
eligible_for_cluster_no_change_optimization[j] = 0;
}
}
} else {
/* naive k-means without any optimization remembers nothing from
* the previous iteration.
*/
for (j = 0; j < ctx.samples->sample_count; j++) {
ctx.cluster_distances[j] = DBL_MAX;
}
}
print_iteration_summary(&ctx, prms, i);
/* print block vector statistics */
if (prms->verbose) LOG_INFO("BV statistics c:%" PRINTF_INT64_MODIFIER "u/b:%" PRINTF_INT64_MODIFIER "u/db:%" PRINTF_INT64_MODIFIER "u/pc:%" PRINTF_INT64_MODIFIER "u"
, saved_calculations_cauchy
, saved_calculations_bv
, done_blockvector_calcs
, saved_calculations_prev_cluster);
}
if (prms->verbose) LOG_INFO("total total_no_calcs = %" PRINTF_INT64_MODIFIER "u", ctx.total_no_calcs);
res = create_kmeans_result(prms, &ctx);
/* cleanup all */
if (!disable_optimizations) {
free_csr_matrix(&block_vectors_samples);
free_vector_list(block_vectors_clusters, ctx.no_clusters);
free(block_vectors_clusters);
}
free_general_context(&ctx, prms);
free_null(eligible_for_cluster_no_change_optimization);
return res;
}
|
sieve.c | /*
* Adapted from: http://w...content-available-to-author-only...s.org/sieve-of-eratosthenes
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
int sieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
int primes = 0;
bool *prime = (bool*) malloc((n+1)*sizeof(bool));
int sqrt_n = sqrt(n);
memset(prime, true,(n+1)*sizeof(bool));
int i, p;
#pragma omp parallel for
for (p=2; p <= sqrt_n; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
#pragma omp parallel for
for(i=p*2; i<=n; i += p)
prime[i] = false;
}
}
// count prime numbers
#pragma omp parallel for reduction(+:primes)
for (int p=2; p<=n; p++)
if (prime[p])
primes++;
return(primes);
}
int main()
{
int n = 100000000;
printf("%d\n",sieveOfEratosthenes(n));
return 0;
}
|
LBMClass.h | #ifndef LIDDRIVENCAVITYLBM_LBMCLASS_H
#define LIDDRIVENCAVITYLBM_LBMCLASS_H
#include <iostream>
#include <vector>
#include <math.h>
#include <omp.h>
#include "Eigen/Dense"
using namespace std;
extern const double Re;
extern const int N;
extern const int M;
extern const double Utop,Vtop;
extern const double Ubot,Vbot;
extern const double Ulef,Vlef;
extern const double Urig,Vrig;
extern const int SAVETXT;
extern const double THRESH;
extern const int THREADS;
extern const int MBounds;
extern const int MCollide;
extern const int PRECOND;
extern const double GAMMA;
extern const int INCOMP;
extern const int BC;
extern const int Q;
extern const double MAXITER;
extern const double NU;
extern const double TAU;
extern const double MAGIC;
extern const double RHO0,U0,V0;
extern const int N2;
extern const int NQ;
extern const double w[9];
extern const int c[9][2];
extern const int opp[9];
extern const int half[4];
extern const int prntInt;
extern const int Nm1,Mm1;
extern const int Nm2,Mm2;
extern const int GM[9][9];
extern const double GMinv[9][9];
extern double start,stop;
extern const int IBN,IB;
extern const double IBcenter[2],IBradius;
class LBMClass{
public:
LBMClass(): _f1(NQ,0.0), _f2(NQ,0.0), _fstar(NQ, 0.0),_u1(N2, U0) ,_u2(N2, V0), _rho(N2, RHO0),_p(N2, 0.0), _x(N, 0.0),_y(M, 0.0), _error(100, 0.0),_vmag(N2,0.0),
_stress(N2, 0.0), _vort(N2, 0.0),_dudx(N2, 0.0),_dudy(N2, 0.0),_dvdx(N2, 0.0),_dvdy(N2, 0.0),_forceX(N2, 0.0),_forceY(N2, 0.0),
_df(), _df0(),_MACHSTAR(0.0), _TAU_P(0.0), _OMEGA(0.0), _OMEGAm(0.0), _CS(0.0), _MACH(0.0), _rhobar(1.0),
_filename1(),_filename2(),_omega_e(),_omega_eps(),_omega_q(),_omega_nu(), _GS{}, _Umax(),
_IBrx(IBN,0.0), _IBry(IBN,0.0), _IBur(IBN,0.0), _IBvr(IBN,0.0), _IBFx(IBN,0.0), _IBFy(IBN,0.0), _IBub(IBN,0.0), _IBvb(IBN,0.0),
_IBmatrixAx(IBN,IBN), _IBmatrixAy(IBN,IBN), _IBmatrixAxInv(IBN,IBN), _IBmatrixAyInv(IBN,IBN), _fBodyX(),_fBodyY(),_IBds(),_IBrxmx(),_IBrxmn(),_IBrymx(),_IBrymn()
{
// Initialize x
if (MBounds == 0){
linspace(_x,(0.5 / N), (N - 0.5) / (double) N,N);
linspace(_y,(0.5 / M), (M - 0.5) / (double) N,M);
}
else{
linspace(_x,0.0,1.0 ,N);
linspace(_y,0.0,(double) M / (double) N ,M);
}
_CS = 1.0 / sqrt(3.0);
_MACH = Utop / _CS;
_MACHSTAR = _MACH / sqrt(GAMMA);
_TAU_P = 0.5 + (TAU - 0.5) / GAMMA;
_OMEGA = 1.0 / _TAU_P;
_OMEGAm = 1.0 / (0.5 + ((MAGIC) / ((1.0 / (_OMEGA)) - 0.5)));
_Umax = max(max(Utop,Ubot),max(Vlef,Vrig));
_omega_e = 1.1; // Bulk viscosity
_omega_eps = 1.1; // free parameter
_omega_q = 1.1; // free parameter
_omega_nu = _OMEGA; // Shear viscosity
_GS[0] = 0.0;
_GS[1] = _omega_e;
_GS[2] = _omega_eps;
_GS[3] = 0.0;
_GS[4] = _omega_q;
_GS[5] = 0.0;
_GS[6] = _omega_q;
_GS[7] = _omega_nu;
_GS[8] = _omega_nu;
//_GS = {0.0, _omega_e, _omega_eps, 0.0, _omega_q, 0.0, _omega_q, _omega_nu, _omega_nu};
// SRT
//const double _GS[Q] = {0.0, _OMEGA, _OMEGA, 0.0, _OMEGA, 0.0, _OMEGA, _OMEGA, _OMEGA};
// Mohamad Textbook
//const double _GS[Q] = {0.0, 1.4, 1.4, 0.0, 1.2, 0.0, 1.2, _OMEGA, _OMEGA};
// High Re from Zhen-Hua et al.
//const double _GS[Q] = {0.0, 1.1, 1.0, 0.0, 1.2, 0.0, 1.2, _OMEGA, _OMEGA};
// _GS[0] = 0.0;
// _GS[1] = 1.1;
// _GS[2] = 1.0;
// _GS[3] = 0.0;
// _GS[4] = 1.2;
// _GS[5] = 0.0;
// _GS[6] = 1.2;
// _GS[7] = _omega_nu;
// _GS[8] = _omega_nu;
sprintf(_filename1,"Solution_n=%d_m=%d_Re=%.0f_BCM=%d_CM=%d_G=%0.2f_U=%0.2f.dat",N,M,Re,MBounds,MCollide, GAMMA, Utop);
sprintf(_filename2,"Error_n=%d_m=%d_Re=%.0f_BCM=%d_CM=%d_G=%0.2f_U=%0.2f.txt",N,M,Re,MBounds,MCollide, GAMMA,Utop);
// Initialize f
int ind1,ind2;
#pragma omp parallel for private(ind1,ind2) collapse(2)
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
ind1 = LU2(i, j);
for (int k = 0; k < Q; k++) {
ind2 = LU3(i, j, k);
_f1[ind2] = calcfeq(k,ind1);
_f2[ind2] = _f1[ind2];
}
}
}
if (BC == 1){
_fBodyX = 8.0 * NU * _Umax / (M*M);
}
if (IB==1) {
//***** Immersed Boundary Initialization *****
// initialize position of points on boundary
for (int i = 0; i < IBN; i++){
_IBrx[i] = IBcenter[0] + IBradius * cos((i * 360.0 / (double) IBN) * (_pi/180.0));
_IBry[i] = IBcenter[1] + IBradius * sin((i * 360.0 / (double) IBN) * (_pi/180.0));
}
// Find IB region
for (int i = 0; i < IBN; i++){
if (i == 0){
_IBrxmx = _IBrx[0];
_IBrxmn = _IBrx[0];
_IBrymx = _IBry[0];
_IBrymn = _IBry[0];
}
else {
if (_IBrx[i] < _IBrxmn)
_IBrxmn = _IBrx[i];
if (_IBrx[i] > _IBrxmx)
_IBrxmx = _IBrx[i];
if (_IBry[i] < _IBrymn)
_IBrymn = _IBry[i];
if (_IBry[i] > _IBrymx)
_IBrymx = _IBry[i];
}
}
// Find loop bounds
_IBrxmx = min(ceil(_IBrxmx + 2), (double) Nm1);
_IBrymx = min(ceil(_IBrymx + 2), (double) Mm1);
_IBrxmn = max(floor(_IBrxmn - 2), 0.0);
_IBrymn = max(floor(_IBrymn - 2), 0.0);
//_IBrxmx = Nm1;
//_IBrymx = Mm1;
//_IBrxmn = 0.0;
//_IBrymn = 0.0;
_IBds = 2.0 * _pi * IBradius / (double) IBN;
printf("Points of Immersed Boundary:\n");
for (int i = 0; i < IBN; i++)
printf("(%.3f, %.3f)\n", _IBrx[i],_IBry[i]);
printf("X IB (%d,%d)\n",(int)_IBrxmn,(int)_IBrxmx);
printf("Y IB (%d,%d)\n",(int)_IBrymn,(int)_IBrymx);
// Velocity of boundary
for (int i = 0; i < IBN; i++){
_IBub[i] = 0.0;
_IBub[i] = 0.0;
}
// Calculate matrix A
_IBmatrixAx = Eigen::MatrixXd::Zero(IBN,IBN);
_IBmatrixAy = Eigen::MatrixXd::Zero(IBN,IBN);
double Dirac1,Dirac2;
#pragma omp parallel for collapse(2) private(Dirac1,Dirac2)
for (int i = 0; i < IBN; i++){
for (int j = 0; j < IBN; j++){
for (int k = (int)_IBrxmn; k <= (int)_IBrxmx; k++){
for (int l = (int)_IBrymn; l <= (int)_IBrymx; l++){
Dirac1 = diracdelta(_IBrx[i] - k) * diracdelta(_IBry[i] - l);
Dirac2 = diracdelta(_IBrx[j] - k) * diracdelta(_IBry[j] - l);
_IBmatrixAx(i,j) += _IBds * Dirac1 * Dirac2;
_IBmatrixAy(i,j) += _IBds * Dirac1 * Dirac2;
}
}
}
}
// Calculate inverse of matrix A
_IBmatrixAxInv = _IBmatrixAx.inverse();
_IBmatrixAyInv = _IBmatrixAy.inverse();
}
// Print parameters
printf("Re =\t%.0f\n", Re);
printf("U =\t%.3e\n", Utop);
printf("M =\t%.3e\n", Utop * sqrt(3));
printf("N =\t%d\n", N);
printf("M =\t%d\n", M);
printf("tau =\t%.3e\n", _TAU_P);
printf("nu =\t%.3e\n", NU);
printf("Gamma =\t%.3e\n", GAMMA);
if (PRECOND == 1){
printf("_MACH* =\t%.3e\n", _MACHSTAR);
}
}
// Collide Methods
inline void collideSRT() {
int ind1{}, ind2{};
double Fsource{},fTotalx{},fTotaly{};
#pragma omp parallel for private(ind1, ind2,Fsource,fTotalx,fTotaly) collapse(2)
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
ind1 = LU2(i, j);
fTotalx = _forceX[ind1] + _fBodyX;
fTotaly = _forceY[ind1] + _fBodyY;
for (int k = 0; k < Q; k++) {
ind2 = LU3(i, j, k);
_fstar[ind2] = (1.0 - _OMEGA) * _f1[ind2] + _OMEGA * calcfeq(k, ind1);
Fsource = (1.0 - 0.5 * _OMEGA) * w[k] *
(3.0 * (c[k][0] - _u1[ind1]) + 9.0 * (c[k][0] * _u1[ind1] + c[k][1] * _u2[ind1]) * c[k][0]) * fTotalx +
(3.0 * (c[k][1] - _u2[ind1]) + 9.0 * (c[k][0] * _u1[ind1] + c[k][1] * _u2[ind1]) * c[k][1]) * fTotaly;
_fstar[ind2] += Fsource;
}
}
}
if (BC == 0 || BC == 1)
virtualnode();
}
inline void collideTRT(){
double fplus{},fminus{},feqplus{},feqminus{},feq[9]{};
int ind1{},l{},notl{};
#pragma omp parallel for private(fplus,fminus,feqplus,feqminus,feq,l,notl,ind1) collapse(2)
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
ind1 = LU2(i, j);
for (int k = 0; k < Q; k++)
feq[k] = calcfeq(k,ind1);
// Rest population
fplus = _f1[LU3(i,j,0)];
feqplus = feq[0];
_fstar[LU3(i, j, 0)] = _f1[LU3(i, j, 0)] - _OMEGA * (fplus - feqplus);
for (int k = 0; k < 4; k++) {
l = half[k];
notl = opp[l];
fplus = 0.5 * (_f1[LU3(i,j,l)] + _f1[LU3(i,j,notl)]);
fminus = 0.5 * (_f1[LU3(i,j,l)] - _f1[LU3(i,j,notl)]);
feqplus = 0.5 * (feq[l] + feq[notl]);
feqminus = 0.5 * (feq[l] - feq[notl]);
fplus = _OMEGA * (fplus - feqplus);
fminus = _OMEGAm * (fminus - feqminus);
_fstar[LU3(i, j, l)] = _f1[LU3(i, j, l)] - fplus - fminus;
_fstar[LU3(i, j, notl)] = _f1[LU3(i, j, notl)] - fplus + fminus;
}
}
}
if (BC == 0 || BC == 1)
virtualnode();
}
inline void collideMRT(){
#pragma omp parallel
{
int ind1;
vector<double> _meq(Q,0.0),_mstar(Q,0.0); // moments
double _m{},fTotalx,fTotaly; // moments
#pragma omp for collapse(2)
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
ind1 = LU2(i,j);
fTotalx = _forceX[ind1] + _fBodyX;
fTotaly = _forceY[ind1] + _fBodyY;
calcmeq(_meq, _u1[ind1], _u2[ind1], _rho[ind1],_p[ind1]);
for (int k = 0; k < Q; k++){
_m = GM[k][0] * _f1[LU3(i,j,0)] + GM[k][1] * _f1[LU3(i,j,1)] + GM[k][2] * _f1[LU3(i,j,2)] +GM[k][3] * _f1[LU3(i,j,3)] + GM[k][4] * _f1[LU3(i,j,4)]
+ GM[k][5] * _f1[LU3(i,j,5)] + GM[k][6] * _f1[LU3(i,j,6)] + GM[k][7] * _f1[LU3(i,j,7)] + GM[k][8] * _f1[LU3(i,j,8)];
_mstar[k] = _m - _GS[k] * (_m - _meq[k]);
}
// Forces
_mstar[1] += (1.0 - 0.5 * _GS[1]) * (6.0 * (fTotalx * _u1[ind1] + fTotaly * _u2[ind1]));
_mstar[2] += (1.0 - 0.5 * _GS[2]) * (-6.0 * (fTotalx * _u1[ind1] + fTotaly * _u2[ind1]));
_mstar[3] += (1.0 - 0.5 * _GS[3]) * (fTotalx);
_mstar[4] += (1.0 - 0.5 * _GS[4]) * (-fTotalx);
_mstar[5] += (1.0 - 0.5 * _GS[5]) * (fTotaly);
_mstar[6] += (1.0 - 0.5 * _GS[6]) * (-fTotaly);
_mstar[7] += (1.0 - 0.5 * _GS[7]) * (2.0 * (fTotalx * _u1[ind1] - fTotaly * _u2[ind1]));
_mstar[8] += (1.0 - 0.5 * _GS[8]) * (fTotaly * _u1[ind1] + fTotalx * _u2[ind1]);
for (int k = 0; k < Q; k++){
_fstar[LU3(i, j, k)] = GMinv[k][0] * _mstar[0] + GMinv[k][1] * _mstar[1] + GMinv[k][2] * _mstar[2] + GMinv[k][3] * _mstar[3]
+ GMinv[k][4] * _mstar[4] + GMinv[k][5] * _mstar[5] + GMinv[k][6] * _mstar[6] + GMinv[k][7] * _mstar[7] + GMinv[k][8] * _mstar[8];
}
}
}
}
if (BC == 0 || BC == 1)
virtualnode();
}
// Stream Methods
inline void streamPush() {
#pragma omp parallel
{
int inew, jnew;
#pragma omp for collapse(3)
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
for (int k = 0; k < Q; k++) {
inew = i + c[k][0];
jnew = j + c[k][1];
if (inew < N && inew >= 0 && jnew < M && jnew >= 0)
_f2[LU3(inew, jnew, k)] = _fstar[LU3(i, j, k)];
}
}
}
}
}
inline void streamPull() {
#pragma omp parallel
{
int iold, jold;
#pragma omp for collapse(3)
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
for (int k = 0; k < Q; k++) {
iold = i - c[k][0];
jold = j - c[k][1];
if (iold < N && iold >= 0 && jold < M && jold >= 0)
_f2[LU3(i, j, k)] = _fstar[LU3(iold, jold, k)];
}
}
}
}
}
// Bounday Condition Methods
// Wind tunnel simulation
inline void uniformFlow(){
double rho{1.0}, sixth=1.0/6.0,twothirds=2.0/3.0,twelfth=1.0/12.0,Ucorner{};
// Outflow, 2nd order polynomial extrapolation
double uout{};
for (int i = 1; i < Mm1 ;i++) {
uout = -1.0 + _f2[LU3(Nm1, i, 0)] + _f2[LU3(Nm1, i, 2)] + _f2[LU3(Nm1, i, 4)] + 2.0 * (_f2[LU3(Nm1, i, 1)] + _f2[LU3(Nm1, i, 5)] + _f2[LU3(Nm1, i, 8)]);
_f2[LU3(Nm1, i, 3)] = _f2[LU3(Nm1, i, 1)] - twothirds * uout;
_f2[LU3(Nm1, i, 7)] = _f2[LU3(Nm1, i, 5)] + 0.5 * (_f2[LU3(Nm1, i, 2)]-_f2[LU3(Nm1, i, 4)]) - sixth * uout;
_f2[LU3(Nm1, i, 6)] = _f2[LU3(Nm1, i, 8)] - 0.5 * (_f2[LU3(Nm1, i, 2)]-_f2[LU3(Nm1, i, 4)]) - sixth * uout;
}
// Inflow, Dirichlet BC
for (int i = 0; i < M ;i++) {
// rho = _f2[LU3(0, i, 0)] + _f2[LU3(0, i, 2)] + _f2[LU3(0, i, 4)] + 2.0 * (_f2[LU3(0, i, 3)] + _f2[LU3(0, i, 6)] + _f2[LU3(0, i, 7)]);
_f2[LU3(0, i, 1)] = _f2[LU3(0, i, 3)] + twothirds * rho * Ulef;
_f2[LU3(0, i, 5)] = _f2[LU3(0, i, 7)] + sixth * rho * Ulef;
_f2[LU3(0, i, 8)] = _f2[LU3(0, i, 6)] + sixth * rho * Ulef;
}
// half-way Specular reflection on top and bottom
for (int i = 0; i < N; i++) {
// Top
_f2[LU3(i, Mm1, 4)] = _f2[LU3(i, Mm1, 2)];
_f2[LU3(i, Mm1, 7)] = _f2[LU3(i, Mm1, 6)];
_f2[LU3(i, Mm1, 8)] = _f2[LU3(i, Mm1, 5)];
// Bottom
_f2[LU3(i, 0, 2)] = _f2[LU3(i, 0, 4)];
_f2[LU3(i, 0, 5)] = _f2[LU3(i, 0, 8)];
_f2[LU3(i, 0, 6)] = _f2[LU3(i, 0, 7)];
}
// Top Left (0,Nm1) knowns: 1,4,8, unknowns: 0, 5, 7
// rho = _rho[LU2(0,Mm1)];
// Ucorner = Ulef;
// _f2[LU3(0, Mm1, 1)] = _f2[LU3(0, Mm1, 3)] + twothirds * rho * Ucorner;
// _f2[LU3(0, Mm1, 4)] = _f2[LU3(0, Mm1, 2)];
// _f2[LU3(0, Mm1, 8)] = _f2[LU3(0, Mm1, 6)] + sixth * rho * (Ucorner);
// _f2[LU3(0, Mm1, 5)] = twelfth * rho * (Ucorner);
// _f2[LU3(0, Mm1, 7)] = -_f2[LU3(0, Mm1, 5)];
// _f2[LU3(0, Mm1, 0)] = rho - (_f2[LU3(0, Mm1, 1)] + _f2[LU3(0, Mm1, 2)] + _f2[LU3(0, Mm1, 3)] + _f2[LU3(0, Mm1, 4)] + _f2[LU3(0, Mm1, 5)] + _f2[LU3(0, Mm1, 6)] + _f2[LU3(0, Mm1, 7)] + _f2[LU3(0, Mm1, 8)]);
// rho = _rho[LU2(0,0)];
// Ucorner = Ulef;
// _f2[LU3(0, 0, 1)] = _f2[LU3(0, 0, 3)] + twothirds * rho * Ucorner;
// _f2[LU3(0, 0, 2)] = _f2[LU3(0, 0, 4)];
// _f2[LU3(0, 0, 5)] = _f2[LU3(0, 0, 7)] + sixth * rho * (Ucorner);
// _f2[LU3(0, 0, 6)] = twelfth * rho * (Ucorner);
// _f2[LU3(0, 0, 8)] = -_f2[LU3(0, 0, 6)];
// _f2[LU3(0, 0, 0)] = rho - (_f2[LU3(0, 0, 1)] + _f2[LU3(0, 0, 2)] + _f2[LU3(0, 0, 3)] + _f2[LU3(0, 0, 4)] + _f2[LU3(0, 0, 5)] + _f2[LU3(0, 0, 6)] + _f2[LU3(0, 0, 7)] + _f2[LU3(0, 0, 8)]);
}
inline void NEBB(){
switch (BC){
case 2 : { // Lid-driven cavity flow
const double sixth = 1.0 / 6.0, twothirds = 2.0 / 3.0, twelfth = 1.0 / 12.0;
double rho{_rhobar},Ucorner{},Vcorner{};
#pragma omp parallel for private(rho)
for (int i = 1; i < N - 1; i++) {
// Top wall, general case
rho = _f2[LU3(i, Mm1, 0)] + _f2[LU3(i, Mm1, 1)] + _f2[LU3(i, Mm1, 3)] + 2.0 * (_f2[LU3(i, Mm1, 2)] + _f2[LU3(i, Mm1, 6)] + _f2[LU3(i, Mm1, 5)]);
_f2[LU3(i, Mm1, 4)] = _f2[LU3(i, Mm1, 2)] - twothirds * rho * Vtop;
_f2[LU3(i, Mm1, 7)] = _f2[LU3(i, Mm1, 5)] + 0.5 * (_f2[LU3(i, Mm1, 1)] - _f2[LU3(i, Mm1, 3)]) - 0.5 * rho * Utop - sixth * rho * Vtop;
_f2[LU3(i, Mm1, 8)] = _f2[LU3(i, Mm1, 6)] - 0.5 * (_f2[LU3(i, Mm1, 1)] - _f2[LU3(i, Mm1, 3)]) + 0.5 * rho * Utop - sixth * rho * Vtop;
// Bottom wall, general case
rho = _f2[LU3(i, 0, 0)] + _f2[LU3(i, 0, 1)] + _f2[LU3(i, 0, 3)] + 2.0 * (_f2[LU3(i, 0, 4)] + _f2[LU3(i, 0, 7)] + _f2[LU3(i, 0, 8)]);
_f2[LU3(i, 0, 2)] = _f2[LU3(i, 0, 4)] + twothirds * rho * Vbot;
_f2[LU3(i, 0, 5)] = _f2[LU3(i, 0, 7)] - 0.5 * (_f2[LU3(i, 0, 1)] - _f2[LU3(i, 0, 3)]) + 0.5 * rho * Ubot + sixth * rho * Vbot;
_f2[LU3(i, 0, 6)] = _f2[LU3(i, 0, 8)] + 0.5 * (_f2[LU3(i, 0, 1)] - _f2[LU3(i, 0, 3)]) - 0.5 * rho * Ubot + sixth * rho * Vbot;
}
#pragma omp parallel for private(rho)
for (int i = 1; i < Mm1; i++) {
// Left wall, general case
rho = _f2[LU3(0, i, 0)] + _f2[LU3(0, i, 2)] + _f2[LU3(0, i, 4)] + 2.0 * (_f2[LU3(0, i, 3)] + _f2[LU3(0, i, 6)] + _f2[LU3(0, i, 7)]);
_f2[LU3(0, i, 1)] = _f2[LU3(0, i, 3)] + twothirds * rho * Ulef;
_f2[LU3(0, i, 5)] = _f2[LU3(0, i, 7)] - 0.5 * (_f2[LU3(0, i, 2)] - _f2[LU3(0, i, 4)]) + 0.5 * rho * Vlef + sixth * rho * Ulef;
_f2[LU3(0, i, 8)] = _f2[LU3(0, i, 6)] + 0.5 * (_f2[LU3(0, i, 2)] - _f2[LU3(0, i, 4)]) - 0.5 * rho * Vlef + sixth * rho * Ulef;
// Right wall, general case
rho = _f2[LU3(Nm1, i, 0)] + _f2[LU3(Nm1, i, 2)] + _f2[LU3(Nm1, i, 4)] + 2.0 * (_f2[LU3(Nm1, i, 1)] + _f2[LU3(Nm1, i, 5)] + _f2[LU3(Nm1, i, 8)]);
_f2[LU3(Nm1, i, 3)] = _f2[LU3(Nm1, i, 1)] - twothirds * rho * Urig;
_f2[LU3(Nm1, i, 7)] = _f2[LU3(Nm1, i, 5)] + 0.5 * (_f2[LU3(Nm1, i, 2)] - _f2[LU3(Nm1, i, 4)]) - 0.5 * rho * Vrig - sixth * rho * Urig;
_f2[LU3(Nm1, i, 6)] = _f2[LU3(Nm1, i, 8)] - 0.5 * (_f2[LU3(Nm1, i, 2)] - _f2[LU3(Nm1, i, 4)]) + 0.5 * rho * Vrig - sixth * rho * Urig;
}
// Corners
rho = _rhobar;
// Bottom Left (0,0) knowns: 1,5,2, unknowns: 0,6,8
rho = _rho[LU2(0,0)];
Vcorner = max(Vbot, Vlef);
Ucorner = max(Ubot, Ulef);
_f2[LU3(0, 0, 1)] = _f2[LU3(0, 0, 3)] + twothirds * rho * Ucorner;
_f2[LU3(0, 0, 2)] = _f2[LU3(0, 0, 4)] + twothirds * rho * Vcorner;
_f2[LU3(0, 0, 5)] = _f2[LU3(0, 0, 7)] + sixth * rho * (Ucorner + Vcorner);
_f2[LU3(0, 0, 6)] = twelfth * rho * (Vcorner - Ucorner);
_f2[LU3(0, 0, 8)] = -_f2[LU3(0, 0, 6)];
_f2[LU3(0, 0, 0)] = rho - (_f2[LU3(0, 0, 1)] + _f2[LU3(0, 0, 2)] + _f2[LU3(0, 0, 3)] + _f2[LU3(0, 0, 4)] + _f2[LU3(0, 0, 5)] + _f2[LU3(0, 0, 6)] + _f2[LU3(0, 0, 7)] + _f2[LU3(0, 0, 8)]);
// Bottom Right (Nm1,0) knowns: 2,3,6, unknowns: 0, 5, 7
rho = _rho[LU2(Nm1,0)];
Vcorner = max(Vbot, Vrig);
Ucorner = max(Ubot, Urig);
_f2[LU3(Nm1, 0, 2)] = _f2[LU3(Nm1, 0, 4)] + twothirds * rho * Vcorner;
_f2[LU3(Nm1, 0, 3)] = _f2[LU3(Nm1, 0, 1)] - twothirds * rho * Ucorner;
_f2[LU3(Nm1, 0, 6)] = _f2[LU3(Nm1, 0, 8)] + sixth * rho * (-Ucorner + Vcorner);
_f2[LU3(Nm1, 0, 5)] = twelfth * rho * (Vcorner + Ucorner);
_f2[LU3(Nm1, 0, 7)] = -_f2[LU3(Nm1, 0, 5)];
_f2[LU3(Nm1, 0, 0)] = rho - (_f2[LU3(Nm1, 0, 1)] + _f2[LU3(Nm1, 0, 2)] + _f2[LU3(Nm1, 0, 3)] + _f2[LU3(Nm1, 0, 4)] + _f2[LU3(Nm1, 0, 5)] + _f2[LU3(Nm1, 0, 6)] + _f2[LU3(Nm1, 0, 7)] + _f2[LU3(Nm1, 0, 8)]);
// Top Left (0,Nm1) knowns: 1,4,8, unknowns: 0, 5, 7
rho = _rho[LU2(0,Mm1)];
Vcorner = max(Vtop, Vlef);
Ucorner = max(Utop, Ulef);
_f2[LU3(0, Mm1, 1)] = _f2[LU3(0, Mm1, 3)] + twothirds * rho * Ucorner;
_f2[LU3(0, Mm1, 4)] = _f2[LU3(0, Mm1, 2)] - twothirds * rho * Vcorner;
_f2[LU3(0, Mm1, 8)] = _f2[LU3(0, Mm1, 6)] + sixth * rho * (Ucorner - Vcorner);
_f2[LU3(0, Mm1, 5)] = twelfth * rho * (Vcorner + Ucorner);
_f2[LU3(0, Mm1, 7)] = -_f2[LU3(0, Mm1, 5)];
_f2[LU3(0, Mm1, 0)] = rho - (_f2[LU3(0, Mm1, 1)] + _f2[LU3(0, Mm1, 2)] + _f2[LU3(0, Mm1, 3)] + _f2[LU3(0, Mm1, 4)] + _f2[LU3(0, Mm1, 5)] + _f2[LU3(0, Mm1, 6)] + _f2[LU3(0, Mm1, 7)] + _f2[LU3(0, Mm1, 8)]);
// Top Right (Nm1,Nm1) knowns: 3,7,4, unknowns: 0, 6, 8
rho = _rho[LU2(Nm1,Mm1)];
Vcorner = max(Vtop, Vrig);
Ucorner = max(Utop, Urig);
_f2[LU3(Nm1, Mm1, 4)] = _f2[LU3(Nm1, Mm1, 2)] - twothirds * rho * Vcorner;
_f2[LU3(Nm1, Mm1, 3)] = _f2[LU3(Nm1, Mm1, 1)] - twothirds * rho * Ucorner;
_f2[LU3(Nm1, Mm1, 7)] = _f2[LU3(Nm1, Mm1, 5)] - sixth * rho * (Ucorner + Vcorner);
_f2[LU3(Nm1, Mm1, 6)] = twelfth * rho * (Vcorner - Ucorner);
_f2[LU3(Nm1, Mm1, 8)] = -_f2[LU3(Nm1, Mm1, 6)];
_f2[LU3(Nm1, Mm1, 0)] = rho - (_f2[LU3(Nm1, Mm1, 1)] + _f2[LU3(Nm1, Mm1, 2)] + _f2[LU3(Nm1, Mm1, 3)] + _f2[LU3(Nm1, Mm1, 4)] + _f2[LU3(Nm1, Mm1, 5)] + _f2[LU3(Nm1, Mm1, 6)] + _f2[LU3(Nm1, Mm1, 7)] + _f2[LU3(Nm1, Mm1, 8)]);
break;
}
case 1: { // Poiseuille Flow
#pragma omp parallel for
for (int i = 0; i < N; i++) {
// Top wall, general case
_f2[LU3(i, Mm1, 4)] = _f2[LU3(i, Mm1, 2)];
_f2[LU3(i, Mm1, 7)] = _f2[LU3(i, Mm1, 5)] + 0.5 * (_f2[LU3(i, Mm1, 1)] - _f2[LU3(i, Mm1, 3)]);
_f2[LU3(i, Mm1, 8)] = _f2[LU3(i, Mm1, 6)] - 0.5 * (_f2[LU3(i, Mm1, 1)] - _f2[LU3(i, Mm1, 3)]);
// Bottom wall, general case
_f2[LU3(i, 0, 2)] = _f2[LU3(i, 0, 4)];
_f2[LU3(i, 0, 5)] = _f2[LU3(i, 0, 7)] - 0.5 * (_f2[LU3(i, 0, 1)] - _f2[LU3(i, 0, 3)]);
_f2[LU3(i, 0, 6)] = _f2[LU3(i, 0, 8)] + 0.5 * (_f2[LU3(i, 0, 1)] - _f2[LU3(i, 0, 3)]);
}
break;
}
case 0: { // Couette Flow
double rho{};
#pragma omp parallel for private(rho)
for (int i = 0; i < N; i++) {
// Top wall, general case
rho = _f2[LU3(i, Mm1, 0)] + _f2[LU3(i, Mm1, 1)] + _f2[LU3(i, Mm1, 3)] + 2.0 * (_f2[LU3(i, Mm1, 2)] + _f2[LU3(i, Mm1, 6)] + _f2[LU3(i, Mm1, 5)]);
_f2[LU3(i, Mm1, 4)] = _f2[LU3(i, Mm1, 2)];
_f2[LU3(i, Mm1, 7)] = _f2[LU3(i, Mm1, 5)] + 0.5 * (_f2[LU3(i, Mm1, 1)] - _f2[LU3(i, Mm1, 3)]) - 0.5 * rho * Utop;
_f2[LU3(i, Mm1, 8)] = _f2[LU3(i, Mm1, 6)] - 0.5 * (_f2[LU3(i, Mm1, 1)] - _f2[LU3(i, Mm1, 3)]) + 0.5 * rho * Utop;
// Bottom wall, general case
rho = _f2[LU3(i, 0, 0)] + _f2[LU3(i, 0, 1)] + _f2[LU3(i, 0, 3)] + 2.0 * (_f2[LU3(i, 0, 4)] + _f2[LU3(i, 0, 7)] + _f2[LU3(i, 0, 8)]);
_f2[LU3(i, 0, 2)] = _f2[LU3(i, 0, 4)];
_f2[LU3(i, 0, 5)] = _f2[LU3(i, 0, 7)] - 0.5 * (_f2[LU3(i, 0, 1)] - _f2[LU3(i, 0, 3)]) + 0.5 * rho * Ubot;
_f2[LU3(i, 0, 6)] = _f2[LU3(i, 0, 8)] + 0.5 * (_f2[LU3(i, 0, 1)] - _f2[LU3(i, 0, 3)]) - 0.5 * rho * Ubot;
}
break;
}
default: {
std::printf("Error: Invalid Boundary condition case number\n");
exit(1);
}
}
}
// Non-equilibrium extrapolation
inline void NEE() {
switch (BC){
case 2: { // Lid-driven cavity flow
#pragma omp parallel
{
double rhof{},u1f{},u2f{};
double rhowall{_rhobar};
#pragma omp for
for (int i = 1; i < N-1; i++){
// Bottom wall, (i, 0)
rhowall = _f2[LU3(i,0,0)] +_f2[LU3(i,0,1)] +_f2[LU3(i,0,3)] + 2.0 * (_f2[LU3(i,0,4)] +_f2[LU3(i,0,7)] +_f2[LU3(i,0,8)]);
rhof = _f2[LU3(i,1,0)] + _f2[LU3(i,1,1)] + _f2[LU3(i,1,2)] + _f2[LU3(i,1,3)] + _f2[LU3(i,1,4)] + _f2[LU3(i,1,5)]+ _f2[LU3(i,1,6)]+ _f2[LU3(i,1,7)]+ _f2[LU3(i,1,8)];
u1f = ((_f2[LU3(i,1,1)] + _f2[LU3(i,1,5)] + _f2[LU3(i,1,8)]) - (_f2[LU3(i,1,3)] + _f2[LU3(i,1,6)] + _f2[LU3(i,1,7)]));
u2f = ((_f2[LU3(i,1,2)] + _f2[LU3(i,1,5)] + _f2[LU3(i,1,6)]) - (_f2[LU3(i,1,4)] + _f2[LU3(i,1,7)] + _f2[LU3(i,1,8)]));
if (INCOMP != 1){
u1f /= rhof;
u2f /= rhof;
}
for (int k = 0; k < Q; k++)
_f2[LU3(i,0,k)] = calcfeq(k,Ubot,Vbot,rhowall) + (_f2[LU3(i,1,k)] - calcfeq(k, u1f, u2f, rhof));
// Top Wall, (i,Nm1)
rhowall = _f2[LU3(i,Mm1,0)] +_f2[LU3(i,Mm1,1)] +_f2[LU3(i,Mm1,3)] + 2.0 * (_f2[LU3(i,Mm1,2)] +_f2[LU3(i,Mm1,6)] +_f2[LU3(i,Mm1,5)]);
rhof = _f2[LU3(i,Mm2,0)] + _f2[LU3(i,Mm2,1)] + _f2[LU3(i,Mm2,2)] + _f2[LU3(i,Mm2,3)] + _f2[LU3(i,Mm2,4)] + _f2[LU3(i,Mm2,5)]+ _f2[LU3(i,Mm2,6)]+ _f2[LU3(i,Mm2,7)]+ _f2[LU3(i,Mm2,8)];
u1f = ((_f2[LU3(i,Mm2,1)] + _f2[LU3(i,Mm2,5)] + _f2[LU3(i,Mm2,8)]) - (_f2[LU3(i,Mm2,3)] + _f2[LU3(i,Mm2,6)] + _f2[LU3(i,Mm2,7)]));
u2f = ((_f2[LU3(i,Mm2,2)] + _f2[LU3(i,Mm2,5)] + _f2[LU3(i,Mm2,6)]) - (_f2[LU3(i,Mm2,4)] + _f2[LU3(i,Mm2,7)] + _f2[LU3(i,Mm2,8)]));
if (INCOMP != 1){
u1f /= rhof;
u2f /= rhof;
}
for (int k = 0; k < Q; k++)
_f2[LU3(i,Mm1,k)] = calcfeq(k,Utop,Vtop,rhowall) + (_f2[LU3(i,Mm2,k)] - calcfeq(k, u1f, u2f, rhof));
}
#pragma omp for
for (int i = 1; i < Mm1; i++){
// Left wall, (0,i)
rhowall = _f2[LU3(0,i,0)] +_f2[LU3(0,i,2)] +_f2[LU3(0,i,4)] + 2.0 * (_f2[LU3(0,i,3)] +_f2[LU3(0,i,6)] +_f2[LU3(0,i,7)]);
rhof = _f2[LU3(1,i,0)] + _f2[LU3(1,i,1)] + _f2[LU3(1,i,2)] + _f2[LU3(1,i,3)] + _f2[LU3(1,i,4)] + _f2[LU3(1,i,5)]+ _f2[LU3(1,i,6)]+ _f2[LU3(1,i,7)]+ _f2[LU3(1,i,8)];
u1f = ((_f2[LU3(1,i,1)] + _f2[LU3(1,i,5)] + _f2[LU3(1,i,8)]) - (_f2[LU3(1,i,3)] + _f2[LU3(1,i,6)] + _f2[LU3(1,i,7)]));
u2f = ((_f2[LU3(1,i,2)] + _f2[LU3(1,i,5)] + _f2[LU3(1,i,6)]) - (_f2[LU3(1,i,4)] + _f2[LU3(1,i,7)] + _f2[LU3(1,i,8)]));
if (INCOMP != 1){
u1f /= rhof;
u2f /= rhof;
}
for (int k = 0; k < Q; k++)
_f2[LU3(0,i,k)] = calcfeq(k,Ulef,Vlef,rhowall) + (_f2[LU3(1,i,k)] - calcfeq(k, u1f, u2f, rhof));
// Right Wall (Nm1, i)
rhowall = _f2[LU3(Nm1,i,0)] +_f2[LU3(Nm1,i,2)] +_f2[LU3(Nm1,i,4)] + 2.0 * (_f2[LU3(Nm1,i,1)] +_f2[LU3(Nm1,i,5)] +_f2[LU3(Nm1,i,8)]);
rhof = _f2[LU3(Nm2,i,0)] + _f2[LU3(Nm2,i,1)] + _f2[LU3(Nm2,i,2)] + _f2[LU3(Nm2,i,3)] + _f2[LU3(Nm2,i,4)] + _f2[LU3(Nm2,i,5)]+ _f2[LU3(Nm2,i,6)]+ _f2[LU3(Nm2,i,7)]+ _f2[LU3(Nm2,i,8)];
u1f = ((_f2[LU3(Nm2,i,1)] + _f2[LU3(Nm2,i,5)] + _f2[LU3(Nm2,i,8)]) - (_f2[LU3(Nm2,i,3)] + _f2[LU3(Nm2,i,6)] + _f2[LU3(Nm2,i,7)]));
u2f = ((_f2[LU3(Nm2,i,2)] + _f2[LU3(Nm2,i,5)] + _f2[LU3(Nm2,i,6)]) - (_f2[LU3(Nm2,i,4)] + _f2[LU3(Nm2,i,7)] + _f2[LU3(Nm2,i,8)]));
if (INCOMP != 1){
u1f /= rhof;
u2f /= rhof;
}
for (int k = 0; k < Q; k++)
_f2[LU3(Nm1,i,k)] = calcfeq(k,Urig,Vrig,rhowall) + (_f2[LU3(Nm2,i,k)] - calcfeq(k, u1f, u2f, rhof));
}
// Corners
// Bottom left (0,0)
rhof = _f2[LU3(1,1,0)] + _f2[LU3(1,1,1)] + _f2[LU3(1,1,2)] + _f2[LU3(1,1,3)] + _f2[LU3(1,1,4)] + _f2[LU3(1,1,5)]+ _f2[LU3(1,1,6)]+ _f2[LU3(1,1,7)]+ _f2[LU3(1,1,8)];
u1f = ((_f2[LU3(1,1,1)] + _f2[LU3(1,1,5)] + _f2[LU3(1,1,8)]) - (_f2[LU3(1,1,3)] + _f2[LU3(1,1,6)] + _f2[LU3(1,1,7)]));
u2f = ((_f2[LU3(1,1,2)] + _f2[LU3(1,1,5)] + _f2[LU3(1,1,6)]) - (_f2[LU3(1,1,4)] + _f2[LU3(1,1,7)] + _f2[LU3(1,1,8)]));
if (INCOMP != 1){
u1f /= rhof;
u2f /= rhof;
}
rhowall = _rho[LU2(0,0)];
rhowall = rhof;
#pragma omp for
for (int k = 0; k < Q; k++)
_f2[LU3(0,0,k)] = calcfeq(k,Ubot,Vlef,rhowall) + (_f2[LU3(1,1,k)] - calcfeq(k, u1f, u2f, rhof));
// Bottom Right (Nm1,0)
rhof = _f2[LU3(Nm2,1,0)] + _f2[LU3(Nm2,1,1)] + _f2[LU3(Nm2,1,2)] + _f2[LU3(Nm2,1,3)] + _f2[LU3(Nm2,1,4)] + _f2[LU3(Nm2,1,5)]+ _f2[LU3(Nm2,1,6)]+ _f2[LU3(Nm2,1,7)]+ _f2[LU3(Nm2,1,8)];
u1f = ((_f2[LU3(Nm2,1,1)] + _f2[LU3(Nm2,1,5)] + _f2[LU3(Nm2,1,8)]) - (_f2[LU3(Nm2,1,3)] + _f2[LU3(Nm2,1,6)] + _f2[LU3(Nm2,1,7)]));
u2f = ((_f2[LU3(Nm2,1,2)] + _f2[LU3(Nm2,1,5)] + _f2[LU3(Nm2,1,6)]) - (_f2[LU3(Nm2,1,4)] + _f2[LU3(Nm2,1,7)] + _f2[LU3(Nm2,1,8)]));
if (INCOMP != 1){
u1f /= rhof;
u2f /= rhof;
}
rhowall = _rho[LU2(Nm1,0)];
rhowall = rhof;
#pragma omp for
for (int k = 0; k < Q; k++)
_f2[LU3(Nm1,0,k)] = calcfeq(k,Ubot,Vrig,rhowall) + (_f2[LU3(Nm2,1,k)] - calcfeq(k, u1f, u2f, rhof));
// Top Right (Nm1,Nm1)
rhof = _f2[LU3(Nm2,Mm2,0)] + _f2[LU3(Nm2,Mm2,1)] + _f2[LU3(Nm2,Mm2,2)] + _f2[LU3(Nm2,Mm2,3)] + _f2[LU3(Nm2,Mm2,4)] + _f2[LU3(Nm2,Mm2,5)]+ _f2[LU3(Nm2,Mm2,6)]+ _f2[LU3(Nm2,Mm2,7)]+ _f2[LU3(Nm2,Mm2,8)];
u1f = ((_f2[LU3(Nm2,Mm2,1)] + _f2[LU3(Nm2,Mm2,5)] + _f2[LU3(Nm2,Mm2,8)]) - (_f2[LU3(Nm2,Mm2,3)] + _f2[LU3(Nm2,Mm2,6)] + _f2[LU3(Nm2,Mm2,7)]));
u2f = ((_f2[LU3(Nm2,Mm2,2)] + _f2[LU3(Nm2,Mm2,5)] + _f2[LU3(Nm2,Mm2,6)]) - (_f2[LU3(Nm2,Mm2,4)] + _f2[LU3(Nm2,Mm2,7)] + _f2[LU3(Nm2,Mm2,8)]));
if (INCOMP != 1){
u1f /= rhof;
u2f /= rhof;
}
rhowall = _rho[LU2(Nm1,Mm1)];
rhowall = rhof;
#pragma omp for
for (int k = 0; k < Q; k++)
_f2[LU3(Nm1,Mm1,k)] = calcfeq(k,Utop,Vrig,rhowall) + (_f2[LU3(Nm2,Mm2,k)] - calcfeq(k, u1f, u2f, rhof));
// Top Left (0,Nm1)
rhof = _f2[LU3(1,Mm2,0)] + _f2[LU3(1,Mm2,1)] + _f2[LU3(1,Mm2,2)] + _f2[LU3(1,Mm2,3)] + _f2[LU3(1,Mm2,4)] + _f2[LU3(1,Mm2,5)]+ _f2[LU3(1,Mm2,6)]+ _f2[LU3(1,Mm2,7)]+ _f2[LU3(1,Mm2,8)];
u1f = ((_f2[LU3(1,Mm2,1)] + _f2[LU3(1,Mm2,5)] + _f2[LU3(1,Mm2,8)]) - (_f2[LU3(1,Mm2,3)] + _f2[LU3(1,Mm2,6)] + _f2[LU3(1,Mm2,7)]));
u2f = ((_f2[LU3(1,Mm2,2)] + _f2[LU3(1,Mm2,5)] + _f2[LU3(1,Mm2,6)]) - (_f2[LU3(1,Mm2,4)] + _f2[LU3(1,Mm2,7)] + _f2[LU3(1,Mm2,8)]));
if (INCOMP != 1){
u1f /= rhof;
u2f /= rhof;
}
rhowall = _rho[LU2(0,Mm1)];
rhowall = rhof;
#pragma omp for
for (int k = 0; k < Q; k++)
_f2[LU3(0,Mm1,k)] = calcfeq(k,Utop,Vlef,rhowall) + (_f2[LU3(1,Mm2,k)] - calcfeq(k, u1f, u2f, rhof));
};
break;
}
case 1: { // Poiseuille Flow
#pragma omp parallel
{
double rhof{},u1f{},u2f{};
double rhowall{1.0};
#pragma omp for
for (int i = 1; i < N-1; i++){
// Bottom wall, (i, 0)
rhowall = _f2[LU3(i,0,0)] +_f2[LU3(i,0,1)] +_f2[LU3(i,0,3)] + 2.0 * (_f2[LU3(i,0,4)] +_f2[LU3(i,0,7)] +_f2[LU3(i,0,8)]);
rhof = _f2[LU3(i,1,0)] + _f2[LU3(i,1,1)] + _f2[LU3(i,1,2)] + _f2[LU3(i,1,3)] + _f2[LU3(i,1,4)] + _f2[LU3(i,1,5)]+ _f2[LU3(i,1,6)]+ _f2[LU3(i,1,7)]+ _f2[LU3(i,1,8)];
u1f = ((_f2[LU3(i,1,1)] + _f2[LU3(i,1,5)] + _f2[LU3(i,1,8)]) - (_f2[LU3(i,1,3)] + _f2[LU3(i,1,6)] + _f2[LU3(i,1,7)])) / rhof;
u2f = ((_f2[LU3(i,1,2)] + _f2[LU3(i,1,5)] + _f2[LU3(i,1,6)]) - (_f2[LU3(i,1,4)] + _f2[LU3(i,1,7)] + _f2[LU3(i,1,8)])) / rhof;
for (int k = 0; k < Q; k++)
_f2[LU3(i,0,k)] = calcfeq(k,0.0,0.0,rhowall) + (_f2[LU3(i,1,k)] - calcfeq(k, u1f, u2f, rhof));
// Top Wall, (i,Nm1)
rhowall = _f2[LU3(i,Mm1,0)] +_f2[LU3(i,Mm1,1)] +_f2[LU3(i,Mm1,3)] + 2.0 * (_f2[LU3(i,Mm1,2)] +_f2[LU3(i,Mm1,6)] +_f2[LU3(i,Mm1,5)]);
rhof = _f2[LU3(i,Mm2,0)] + _f2[LU3(i,Mm2,1)] + _f2[LU3(i,Mm2,2)] + _f2[LU3(i,Mm2,3)] + _f2[LU3(i,Mm2,4)] + _f2[LU3(i,Mm2,5)]+ _f2[LU3(i,Mm2,6)]+ _f2[LU3(i,Mm2,7)]+ _f2[LU3(i,Mm2,8)];
u1f = ((_f2[LU3(i,Mm2,1)] + _f2[LU3(i,Mm2,5)] + _f2[LU3(i,Mm2,8)]) - (_f2[LU3(i,Mm2,3)] + _f2[LU3(i,Mm2,6)] + _f2[LU3(i,Mm2,7)])) / rhof;
u2f = ((_f2[LU3(i,Mm2,2)] + _f2[LU3(i,Mm2,5)] + _f2[LU3(i,Mm2,6)]) - (_f2[LU3(i,Mm2,4)] + _f2[LU3(i,Mm2,7)] + _f2[LU3(i,Mm2,8)])) / rhof;
for (int k = 0; k < Q; k++)
_f2[LU3(i,Mm1,k)] = calcfeq(k,0.0,0.0,rhowall) + (_f2[LU3(i,Mm2,k)] - calcfeq(k, u1f, u2f, rhof));
}
}
break;
}
case 0: { // Couette Flow
#pragma omp parallel
{
double rhof{},u1f{},u2f{};
double rhowall{1.0};
#pragma omp for
for (int i = 1; i < N-1; i++){
// Bottom wall, (i, 0)
rhowall = _f2[LU3(i,0,0)] +_f2[LU3(i,0,1)] +_f2[LU3(i,0,3)] + 2.0 * (_f2[LU3(i,0,4)] +_f2[LU3(i,0,7)] +_f2[LU3(i,0,8)]);
rhof = _f2[LU3(i,1,0)] + _f2[LU3(i,1,1)] + _f2[LU3(i,1,2)] + _f2[LU3(i,1,3)] + _f2[LU3(i,1,4)] + _f2[LU3(i,1,5)]+ _f2[LU3(i,1,6)]+ _f2[LU3(i,1,7)]+ _f2[LU3(i,1,8)];
u1f = ((_f2[LU3(i,1,1)] + _f2[LU3(i,1,5)] + _f2[LU3(i,1,8)]) - (_f2[LU3(i,1,3)] + _f2[LU3(i,1,6)] + _f2[LU3(i,1,7)])) / rhof;
u2f = ((_f2[LU3(i,1,2)] + _f2[LU3(i,1,5)] + _f2[LU3(i,1,6)]) - (_f2[LU3(i,1,4)] + _f2[LU3(i,1,7)] + _f2[LU3(i,1,8)])) / rhof;
for (int k = 0; k < Q; k++)
_f2[LU3(i,0,k)] = calcfeq(k,Ubot,0.0,rhowall) + (_f2[LU3(i,1,k)] - calcfeq(k, u1f, u2f, rhof));
// Top Wall, (i,Nm1)
rhowall = _f2[LU3(i,Mm1,0)] +_f2[LU3(i,Mm1,1)] +_f2[LU3(i,Mm1,3)] + 2.0 * (_f2[LU3(i,Mm1,2)] +_f2[LU3(i,Mm1,6)] +_f2[LU3(i,Mm1,5)]);
rhof = _f2[LU3(i,Mm2,0)] + _f2[LU3(i,Mm2,1)] + _f2[LU3(i,Mm2,2)] + _f2[LU3(i,Mm2,3)] + _f2[LU3(i,Mm2,4)] + _f2[LU3(i,Mm2,5)]+ _f2[LU3(i,Mm2,6)]+ _f2[LU3(i,Mm2,7)]+ _f2[LU3(i,Mm2,8)];
u1f = ((_f2[LU3(i,Mm2,1)] + _f2[LU3(i,Mm2,5)] + _f2[LU3(i,Mm2,8)]) - (_f2[LU3(i,Mm2,3)] + _f2[LU3(i,Mm2,6)] + _f2[LU3(i,Mm2,7)])) / rhof;
u2f = ((_f2[LU3(i,Mm2,2)] + _f2[LU3(i,Mm2,5)] + _f2[LU3(i,Mm2,6)]) - (_f2[LU3(i,Mm2,4)] + _f2[LU3(i,Mm2,7)] + _f2[LU3(i,Mm2,8)])) / rhof;
for (int k = 0; k < Q; k++)
_f2[LU3(i,Mm1,k)] = calcfeq(k,Utop,0.0,rhowall) + (_f2[LU3(i,Mm2,k)] - calcfeq(k, u1f, u2f, rhof));
}
}
break;
}
default: {
std::printf("Error: Invalid Boundary condition case number\n");
exit(1);
}
}
};
inline void HWBB(){
double rhowall = _rhobar;
switch (BC){
case 2: { // Lid-driven cavity flow
#pragma omp parallel for
for (int i = 1; i < Mm1; i++){
// Left wall
// rhowall = _f2[LU3(0,i,0)] +_f2[LU3(0,i,2)] +_f2[LU3(0,i,4)] + 2.0 * (_f2[LU3(0,i,3)] +_f2[LU3(0,i,6)] +_f2[LU3(0,i,7)]);
_f2[LU3(0, i, 5)] = _fstar[LU3(0, i, 7)] - 2.0 * w[7] * rhowall * c[7][1] * Vlef * 3.0;
_f2[LU3(0, i, 1)] = _fstar[LU3(0, i, 3)];
_f2[LU3(0, i, 8)] = _fstar[LU3(0, i, 6)] - 2.0 * w[6] * rhowall * c[6][1] * Vlef * 3.0;
// Right wall
// rhowall = _f2[LU3(Nm1,i,0)] +_f2[LU3(Nm1,i,2)] +_f2[LU3(Nm1,i,4)] + 2.0 * (_f2[LU3(Nm1,i,1)] +_f2[LU3(Nm1,i,5)] +_f2[LU3(Nm1,i,8)]);
_f2[LU3(Nm1, i, 7)] = _fstar[LU3(Nm1, i, 5)] - 2.0 * w[5] * rhowall * c[5][1] * Vrig * 3.0;
_f2[LU3(Nm1, i, 3)] = _fstar[LU3(Nm1, i, 1)];
_f2[LU3(Nm1, i, 6)] = _fstar[LU3(Nm1, i, 8)] - 2.0 * w[8] * rhowall * c[8][1] * Vrig * 3.0;
}
#pragma omp parallel for
for (int i = 1; i < Nm1; i++){
// Bottom wall
// rhowall = _f2[LU3(i,0,0)] +_f2[LU3(i,0,1)] +_f2[LU3(i,0,3)] + 2.0 * (_f2[LU3(i,0,4)] +_f2[LU3(i,0,7)] +_f2[LU3(i,0,8)]);
_f2[LU3(i, 0, 6)] = _fstar[LU3(i, 0, 8)] - 2.0 * w[8] * rhowall * c[8][0] * Ubot * 3.0;
_f2[LU3(i, 0, 2)] = _fstar[LU3(i, 0, 4)];
_f2[LU3(i, 0, 5)] = _fstar[LU3(i, 0, 7)] - 2.0 * w[7] * rhowall * c[7][0] * Ubot * 3.0;
// Top wall
// rhowall = _f2[LU3(i,Mm1,0)] +_f2[LU3(i,Mm1,1)] +_f2[LU3(i,Mm1,3)] + 2.0 * (_f2[LU3(i,Mm1,2)] +_f2[LU3(i,Mm1,6)] +_f2[LU3(i,Mm1,5)]);
_f2[LU3(i, Mm1, 8)] = _fstar[LU3(i, Mm1, 6)] - 2.0 * w[6] * rhowall * c[6][0] * Utop * 3.0;
_f2[LU3(i, Mm1, 4)] = _fstar[LU3(i, Mm1, 2)];
_f2[LU3(i, Mm1, 7)] = _fstar[LU3(i, Mm1, 5)] - 2.0 * w[5] * rhowall * c[5][0] * Utop * 3.0;
}
// Corners
// Top left
// rhowall = _rho[LU2(0, Mm1)];
_f2[LU3(0, Mm1, 1)] = _fstar[LU3(0, Mm1, 3)];
_f2[LU3(0, Mm1, 8)] = _fstar[LU3(0, Mm1, 6)] - 2.0 * w[6] * rhowall * (c[6][0] * Utop + c[6][1] * Vlef) * 3.0;
_f2[LU3(0, Mm1, 4)] = _fstar[LU3(0, Mm1, 2)];
// Bottom Left
// rhowall = _rho[LU2(0, 0)];
_f2[LU3(0, 0, 1)] = _fstar[LU3(0, 0, 3)];
_f2[LU3(0, 0, 5)] = _fstar[LU3(0, 0, 7)] - 2.0 * w[7] * rhowall * (c[7][0] * Ubot + c[7][1] * Vlef) * 3.0;
_f2[LU3(0, 0, 2)] = _fstar[LU3(0, 0, 4)];
// Top Right
// rhowall = _rho[LU2(Nm1, Mm1)];
_f2[LU3(Nm1, Mm1, 3)] = _fstar[LU3(Nm1, Mm1, 1)];
_f2[LU3(Nm1, Mm1, 7)] = _fstar[LU3(Nm1, Mm1, 5)] - 2.0 * w[5] * rhowall * (c[5][0] * Utop + c[5][1] * Vrig) * 3.0;
_f2[LU3(Nm1, Mm1, 4)] = _fstar[LU3(Nm1, Mm1, 2)];
// Bottom Right
// rhowall = _rho[LU2(Nm1, 0)];
_f2[LU3(Nm1, 0, 3)] = _fstar[LU3(Nm1, 0, 1)];
_f2[LU3(Nm1, 0, 6)] = _fstar[LU3(Nm1, 0, 8)] - 2.0 * w[8] * rhowall * (c[8][0] * Ubot + c[8][1] * Vrig) * 3.0;
_f2[LU3(Nm1, 0, 2)] = _fstar[LU3(Nm1, 0, 4)];
break;
}
case 1: { // Poiseuille Flow
#pragma omp parallel for
for (int i = 0; i < N; i++){
// Bottom wall
_f2[LU3(i, 0, 6)] = _fstar[LU3(i, 0, 8)];
_f2[LU3(i, 0, 2)] = _fstar[LU3(i, 0, 4)];
_f2[LU3(i, 0, 5)] = _fstar[LU3(i, 0, 7)];
// Top wall
_f2[LU3(i, Mm1, 8)] = _fstar[LU3(i, Mm1, 6)];
_f2[LU3(i, Mm1, 4)] = _fstar[LU3(i, Mm1, 2)];
_f2[LU3(i, Mm1, 7)] = _fstar[LU3(i, Mm1, 5)];
}
break;
}
case 0: { // Couette flow
#pragma omp parallel for
for (int i = 0; i < N; i++){
// Bottom wall
_f2[LU3(i, 0, 6)] = _fstar[LU3(i, 0, 8)] - 2.0 * w[8] * _rhobar * c[8][0] * Ubot * 3.0;
_f2[LU3(i, 0, 2)] = _fstar[LU3(i, 0, 4)] - 2.0 * w[4] * _rhobar * c[4][0] * Ubot * 3.0;
_f2[LU3(i, 0, 5)] = _fstar[LU3(i, 0, 7)] - 2.0 * w[7] * _rhobar * c[7][0] * Ubot * 3.0;
// Top wall
_f2[LU3(i, Mm1, 8)] = _fstar[LU3(i, Mm1, 6)] - 2.0 * w[6] * _rhobar * c[6][0] * Utop * 3.0;
_f2[LU3(i, Mm1, 4)] = _fstar[LU3(i, Mm1, 2)] - 2.0 * w[2] * _rhobar * c[2][0] * Utop * 3.0;
_f2[LU3(i, Mm1, 7)] = _fstar[LU3(i, Mm1, 5)] - 2.0 * w[5] * _rhobar * c[5][0] * Utop * 3.0;
}
break;
}
default: {
std::printf("Error: Invalid Boundary condition case number\n");
exit(1);
}
}
}
inline void swap(){
_f1.swap(_f2);
}
inline bool convergence(const unsigned int t){
if (t == 0)
_df0 = 1.0 / rmsError();
if (t % 1000 == 0) {
_df = rmsError() * _df0;
if (t / 1000 == _error.size())
_error.resize(2 * t / 1000);
_error[t / 1000] = _df;
}
if (t % prntInt == 0) {
cout << "\nIteration " << t << ":" << endl;
printf("df/df0:\t%.3e\n", _df);
stop = omp_get_wtime();
printf("Time:\t%.3e s\n", stop-start);
printf("rho:\t%.3e\n", _rhobar);
start = omp_get_wtime();
}
return (_df < THRESH);
}
inline void macroVars(){
double temp{},fTotalx{},fTotaly{};
int ind1{};
_rhobar = 0.0;
#pragma omp parallel for private(temp,ind1,fTotalx,fTotaly) collapse(2) reduction(+:_rhobar)
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
ind1 = LU2(i,j);
fTotalx = _forceX[ind1] + _fBodyX;
fTotaly = _forceY[ind1] + _fBodyY;
temp = _f2[LU3(i,j,0)] + _f2[LU3(i,j,1)] + _f2[LU3(i,j,2)] + _f2[LU3(i,j,3)] + _f2[LU3(i,j,4)] + _f2[LU3(i,j,5)] + _f2[LU3(i,j,6)] + _f2[LU3(i,j,7)] + _f2[LU3(i,j,8)];
_rho[ind1] = temp;
_rhobar += (temp / N2);
_u1[ind1] = ((_f2[LU3(i,j,1)] + _f2[LU3(i,j,5)] + _f2[LU3(i,j,8)]) - (_f2[LU3(i,j,3)] + _f2[LU3(i,j,6)] + _f2[LU3(i,j,7)]));
_u2[ind1] = ((_f2[LU3(i,j,2)] + _f2[LU3(i,j,5)] + _f2[LU3(i,j,6)]) - (_f2[LU3(i,j,4)] + _f2[LU3(i,j,7)] + _f2[LU3(i,j,8)]));
if (INCOMP != 1){
_u1[ind1] /= temp;
_u2[ind1] /= temp;
_p[ind1] = _rho[ind1] / 3.0;
}
else {
_p[ind1] = (1.0/(3.0*(1.0 - w[0]))) * (calcfeq(0,ind1)+calcfeq(1,ind1)+calcfeq(2,ind1)+calcfeq(3,ind1)+calcfeq(4,ind1)
+calcfeq(5,ind1)+calcfeq(6,ind1)+calcfeq(7,ind1)+calcfeq(8,ind1) - 1.5 * (P2(_u1[ind1]) + P2(_u2[ind1])));
}
// Forces
_u1[ind1] += 0.5 * fTotalx / temp;
_u2[ind1] += 0.5 * fTotaly / temp;
}
}
}
inline void output(){
calcvmag();
calcstress();
calcVort();
FILE *f = fopen(_filename1,"w");
int ind1;
if (f == nullptr) {
printf("Error opening file!\n");
exit(1);
}
fprintf(f, "TITLE=\"%s\" VARIABLES=\"x\", \"y\", \"u\", \"v\", \"vmag\", \"omegaxy\", \"vortz\" ZONE T=\"%s\" I=%d J=%d F=POINT\n", _filename1, _filename1,N,M);
for (int j = 0; j < M; j++) {
for (int i = 0; i < N; i++) {
ind1 = LU2(i,j);
fprintf(f, "%.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f\n", _x[i], _y[j], _u1[ind1] / _Umax,_u2[ind1] / _Umax, _vmag[ind1], _stress[ind1], _vort[ind1]);
}
}
fclose(f);
FILE *f2 = fopen(_filename2,"w");
if (f2 == nullptr) {
printf("Error opening file!\n");
exit(1);
}
for (unsigned int i = 0; i < _error.size(); i++) {
if (_error[i] == 0.0)
break;
else
fprintf(f2, "%d\t%.10e\n", 1000*i,_error[i]);
}
fclose(f2);
}
inline void immersedBoundary(){
// Calculate vector B
Eigen::VectorXd matrixBx = Eigen::VectorXd::Zero(IBN),matrixBy = Eigen::VectorXd::Zero(IBN);
double sumx{},sumy{},Dirac;
for (int i = 0; i < IBN; i++){
sumx = 0.0;
sumy = 0.0;
#pragma omp parallel for collapse(2) private(Dirac) reduction(+:sumx,sumy)
for (int k = (int)_IBrxmn; k <= (int)_IBrxmx; k++) {
for (int l =(int) _IBrymn; l <= (int)_IBrymx; l++) {
Dirac = diracdelta(_IBrx[i] - k) * diracdelta(_IBry[i] - l);
sumx += _u1[LU2(k,l)] * Dirac;
sumy += _u2[LU2(k,l)] * Dirac;
}
}
matrixBx(i) = _IBub[i] - sumx;
matrixBy(i) = _IBvb[i] - sumy;
}
// Solve for velocity correction
Eigen::VectorXd IBdu = Eigen::VectorXd::Zero(IBN),IBdv = Eigen::VectorXd::Zero(IBN);
IBdu = _IBmatrixAxInv * matrixBx;
IBdv = _IBmatrixAyInv * matrixBy;
// Spread du to LBM grid
double du,dv,ind1;
#pragma omp parallel for collapse(2) private(du,dv,ind1,Dirac)
for (int i = (int)_IBrxmn; i <= (int)_IBrxmx; i++){
for (int j = (int)_IBrymn; j <= (int)_IBrymx; j++){
du = 0.0; dv = 0.0; ind1 = LU2(i,j);_forceX[ind1] = 0.0;_forceY[ind1] = 0.0;
for (int k = 0; k < IBN; k++){
Dirac = diracdelta(_IBrx[k] - i) * diracdelta(_IBry[k] - j);
du += IBdu[k] * Dirac;
dv += IBdv[k] * Dirac;
}
_u1[ind1] += du;
_u2[ind1] += dv;
_forceX[ind1] += 2.0 * du * _rho[ind1];
_forceY[ind1] += 2.0 * dv * _rho[ind1];
}
}
}
private:
vector<double> _f1,_f2,_fstar,_u1,_u2,_rho,_p,_x,_y,_error,_vmag,_stress,_vort,_dudx,_dudy,_dvdx,_dvdy,_forceX,_forceY;
double _df, _df0, _MACHSTAR, _TAU_P, _OMEGA, _OMEGAm, _CS, _MACH, _rhobar;
char _filename1[80];
char _filename2[80];
double _omega_e,_omega_eps,_omega_q,_omega_nu, _GS[9];
double _Umax;
double _pi = 3.1415926535897;
vector<double> _IBrx, _IBry, _IBur, _IBvr, _IBFx, _IBFy, _IBub, _IBvb;
Eigen::MatrixXd _IBmatrixAx, _IBmatrixAy, _IBmatrixAxInv, _IBmatrixAyInv;
double _fBodyX,_fBodyY,_IBds,_IBrxmx,_IBrxmn,_IBrymx,_IBrymn;
// Left-right periodicity
inline void virtualnode(){
#pragma omp parallel for
for (int j = 1; j < Mm1; j++) {
_fstar[LU3(0, j, 1)] = _fstar[LU3(Nm2, j, 1)];
_fstar[LU3(0, j, 5)] = _fstar[LU3(Nm2, j, 5)];
_fstar[LU3(0, j, 8)] = _fstar[LU3(Nm2, j, 8)];
_fstar[LU3(Nm1, j, 3)] = _fstar[LU3(1, j, 3)];
_fstar[LU3(Nm1, j, 6)] = _fstar[LU3(1, j, 6)];
_fstar[LU3(Nm1, j, 7)] = _fstar[LU3(1, j, 7)];
}
// Top Left
_fstar[LU3(0, Mm1, 1)] = _fstar[LU3(Nm2, Mm1, 1)];
_fstar[LU3(0, Mm1, 4)] = _fstar[LU3(Nm2, Mm1, 4)];
_fstar[LU3(0, Mm1, 8)] = _fstar[LU3(Nm2, Mm1, 8)];
// Top Right
_fstar[LU3(Nm1, Mm1, 3)] = _fstar[LU3(1, Mm1, 3)];
_fstar[LU3(Nm1, Mm1, 7)] = _fstar[LU3(1, Mm1, 7)];
_fstar[LU3(Nm1, Mm1, 4)] = _fstar[LU3(1, Mm1, 4)];
// Bottom Left
_fstar[LU3(0, 0, 1)] = _fstar[LU3(Nm2, 0, 1)];
_fstar[LU3(0, 0, 2)] = _fstar[LU3(Nm2, 0, 2)];
_fstar[LU3(0, 0, 5)] = _fstar[LU3(Nm2, 0, 5)];
// Bottom Right
_fstar[LU3(Nm1, 0, 3)] = _fstar[LU3(1, 0, 3)];
_fstar[LU3(Nm1, 0, 2)] = _fstar[LU3(1, 0, 2)];
_fstar[LU3(Nm1, 0, 6)] = _fstar[LU3(1, 0, 6)];
}
// Intitializes x vector
inline void linspace(vector<double> &x, const double _start, const double _end, const int _num){
for (int i = 0; i < _num; i++)
x[i] = _start + i * (_end - _start) / (_num - 1.0);
}
inline double calcfeq(const int k, const int ind, const int check = 1){
const double u1ij=_u1[ind], u2ij = _u2[ind];
double cdotu{},feq{},u2{},rho0=_rho[ind];
if (INCOMP==1){
u2 = P2(u1ij) + P2(u2ij);
const double s0 = w[0] * (-1.5 * u2);
const double p = (1.0 / (3.0*(1.0 - w[0]))) * (_rho[ind] + s0);
cdotu = c[k][0] * u1ij + c[k][1] * u2ij;
const double s = w[k]*(3.0 * cdotu + 4.5 * P2(cdotu) - 1.5 * u2);
if (k == 0) {
feq = _rho[ind] - (1.0 - w[0]) * 3.0 * p + s0;
}
else {
feq = w[k] * 3.0 * p + s;
}
}
else{
u2 = P2(u1ij) + P2(u2ij);
cdotu = c[k][0] * u1ij + c[k][1] * u2ij;
feq = w[k] * (_rho[ind] + rho0 * (3.0 * cdotu + (4.5 * P2(cdotu) - 1.5 * u2) / GAMMA));
if (check == 1)
checkfeq(feq,ind);
}
return feq;
}
inline double calcfeq(const int k, const double u1ij, const double u2ij, const double rhoij, const int check = 1){
double cdotu{},feq{},u2{}, rho0=rhoij;
if (INCOMP==1){
u2 = P2(u1ij) + P2(u2ij);
const double s0 = w[0] * (-1.5 * u2);
const double p = (1.0 / (3.0*(1.0 - w[0]))) * (rhoij + s0);
cdotu = c[k][0] * u1ij + c[k][1] * u2ij;
const double s = w[k]*(3.0 * cdotu + 4.5 * P2(cdotu) - 1.5 * u2);
if (k == 0) {
feq = rhoij - (1.0 - w[0]) * 3.0 * p + s0;
}
else {
feq = w[k] * 3.0 * p + s;
}
}
else{
u2 = P2(u1ij) + P2(u2ij);
cdotu = c[k][0] * u1ij + c[k][1] * u2ij;
feq = w[k] * (rhoij + rho0 * (3.0 * cdotu + (4.5 * P2(cdotu) - 1.5 * u2) / GAMMA));
if (check == 1)
checkfeq(feq,1);
}
return feq;
}
// Checks for negative feq
inline void checkfeq(const double value, const int index){
if (value < 0) {
printf("Error: negative feq at index %d. Therefore, unstable.\n",index);
exit(1);
}
}
inline double rmsError(){
double difference{};
#pragma omp parallel for reduction(+:difference)
for (int i = 0; i < NQ; i++)
difference += P2(_f2[i] - _f1[i]);
return sqrt(difference / NQ);
}
inline void calcmeq(vector<double> &meq, const double u1, const double u2, const double rho, const double pres) {
const double u12 = P2(u1);
const double u22 = P2(u2);
if (INCOMP==1) {
const double alpha2 = 24.0, alpha3 = -36.0;
const double c1 = -2.0, c2 = -2.0;
const double gamma1 = 2.0/3.0,gamma2 = 18.0,gamma3=2.0/3.0,gamma4=-18.0;
meq[0] = rho; // rho
meq[1] = 0.25*alpha2*pres + (gamma2/6.0)*(u12+u22); // e
meq[2] = 0.25*alpha3*pres + (gamma4/6.0)*(u12+u22); // eps
meq[3] = u1; // jx
meq[4] = 0.5*c1*u1; // qx
meq[5] = u2; // jy
meq[6] = 0.5*c2*u2; // qy
meq[7] = 1.5*gamma1*(u12-u22); // pxx
meq[8] = 1.5*gamma3*u1*u2; // pxy
}
else {
meq[0] = rho; // rho
meq[1] = -2 * rho + 3 * rho * (u12 + u22) / GAMMA; // e
meq[2] = rho - 3 * rho * (u12 + u22) / GAMMA; // eps
meq[3] = rho * u1; // jx
meq[4] = -meq[3]; // qx
meq[5] = rho * u2; // jy
meq[6] = -meq[5]; // qy
meq[7] = rho * (u12 - u22) / GAMMA; // pxx
meq[8] = rho * u1 * u2 / GAMMA; // pxy
}
}
inline int LU2(const int i, const int j){
return N*j + i;
}
inline int LU3(const int i, const int j, const int k){
return N2*k + N*j + i;
}
inline double P2(const double value){
return (value * value);
}
inline void calcvmag(){
#pragma omp parallel for
for (int i = 0; i < N2; i++)
_vmag[i] = sqrt(P2(_u1[i]) + P2(_u2[i]));
}
inline void calcstress(){
#pragma omp parallel
{
int ind1;
#pragma omp for collapse(2)
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
ind1 = LU2(i,j);
for (int k = 0; k < Q; k++){
_stress[ind1] -= (1.0 - 0.5 * _OMEGA) * c[k][0] * c[k][1] * (_f2[LU3(i,j,k)] - calcfeq(k,ind1));
}
if (BC == 1)
_stress[ind1] -= 0.5 * (1.0 - 0.5 * _OMEGA) * (_forceX[ind1] * _u2[ind1] + _forceY[ind1] * _u1[ind1]);
}
}
}
}
inline void calcVort(){
calcDerivatives();
#pragma omp parallel for
for (int i = 0; i < N2; i++)
_vort[i] = _dvdx[i] - _dudy[i];
}
inline void calcDerivatives(){
// 2rd order Finite Difference
int indS{},indE{},ind{},indN{},indW{};
double hinv = 1.0 / ((_x[1] - _x[0]) * _Umax); // scales derivatives in space and velocity scale
// // d/dx central differences
for (int i = 1; i < Nm1; i++){
for (int j = 1; j < M; j++){
ind = LU2(i,j); // Current point
indE = LU2(i+1,j); // West
indW = LU2(i-1,j); // East
_dudx[ind] = 0.5 * (_u1[indE] - _u1[indW]) * hinv;
_dvdx[ind] = 0.5 * (_u2[indE] - _u2[indW]) * hinv;
}
}
// d/dy central differences
for (int i = 0; i < N; i++){
for (int j = 1; j < Mm1; j++){
ind = LU2(i,j); // Current point
indN = LU2(i,j+1); // North
indS = LU2(i,j-1); // South
_dudy[ind] = 0.5 * (_u1[indN] - _u1[indS]) * hinv;
_dvdy[ind] = 0.5 * (_u2[indN] - _u2[indS]) * hinv;
}
}
int indSS{},indNN{},indEE{},indWW{};
// d/dx forward (i = 0) & backward (i = Nm1) differences
for (int j = 0; j < M; j++){
// forward
ind = LU2(0,j);
indE = LU2(1,j);
indEE = LU2(2,j);
_dudx[ind] = (-1.5 * _u1[ind] + 2.0 * _u1[indE] - 0.5 * _u1[indEE]) * hinv;
_dvdx[ind] = (-1.5 * _u2[ind] + 2.0 * _u2[indE] - 0.5 * _u2[indEE]) * hinv;
// backward
ind = LU2(Nm1,j);
indW = LU2(Nm2,j);
indWW = LU2(N - 3,j);
_dudx[ind] = (1.5 * _u1[ind] - 2.0 * _u1[indW] + 0.5 * _u1[indWW]) * hinv;
_dvdx[ind] = (1.5 * _u2[ind] - 2.0 * _u2[indW] + 0.5 * _u2[indWW]) * hinv;
}
// d/dy forward (j = 0) & backward (j = Mm1) differences
for (int i = 0; i < N; i++){
// forward
ind = LU2(i,0);
indN = LU2(i,1);
indNN = LU2(i,2);
_dudy[ind] = (-1.5 * _u1[ind] + 2.0 * _u1[indN] - 0.5 * _u1[indNN]) * hinv;
_dvdy[ind] = (-1.5 * _u2[ind] + 2.0 * _u2[indN] - 0.5 * _u2[indNN]) * hinv;
// backward
ind = LU2(i,Mm1);
indS = LU2(i,Mm2);
indSS = LU2(i,M - 3);
_dudy[ind] = (1.5 * _u1[ind] - 2.0 * _u1[indS] + 0.5 * _u1[indSS]) * hinv;
_dvdy[ind] = (1.5 * _u2[ind] - 2.0 * _u2[indS] + 0.5 * _u2[indSS]) * hinv;
}
}
inline double diracdelta(const double x, const int order = 4){
const double absx = abs(x);
double phi{};
const double dx = 1.0;
switch (order){
case 2 : {
if (absx < dx)
phi = 1.0 - absx;
else
phi = 0.0;
break;
}
case 3 : {
if (absx <= 0.5 * dx)
phi = (1.0/3.0) * (1.0 + sqrt(1.0 - 3.0 * P2(absx)));
else if (absx <= 1.5 * dx)
phi = (1.0/6.0) * (5.0 - 3.0 * absx - sqrt(-2.0 + 6.0 * absx - 3.0 * P2(absx)));
else
phi = 0.0;
break;
}
case 4 : {
if (absx <= dx)
phi = (1.0/8.0) * (3.0 - 2.0 * absx + sqrt(1.0 + 4.0 * absx - 4.0 * P2(absx)));
else if (absx <= (2.0 * dx))
phi = (1.0/8.0) * (5.0 - 2.0 * absx - sqrt(-7.0 + 12.0 * absx - 4.0 * P2(absx)));
else
phi = 0.0;
break;
}
default : {
cout << "Invalid order for delta function. Must be 2,3, or 4" << endl;
exit(1);
}
}
return phi;
}
bool diagdominant(const vector<vector<double>> &matrix, const int size){
double diag{},sum{};
bool dd = true;
for (int i = 0; i < size; i++){
diag = matrix[i][i];
sum = 0.0;
for (int j = 0; j < size; j++){
if (j != i)
sum += matrix[i][j];
}
if (sum > diag){
dd = false;
break;
}
}
return dd;
}
};
#endif //LIDDRIVENCAVITYLBM_LBMCLASS_H
|
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;
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> CilkHintHandler;
std::unique_ptr<PragmaHandler> OptimizeHandler;
std::unique_ptr<PragmaHandler> LoopHintHandler;
std::unique_ptr<PragmaHandler> UnrollHintHandler;
std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
std::unique_ptr<PragmaHandler> FPHandler;
std::unique_ptr<PragmaHandler> STDCFenvAccessHandler;
std::unique_ptr<PragmaHandler> STDCFenvRoundHandler;
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();
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 STDC FENV_ROUND...
void HandlePragmaFEnvRound();
/// 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);
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 ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
bool &isCastExpr,
ParsedType &CastTy,
SourceRange &CastRange);
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 ParseCilkSpawnStatement();
StmtResult ParseCilkSyncStatement();
StmtResult ParseCilkForStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseCilkScopeStatement();
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::TypeName,
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 ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc,
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,
OMPTraitInfo *ParentTI);
/// Parse clauses for '#pragma omp declare variant'.
void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
SourceLocation Loc);
/// Parse 'omp [begin] assume[s]' directive.
void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
SourceLocation Loc);
/// Parse 'omp end assumes' directive.
void ParseOpenMPEndAssumesDirective(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();
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
|
GB_AxB_rowscale_template.c | //------------------------------------------------------------------------------
// GB_AxB_rowscale_template: C=D*B where D is a square diagonal matrix
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// This template is not used If C is iso, since all that is needed is to create
// C as a shallow-copy of the pattern of A.
// B and C can be jumbled. D cannot, but it is a diagonal matrix so it is
// never jumbled.
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
// Bx is unused if the operator is FIRST or PAIR
#include "GB_unused.h"
ASSERT (GB_JUMBLED_OK (C)) ;
ASSERT (!GB_JUMBLED (D)) ;
ASSERT (GB_JUMBLED_OK (B)) ;
ASSERT (!C->iso) ;
//--------------------------------------------------------------------------
// get D and B
//--------------------------------------------------------------------------
const GB_ATYPE *restrict Dx = (GB_ATYPE *) (D_is_pattern ? NULL : D->x) ;
const bool D_iso = D->iso ;
const GB_BTYPE *restrict Bx = (GB_BTYPE *) (B_is_pattern ? NULL : B->x) ;
const bool B_iso = B->iso ;
const int64_t *restrict Bi = B->i ;
const int64_t bnz = GB_nnz (B) ;
const int64_t bvlen = B->vlen ;
//--------------------------------------------------------------------------
// C=D*B
//--------------------------------------------------------------------------
int ntasks = nthreads ;
ntasks = GB_IMIN (bnz, ntasks) ;
int tid ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (tid = 0 ; tid < ntasks ; tid++)
{
int64_t pstart, pend ;
GB_PARTITION (pstart, pend, bnz, tid, ntasks) ;
GB_PRAGMA_SIMD_VECTORIZE
for (int64_t p = pstart ; p < pend ; p++)
{
int64_t i = GBI (Bi, p, bvlen) ; // get row index of B(i,j)
GB_GETA (dii, Dx, i, D_iso) ; // dii = D(i,i)
GB_GETB (bij, Bx, p, B_iso) ; // bij = B(i,j)
GB_BINOP (GB_CX (p), dii, bij, 0, 0) ; // C(i,j) = dii*bij
}
}
}
|
packed_sgemm_a35.h | // Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <arm_neon.h>
#include <cmath>
#include "lite/backends/arm/math/packed_sgemm.h"
#include "lite/core/context.h"
namespace paddle {
namespace lite {
namespace arm {
namespace math {
#ifdef __aarch64__
// loadb: 6x8 b=6
void loadb_6x8(
float *out, const float *in, int ldin, int k0, int kmax, int n0, int nmax) {
auto outptr = reinterpret_cast<uint32_t *>(out);
auto inptr = reinterpret_cast<const uint32_t *>(in) + k0 * ldin + n0;
uint32_t mask_buffer[8] = {0, 1, 2, 3, 4, 5, 6, 7};
int x_len = nmax - n0;
int y_len = kmax - k0;
int right_remain = x_len - 6 * (x_len / 6);
int right_pad = 6 - right_remain;
uint32_t *outptr_row = outptr;
int stride_out = 6 * y_len;
int cnt_y = 4 * (y_len / 4);
uint32x4_t vzero = vdupq_n_u32(0);
uint32x4_t vmask1 =
vcltq_u32(vld1q_u32(mask_buffer), vdupq_n_u32(right_remain));
uint32x4_t vmask2 =
vcltq_u32(vld1q_u32(mask_buffer + 4), vdupq_n_u32(right_remain));
#pragma omp parallel for
for (int y = 0; y < y_len - 3; y += 4) {
const uint32_t *ptr0 = inptr + y * ldin;
const uint32_t *ptr1 = ptr0 + ldin;
const uint32_t *ptr2 = ptr1 + ldin;
const uint32_t *ptr3 = ptr2 + ldin;
uint32_t *outptr_row_col = outptr_row + y * 6;
asm volatile(
"prfm pldl1keep, [%[ptr0]] \n"
"prfm pldl1keep, [%[ptr0], #64] \n"
"prfm pldl1keep, [%[ptr1]] \n"
"prfm pldl1keep, [%[ptr1], #64] \n"
"prfm pldl1keep, [%[ptr2]] \n"
"prfm pldl1keep, [%[ptr2], #64] \n"
"prfm pldl1keep, [%[ptr3]] \n"
"prfm pldl1keep, [%[ptr3], #64] \n"
:
: [ptr0] "r"(ptr0), [ptr1] "r"(ptr1), [ptr2] "r"(ptr2), [ptr3] "r"(ptr3)
: "memory");
int i = 0;
for (; i < x_len - 5; i += 6) {
uint32_t *ptr_out = outptr_row_col;
asm volatile(
"ldr q0, [%[ptr0]], #16\n"
"ld1 {v1.2s}, [%[ptr0]], #8\n"
"ldr q2, [%[ptr1]], #16\n"
"ld1 {v3.2s}, [%[ptr1]], #8\n"
"ldr q4, [%[ptr2]], #16\n"
"str q0, [%[outptr]], #16\n"
"ld1 {v5.2s}, [%[ptr2]], #8\n"
"st1 {v1.2s}, [%[outptr]], #8\n"
"ldr q6, [%[ptr3]], #16\n"
"str q2, [%[outptr]], #16\n"
"ld1 {v7.2s}, [%[ptr3]], #8\n"
"st1 {v3.2s}, [%[outptr]], #8\n"
"str q4, [%[outptr]], #16\n"
"st1 {v5.2s}, [%[outptr]], #8\n"
"str q6, [%[outptr]], #16\n"
"st1 {v7.2s}, [%[outptr]], #8\n"
: [outptr] "+r"(ptr_out),
[ptr0] "+r"(ptr0),
[ptr1] "+r"(ptr1),
[ptr2] "+r"(ptr2),
[ptr3] "+r"(ptr3)
:
: "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "cc", "memory");
outptr_row_col += stride_out;
}
if (right_remain > 0) {
uint32_t *ptr_out = outptr_row_col;
asm volatile(
"ldp q0, q1, [%[ptr0]], #32\n"
"ldp q2, q3, [%[ptr1]], #32\n"
"bif v0.16b, %[vzero].16b, %[vmask1].16b\n"
"bif v1.16b, %[vzero].16b, %[vmask2].16b\n"
"bif v2.16b, %[vzero].16b, %[vmask1].16b\n"
"bif v3.16b, %[vzero].16b, %[vmask2].16b\n"
"str q0, [%[outptr]], #16\n"
"ldp q4, q5, [%[ptr2]], #32\n"
"st1 {v1.2s}, [%[outptr]], #8\n"
"ldp q6, q7, [%[ptr3]], #32\n"
"str q2, [%[outptr]], #16\n"
"bif v4.16b, %[vzero].16b, %[vmask1].16b\n"
"bif v5.16b, %[vzero].16b, %[vmask2].16b\n"
"st1 {v3.2s}, [%[outptr]], #8\n"
"bif v6.16b, %[vzero].16b, %[vmask1].16b\n"
"bif v7.16b, %[vzero].16b, %[vmask2].16b\n"
"str q4, [%[outptr]], #16\n"
"st1 {v5.2s}, [%[outptr]], #8\n"
"str q6, [%[outptr]], #16\n"
"st1 {v7.2s}, [%[outptr]], #8\n"
: [outptr] "+r"(ptr_out),
[ptr0] "+r"(ptr0),
[ptr1] "+r"(ptr1),
[ptr2] "+r"(ptr2),
[ptr3] "+r"(ptr3)
: [vmask1] "w"(vmask1), [vmask2] "w"(vmask2), [vzero] "w"(vzero)
: "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "cc", "memory");
}
}
#pragma omp parallel for
for (int y = cnt_y; y < y_len; ++y) {
const uint32_t *ptr0 = inptr + y * ldin;
uint32_t *outptr_row_col = outptr_row + y * 6;
int i = 0;
for (; i < x_len - 5; i += 6) {
uint32_t *ptr_out = outptr_row_col;
asm volatile(
"ldr q0, [%[ptr0]], #16\n"
"ld1 {v1.2s}, [%[ptr0]], #8\n"
"str q0, [%[outptr]], #16\n"
"st1 {v1.2s}, [%[outptr]], #8\n"
: [ptr0] "+r"(ptr0), [outptr] "+r"(ptr_out)
:
: "v0", "v1", "cc", "memory");
outptr_row_col += stride_out;
}
if (right_remain > 0) {
uint32_t *ptr_out = outptr_row_col;
asm volatile(
"ldp q0, q1, [%[ptr0]], #32\n"
"bif v0.16b, %[vzero].16b, %[vmask1].16b\n"
"bif v1.16b, %[vzero].16b, %[vmask2].16b\n"
"str q0, [%[outptr]], #16\n"
"st1 {v1.2s}, [%[outptr]], #8\n"
: [ptr0] "+r"(ptr0), [outptr] "+r"(ptr_out)
: [vmask1] "w"(vmask1), [vmask2] "w"(vmask2), [vzero] "w"(vzero)
: "v0", "v1", "cc", "memory");
}
}
}
// loadb_trans: 8x6 b=6
void loadb_trans_6x8(
float *out, const float *in, int ldin, int k0, int kmax, int n0, int nmax) {
int x_len = kmax - k0;
uint32_t zerobuff[x_len]; // NOLINT
memset(zerobuff, 0, sizeof(uint32_t) * x_len);
auto outptr = reinterpret_cast<uint32_t *>(out);
auto inptr = reinterpret_cast<const uint32_t *>(in);
//! data B is not transposed, transpose B to k * 6
for (int y = n0; y < nmax; y += 6) {
const uint32_t *inptr0 = inptr + y * ldin + k0;
const uint32_t *inptr1 = inptr0 + ldin;
const uint32_t *inptr2 = inptr1 + ldin;
const uint32_t *inptr3 = inptr2 + ldin;
const uint32_t *inptr4 = inptr3 + ldin;
const uint32_t *inptr5 = inptr4 + ldin;
int x = x_len;
asm volatile(
"prfm pldl1keep, [%[ptr0]] \n"
"prfm pldl1keep, [%[ptr0], #64] \n"
"prfm pldl1keep, [%[ptr1]] \n"
"prfm pldl1keep, [%[ptr1], #64] \n"
"prfm pldl1keep, [%[ptr2]] \n"
"prfm pldl1keep, [%[ptr2], #64] \n"
"prfm pldl1keep, [%[ptr3]] \n"
"prfm pldl1keep, [%[ptr3], #64] \n"
"prfm pldl1keep, [%[ptr4]] \n"
"prfm pldl1keep, [%[ptr4], #64] \n"
"prfm pldl1keep, [%[ptr5]] \n"
"prfm pldl1keep, [%[ptr5], #64] \n"
:
: [ptr0] "r"(inptr0),
[ptr1] "r"(inptr1),
[ptr2] "r"(inptr2),
[ptr3] "r"(inptr3),
[ptr4] "r"(inptr4),
[ptr5] "r"(inptr5)
: "memory");
//! cope with row index exceed real size, set to zero buffer
if ((y + 5) >= nmax) {
switch ((y + 5) - nmax) {
case 4:
inptr1 = zerobuff;
case 3:
inptr2 = zerobuff;
case 2:
inptr3 = zerobuff;
case 1:
inptr4 = zerobuff;
case 0:
inptr5 = zerobuff;
default:
break;
}
}
for (; x > 3; x -= 4) {
// clang-format off
//! zip load 8 elements (2 neon Q registers) from each of 8 rows
asm volatile(
"ldr q0, [%[inptr0]], #16\n"
"ldr q1, [%[inptr1]], #16\n"
"ldr q2, [%[inptr2]], #16\n"
"ldr q3, [%[inptr3]], #16\n"
"ldr q4, [%[inptr4]], #16\n" // e0e1e2e3
"ldr q5, [%[inptr5]], #16\n" // f0f1f2f3
"trn1 v8.4s, v0.4s, v1.4s\n" // a0b0a2b2
"trn2 v9.4s, v0.4s, v1.4s\n" // a1b1a3b3
"trn1 v10.4s, v2.4s, v3.4s\n"// c0d0c2d2
"trn2 v11.4s, v2.4s, v3.4s\n"// c1d1c3d3
"trn1 v6.4s, v4.4s, v5.4s\n" // e0f0e2f2
"trn2 v7.4s, v4.4s, v5.4s\n" // e1f1e3f3
"trn1 v0.2d, v8.2d, v10.2d\n" // a0b0c0d0
"trn1 v1.2d, v9.2d, v11.2d\n" // a1b1c1d1
"trn2 v2.2d, v8.2d, v10.2d\n" // a2b2c2d2
"trn2 v3.2d, v9.2d, v11.2d\n" // a3b3c3d3
"trn1 v4.2d, v6.2d, v7.2d\n" // e0f0e1f1
"trn2 v5.2d, v6.2d, v7.2d\n" // e2f2e3f3
"str q0, [%[outptr]], #16\n" // save q0, a0~d0
"trn1 v6.2d, v4.2d, v1.2d\n" // e0f0a1b1
"st1 {v4.2s}, [%[outptr]], #8\n"
"trn2 v7.2d, v4.2d, v1.2d\n" // e1f1c1d1
"str q1, [%[outptr]], #16\n" // save q0, a1~d1
"trn1 v8.2d, v5.2d, v3.2d\n" // e2f2a3b3
"trn2 v9.2d, v5.2d, v3.2d\n" // e3f3c3d3
"st1 {v7.2s}, [%[outptr]], #8\n"
"str q2, [%[outptr]], #16\n" // save q0, a2~d2
"st1 {v5.2s}, [%[outptr]], #8\n"
"str q3, [%[outptr]], #16\n" // save q0, a3~d3
"st1 {v9.2s}, [%[outptr]], #8\n"
: [inptr0] "+r"(inptr0),
[inptr1] "+r"(inptr1),
[inptr2] "+r"(inptr2),
[inptr3] "+r"(inptr3),
[inptr4] "+r"(inptr4),
[inptr5] "+r"(inptr5),
[outptr] "+r"(outptr)
:
: "v0","v1","v2","v3","v4","v5",
"v6","v7","v8","v9","v10","v11","cc","memory");
// clang-format on
}
for (; x > 0; x--) {
*outptr++ = *inptr0++;
*outptr++ = *inptr1++;
*outptr++ = *inptr2++;
*outptr++ = *inptr3++;
*outptr++ = *inptr4++;
*outptr++ = *inptr5++;
}
}
}
#define FMLA_N8X6 \
"fmla v12.2s, v5.2s, v1.2s\n" \
"fmla v14.2s, v4.2s, v2.2s\n" \
"fmla v15.2s, v5.2s, v2.2s\n" \
"ld1r {v3.2s}, [%[a_ptr]], #4\n" \
"fmla v10.2s, v6.2s, v0.2s\n" \
"fmla v13.2s, v6.2s, v1.2s\n" \
"fmla v16.2s, v6.2s, v2.2s\n" \
"ld1r {v0.2s}, [%[a_ptr]], #4\n" \
"fmla v17.2s, v4.2s, v3.2s\n" \
"fmla v18.2s, v5.2s, v3.2s\n" \
"fmla v19.2s, v6.2s, v3.2s\n" \
"ld1r {v1.2s}, [%[a_ptr]], #4\n" \
"fmla v20.2s, v4.2s, v0.2s\n" \
"fmla v21.2s, v5.2s, v0.2s\n" \
"fmla v22.2s, v6.2s, v0.2s\n" \
"ld1r {v2.2s}, [%[a_ptr]], #4\n" \
"fmla v23.2s, v4.2s, v1.2s\n" \
"fmla v24.2s, v5.2s, v1.2s\n" \
"fmla v25.2s, v6.2s, v1.2s\n" \
"ld1r {v3.2s}, [%[a_ptr]], #4\n" \
"fmla v26.2s, v4.2s, v2.2s\n" \
"fmla v27.2s, v5.2s, v2.2s\n" \
"fmla v28.2s, v6.2s, v2.2s\n" \
"ld1r {v0.2s}, [%[a_ptr]], #4\n" \
"fmla v29.2s, v4.2s, v3.2s\n" \
"fmla v30.2s, v5.2s, v3.2s\n" \
"fmla v31.2s, v6.2s, v3.2s\n"
void sgemm_prepacked_8x6_a35(bool is_transB,
int M,
int N,
int K,
const float *A_packed,
const float *B,
int ldb,
float beta,
float *C,
int ldc,
const float *bias,
bool has_bias,
const operators::ActivationParam act_param,
ARMContext *ctx) {
size_t l2_cache = ctx->llc_size() > 0 ? ctx->llc_size() : 512 * 1024;
auto workspace = ctx->workspace_data<float>();
int threads = ctx->threads();
auto act_type = act_param.active_type;
float alpha[4] = {0.f, 0.f, 0.f, 0.f};
float local_alpha = 0.f;
int flag_act = 0x00; // relu: 1, relu6: 2, leakey: 3
if (act_param.has_active) {
if (act_type == lite_api::ActivationType::kRelu) {
flag_act = 0x01;
} else if (act_type == lite_api::ActivationType::kRelu6) {
flag_act = 0x02;
local_alpha = act_param.Relu_clipped_coef;
} else if (act_type == lite_api::ActivationType::kLeakyRelu) {
flag_act = 0x03;
local_alpha = act_param.Leaky_relu_alpha;
}
}
alpha[0] = local_alpha;
alpha[1] = local_alpha;
alpha[2] = local_alpha;
alpha[3] = local_alpha;
// NBLOCK = 6
int n_block = 6;
int k_block = 2;
X_BLOCK_COMPUTE(l2_cache, MBLOCK, n_block, M, N, K)
// unroll 2 loop
int tail_pre = (K & (k_block - 1));
int k_pre = ((K + k_block - 1) / k_block) - 1;
bool flag_p_remain = false;
int remain = 0;
if (tail_pre == 0) {
tail_pre = k_block;
}
int has_beta = fabsf(beta) > 1e-8f ? 1 : 0;
//! apanel is pre_compute outside gemm
for (unsigned int x0 = 0; x0 < N; x0 += x_block) {
unsigned int xmax = x0 + x_block;
if (xmax > N) {
xmax = N;
}
int bblocks = (xmax - x0 + n_block - 1) / n_block;
remain = xmax - x0 - (bblocks - 1) * n_block;
if (remain > 0) {
flag_p_remain = true;
}
//! load bpanel
float *b_pannel = workspace;
if (is_transB) {
loadb_trans_6x8(b_pannel, B, ldb, 0, K, x0, xmax);
} else {
loadb_6x8(b_pannel, B, ldb, 0, K, x0, xmax);
}
#pragma omp parallel for num_threads(threads)
for (unsigned int y = 0; y < M; y += MBLOCK) {
unsigned int ymax = y + MBLOCK;
if (ymax > M) {
ymax = M;
}
float bias_local[8] = {0};
if (has_bias) {
bias_local[0] = bias[y];
bias_local[1] = bias[y + 1];
bias_local[2] = bias[y + 2];
bias_local[3] = bias[y + 3];
bias_local[4] = bias[y + 4];
bias_local[5] = bias[y + 5];
bias_local[6] = bias[y + 6];
bias_local[7] = bias[y + 7];
}
float cout0[n_block]; // NOLINT
float cout1[n_block]; // NOLINT
float cout2[n_block]; // NOLINT
float cout3[n_block]; // NOLINT
float cout4[n_block]; // NOLINT
float cout5[n_block]; // NOLINT
float cout6[n_block]; // NOLINT
float cout7[n_block]; // NOLINT
float *c_ptr0 = C + y * ldc + x0;
float *c_ptr1 = c_ptr0 + ldc;
float *c_ptr2 = c_ptr1 + ldc;
float *c_ptr3 = c_ptr2 + ldc;
float *c_ptr4 = c_ptr3 + ldc;
float *c_ptr5 = c_ptr4 + ldc;
float *c_ptr6 = c_ptr5 + ldc;
float *c_ptr7 = c_ptr6 + ldc;
float *pout0 = c_ptr0;
float *pout1 = c_ptr1;
float *pout2 = c_ptr2;
float *pout3 = c_ptr3;
float *pout4 = c_ptr4;
float *pout5 = c_ptr5;
float *pout6 = c_ptr6;
float *pout7 = c_ptr7;
const float *a_ptr_l = A_packed + y * K;
const float *b_ptr = b_pannel;
for (int xb = 0; xb < bblocks; xb++) {
if ((y + 7) >= ymax) {
switch ((y + 7) - ymax) {
case 6:
c_ptr1 = cout1;
case 5:
c_ptr2 = cout2;
case 4:
c_ptr3 = cout3;
case 3:
c_ptr4 = cout4;
case 2:
c_ptr5 = cout5;
case 1:
c_ptr6 = cout6;
case 0:
c_ptr7 = cout7;
default:
break;
}
}
if (flag_p_remain && (xb == bblocks - 1)) {
pout0 = c_ptr0;
pout1 = c_ptr1;
pout2 = c_ptr2;
pout3 = c_ptr3;
pout4 = c_ptr4;
pout5 = c_ptr5;
pout6 = c_ptr6;
pout7 = c_ptr7;
c_ptr0 = cout0;
c_ptr1 = cout1;
c_ptr2 = cout2;
c_ptr3 = cout3;
c_ptr4 = cout4;
c_ptr5 = cout5;
c_ptr6 = cout6;
c_ptr7 = cout7;
}
const float *a_ptr = a_ptr_l;
int tail = tail_pre;
int k = k_pre;
// clang-format off
asm volatile(
"prfum pldl1keep, [%[b_ptr]]\n"
"ldp q2, q3, [%[bias_ptr]]\n"
"prfm pldl1keep, [%[a_ptr]]\n"
"dup v8.2s, v2.s[0]\n"
"dup v9.2s, v2.s[0]\n"
"dup v10.2s, v2.s[0]\n"
"prfm pldl1keep, [%[b_ptr], #64]\n"
"dup v11.2s, v2.s[1]\n"
"dup v12.2s, v2.s[1]\n"
"dup v13.2s, v2.s[1]\n"
"prfum pldl1keep, [%[a_ptr], #52]\n"
"dup v14.2s, v2.s[2]\n"
"dup v15.2s, v2.s[2]\n"
"dup v16.2s, v2.s[2]\n"
"prfum pldl1keep, [%[a_ptr], #116]\n"
"dup v17.2s, v2.s[3]\n"
"dup v18.2s, v2.s[3]\n"
"dup v19.2s, v2.s[3]\n"
"prfm pldl1keep, [%[b_ptr], #128]\n"
"dup v20.2s, v3.s[0]\n"
"dup v21.2s, v3.s[0]\n"
"dup v22.2s, v3.s[0]\n"
"dup v23.2s, v3.s[1]\n"
"dup v24.2s, v3.s[1]\n"
"dup v25.2s, v3.s[1]\n"
"cmp %w[has_beta], #1\n"
"dup v26.2s, v3.s[2]\n"
"dup v27.2s, v3.s[2]\n"
"dup v28.2s, v3.s[2]\n"
"dup v29.2s, v3.s[3]\n"
"dup v30.2s, v3.s[3]\n"
"dup v31.2s, v3.s[3]\n"
"blt 0f\n" /* check beta == 0? */
/* process beta */
"dup v7.4s, %w[beta]\n"
"ld1 {v0.2s, v1.2s, v2.2s}, [%[c_ptr0]]\n"
"ld1 {v3.2s, v4.2s, v5.2s}, [%[c_ptr1]]\n"
"fmla v8.2s, v0.2s, v7.2s\n"
"fmla v9.2s, v1.2s, v7.2s\n"
"fmla v10.2s, v2.2s, v7.2s\n"
"ld1 {v0.2s, v1.2s, v2.2s}, [%[c_ptr2]]\n"
"fmla v11.2s, v3.2s, v7.2s\n"
"fmla v12.2s, v4.2s, v7.2s\n"
"fmla v13.2s, v5.2s, v7.2s\n"
"ld1 {v3.2s, v4.2s, v5.2s}, [%[c_ptr3]]\n"
"fmla v14.2s, v0.2s, v7.2s\n"
"fmla v15.2s, v1.2s, v7.2s\n"
"fmla v16.2s, v2.2s, v7.2s\n"
"ld1 {v0.2s, v1.2s, v2.2s}, [%[c_ptr4]]\n"
"fmla v17.2s, v3.2s, v7.2s\n"
"fmla v18.2s, v4.2s, v7.2s\n"
"fmla v19.2s, v5.2s, v7.2s\n"
"ld1 {v3.2s, v4.2s, v5.2s}, [%[c_ptr5]]\n"
"fmla v20.2s, v0.2s, v7.2s\n"
"fmla v21.2s, v1.2s, v7.2s\n"
"fmla v22.2s, v2.2s, v7.2s\n"
"ld1 {v0.2s, v1.2s, v2.2s}, [%[c_ptr6]]\n"
"fmla v23.2s, v3.2s, v7.2s\n"
"fmla v24.2s, v4.2s, v7.2s\n"
"fmla v25.2s, v5.2s, v7.2s\n"
"ld1 {v3.2s, v4.2s, v5.2s}, [%[c_ptr7]]\n"
"fmla v26.2s, v0.2s, v7.2s\n"
"fmla v27.2s, v1.2s, v7.2s\n"
"fmla v28.2s, v2.2s, v7.2s\n"
"fmla v29.2s, v3.2s, v7.2s\n"
"fmla v30.2s, v4.2s, v7.2s\n"
"fmla v31.2s, v5.2s, v7.2s\n"
"0: \n"
"cmp %w[k], #1\n"
"ld1r {v0.2s}, [%[a_ptr]], #4\n"
"ldr d4, [%[b_ptr], #0]\n"
"ld1r {v1.2s}, [%[a_ptr]], #4\n"
"blt 2f\n"
/* main loop */
"1: \n"
/* unrool 0*/
"ldr d5, [%[b_ptr], #8]\n"
"ld1r {v2.2s}, [%[a_ptr]], #4\n"
"fmla v8.2s, v4.2s, v0.2s\n"
"fmla v11.2s, v4.2s, v1.2s\n"
"fmla v9.2s, v5.2s, v0.2s\n"
"ldr d6, [%[b_ptr], #16]\n"
FMLA_N8X6
/* unrool 1*/
"ldr d4, [%[b_ptr], #24]\n"
"prfm pldl1keep, [%[b_ptr], #128]\n"
"ld1r {v1.2s}, [%[a_ptr]], #4\n"
"subs %w[k], %w[k], #1\n"
"prfum pldl1keep, [%[a_ptr], #156]\n"
"ldr d5, [%[b_ptr], #32]\n"
"ld1r {v2.2s}, [%[a_ptr]], #4\n"
"fmla v8.2s, v4.2s, v0.2s\n"
"fmla v11.2s, v4.2s, v1.2s\n"
"fmla v9.2s, v5.2s, v0.2s\n"
"ldr d6, [%[b_ptr], #40]\n"
FMLA_N8X6
"ld1r {v1.2s}, [%[a_ptr]], #4\n"
"add %[b_ptr], %[b_ptr], #48\n"
"prfum pldl1keep, [%[a_ptr], #188]\n"
"ldr d4, [%[b_ptr], #0]\n"
"bne 1b\n"
// tail
"2: \n"
"cmp %w[tail], #1\n"
"ld1r {v2.2s}, [%[a_ptr]], #4\n"
"ldr d5, [%[b_ptr], #8]\n"
"beq 3f \n"
// tail=2
"fmla v8.2s, v4.2s, v0.2s\n"
"fmla v11.2s, v4.2s, v1.2s\n"
"fmla v9.2s, v5.2s, v0.2s\n"
"ldr d6, [%[b_ptr], #16]\n"
FMLA_N8X6
/* unrool 1*/
"ldr d4, [%[b_ptr], #24]\n"
"prfm pldl1keep, [%[b_ptr], #128]\n"
"ld1r {v1.2s}, [%[a_ptr]], #4\n"
"ldr d5, [%[b_ptr], #32]\n"
"ld1r {v2.2s}, [%[a_ptr]], #4\n"
"fmla v8.2s, v4.2s, v0.2s\n"
"fmla v11.2s, v4.2s, v1.2s\n"
"fmla v9.2s, v5.2s, v0.2s\n"
"ldr d6, [%[b_ptr], #40]\n"
FMLA_N8X6
"add %[b_ptr], %[b_ptr], #48\n"
"b 4f\n"
"3: \n"
// tail=1
"fmla v8.2s, v4.2s, v0.2s\n"
"fmla v11.2s, v4.2s, v1.2s\n"
"fmla v9.2s, v5.2s, v0.2s\n"
"ldr d6, [%[b_ptr], #16]\n"
FMLA_N8X6
"add %[b_ptr], %[b_ptr], #24\n"
"4: \n"
"cmp %w[flag_act], #0\n" // no act
"beq 5f\n"
"cmp %w[flag_act], #1\n" // relu
"movi v0.2s, #0\n"
"beq 6f\n"
"cmp %w[flag_act], #2\n" // relu6
"ld1 {v1.2s}, [%[alpha]]\n"
"beq 7f\n"
// leakyrelu
"fcmge v2.2s, v8.2s, v0.2s\n"
"fmul v3.2s, v8.2s, v1.2s\n"
"fcmge v4.2s, v9.2s, v0.2s\n"
"fmul v5.2s, v9.2s, v1.2s\n"
"fcmge v6.2s, v10.2s, v0.2s\n"
"fmul v7.2s, v10.2s, v1.2s\n"
"bif v8.16b, v3.16b, v2.16b\n"
"fcmge v2.2s, v11.2s, v0.2s\n"
"fmul v3.2s, v11.2s, v1.2s\n"
"bif v9.16b, v5.16b, v4.16b\n"
"fcmge v4.2s, v12.2s, v0.2s\n"
"fmul v5.2s, v12.2s, v1.2s\n"
"bif v10.16b, v6.16b, v7.16b\n"
"fcmge v6.2s, v13.2s, v0.2s\n"
"fmul v7.2s, v13.2s, v1.2s\n"
"bif v11.16b, v3.16b, v2.16b\n"
"fcmge v2.2s, v14.2s, v0.2s\n"
"fmul v3.2s, v14.2s, v1.2s\n"
"bif v12.16b, v5.16b, v4.16b\n"
"fcmge v4.2s, v15.2s, v0.2s\n"
"fmul v5.2s, v15.2s, v1.2s\n"
"bif v13.16b, v6.16b, v7.16b\n"
"fcmge v6.2s, v16.2s, v0.2s\n"
"fmul v7.2s, v16.2s, v1.2s\n"
"bif v14.16b, v3.16b, v2.16b\n"
"fcmge v2.2s, v17.2s, v0.2s\n"
"fmul v3.2s, v17.2s, v1.2s\n"
"bif v15.16b, v5.16b, v4.16b\n"
"fcmge v4.2s, v18.2s, v0.2s\n"
"fmul v5.2s, v18.2s, v1.2s\n"
"bif v16.16b, v6.16b, v7.16b\n"
"fcmge v6.2s, v19.2s, v0.2s\n"
"fmul v7.2s, v19.2s, v1.2s\n"
"bif v17.16b, v3.16b, v2.16b\n"
"fcmge v2.2s, v20.2s, v0.2s\n"
"fmul v3.2s, v20.2s, v1.2s\n"
"bif v18.16b, v5.16b, v4.16b\n"
"fcmge v4.2s, v21.2s, v0.2s\n"
"fmul v5.2s, v21.2s, v1.2s\n"
"bif v19.16b, v6.16b, v7.16b\n"
"fcmge v6.2s, v22.2s, v0.2s\n"
"fmul v7.2s, v22.2s, v1.2s\n"
"bif v20.16b, v3.16b, v2.16b\n"
"fcmge v2.2s, v23.2s, v0.2s\n"
"fmul v3.2s, v23.2s, v1.2s\n"
"bif v21.16b, v5.16b, v4.16b\n"
"fcmge v4.2s, v24.2s, v0.2s\n"
"fmul v5.2s, v24.2s, v1.2s\n"
"bif v22.16b, v6.16b, v7.16b\n"
"fcmge v6.2s, v25.2s, v0.2s\n"
"fmul v7.2s, v25.2s, v1.2s\n"
"bif v23.16b, v3.16b, v2.16b\n"
"fcmge v2.2s, v26.2s, v0.2s\n"
"fmul v3.2s, v26.2s, v1.2s\n"
"bif v24.16b, v5.16b, v4.16b\n"
"fcmge v4.2s, v27.2s, v0.2s\n"
"fmul v5.2s, v27.2s, v1.2s\n"
"bif v25.16b, v6.16b, v7.16b\n"
"fcmge v6.2s, v28.2s, v0.2s\n"
"fmul v7.2s, v28.2s, v1.2s\n"
"bif v26.16b, v3.16b, v2.16b\n"
"fcmge v2.2s, v29.2s, v0.2s\n"
"fmul v3.2s, v29.2s, v1.2s\n"
"bif v27.16b, v5.16b, v4.16b\n"
"fcmge v4.2s, v30.2s, v0.2s\n"
"fmul v5.2s, v30.2s, v1.2s\n"
"bif v28.16b, v6.16b, v7.16b\n"
"fcmge v6.2s, v31.2s, v0.2s\n"
"fmul v7.2s, v31.2s, v1.2s\n"
"bif v29.16b, v3.16b, v2.16b\n"
"bif v30.16b, v5.16b, v4.16b\n"
"bif v31.16b, v7.16b, v6.16b\n"
"b 5f\n"
"6: \n" // relu
"fmax v8.2s, v8.2s, v0.2s\n"
"fmax v9.2s, v9.2s, v0.2s\n"
"fmax v10.2s, v10.2s, v0.2s\n"
"fmax v11.2s, v11.2s, v0.2s\n"
"fmax v12.2s, v12.2s, v0.2s\n"
"fmax v13.2s, v13.2s, v0.2s\n"
"fmax v14.2s, v14.2s, v0.2s\n"
"fmax v15.2s, v15.2s, v0.2s\n"
"fmax v16.2s, v16.2s, v0.2s\n"
"fmax v17.2s, v17.2s, v0.2s\n"
"fmax v18.2s, v18.2s, v0.2s\n"
"fmax v19.2s, v19.2s, v0.2s\n"
"fmax v20.2s, v20.2s, v0.2s\n"
"fmax v21.2s, v21.2s, v0.2s\n"
"fmax v22.2s, v22.2s, v0.2s\n"
"fmax v23.2s, v23.2s, v0.2s\n"
"fmax v24.2s, v24.2s, v0.2s\n"
"fmax v25.2s, v25.2s, v0.2s\n"
"fmax v26.2s, v26.2s, v0.2s\n"
"fmax v27.2s, v27.2s, v0.2s\n"
"fmax v28.2s, v28.2s, v0.2s\n"
"fmax v29.2s, v29.2s, v0.2s\n"
"fmax v30.2s, v30.2s, v0.2s\n"
"fmax v31.2s, v31.2s, v0.2s\n"
"b 5f\n"
"7: \n" // relu6
"fmax v8.2s, v8.2s, v0.2s\n"
"fmax v9.2s, v9.2s, v0.2s\n"
"fmax v10.2s, v10.2s, v0.2s\n"
"fmax v11.2s, v11.2s, v0.2s\n"
"fmax v12.2s, v12.2s, v0.2s\n"
"fmax v13.2s, v13.2s, v0.2s\n"
"fmax v14.2s, v14.2s, v0.2s\n"
"fmax v15.2s, v15.2s, v0.2s\n"
"fmax v16.2s, v16.2s, v0.2s\n"
"fmax v17.2s, v17.2s, v0.2s\n"
"fmax v18.2s, v18.2s, v0.2s\n"
"fmax v19.2s, v19.2s, v0.2s\n"
"fmax v20.2s, v20.2s, v0.2s\n"
"fmax v21.2s, v21.2s, v0.2s\n"
"fmax v22.2s, v22.2s, v0.2s\n"
"fmax v23.2s, v23.2s, v0.2s\n"
"fmax v24.2s, v24.2s, v0.2s\n"
"fmax v25.2s, v25.2s, v0.2s\n"
"fmax v26.2s, v26.2s, v0.2s\n"
"fmax v27.2s, v27.2s, v0.2s\n"
"fmax v28.2s, v28.2s, v0.2s\n"
"fmax v29.2s, v29.2s, v0.2s\n"
"fmax v30.2s, v30.2s, v0.2s\n"
"fmax v31.2s, v31.2s, v0.2s\n"
"fmin v8.2s, v8.2s, v1.2s\n"
"fmin v9.2s, v9.2s, v1.2s\n"
"fmin v10.2s, v10.2s, v1.2s\n"
"fmin v11.2s, v11.2s, v1.2s\n"
"fmin v12.2s, v12.2s, v1.2s\n"
"fmin v13.2s, v13.2s, v1.2s\n"
"fmin v14.2s, v14.2s, v1.2s\n"
"fmin v15.2s, v15.2s, v1.2s\n"
"fmin v16.2s, v16.2s, v1.2s\n"
"fmin v17.2s, v17.2s, v1.2s\n"
"fmin v18.2s, v18.2s, v1.2s\n"
"fmin v19.2s, v19.2s, v1.2s\n"
"fmin v20.2s, v20.2s, v1.2s\n"
"fmin v21.2s, v21.2s, v1.2s\n"
"fmin v22.2s, v22.2s, v1.2s\n"
"fmin v23.2s, v23.2s, v1.2s\n"
"fmin v24.2s, v24.2s, v1.2s\n"
"fmin v25.2s, v25.2s, v1.2s\n"
"fmin v26.2s, v26.2s, v1.2s\n"
"fmin v27.2s, v27.2s, v1.2s\n"
"fmin v28.2s, v28.2s, v1.2s\n"
"fmin v29.2s, v29.2s, v1.2s\n"
"fmin v30.2s, v30.2s, v1.2s\n"
"fmin v31.2s, v31.2s, v1.2s\n"
"b 5f\n"
// no act
"5: \n"
"str d8, [%[c_ptr0]], #8\n"
"str d11, [%[c_ptr1]], #8\n"
"str d14, [%[c_ptr2]], #8\n"
"str d17, [%[c_ptr3]], #8\n"
"str d20, [%[c_ptr4]], #8\n"
"str d23, [%[c_ptr5]], #8\n"
"str d26, [%[c_ptr6]], #8\n"
"str d29, [%[c_ptr7]], #8\n"
"str d9, [%[c_ptr0]], #8\n"
"str d12, [%[c_ptr1]], #8\n"
"str d15, [%[c_ptr2]], #8\n"
"str d18, [%[c_ptr3]], #8\n"
"str d21, [%[c_ptr4]], #8\n"
"str d24, [%[c_ptr5]], #8\n"
"str d27, [%[c_ptr6]], #8\n"
"str d30, [%[c_ptr7]], #8\n"
"str d10, [%[c_ptr0]], #8\n"
"str d13, [%[c_ptr1]], #8\n"
"str d16, [%[c_ptr2]], #8\n"
"str d19, [%[c_ptr3]], #8\n"
"str d22, [%[c_ptr4]], #8\n"
"str d25, [%[c_ptr5]], #8\n"
"str d28, [%[c_ptr6]], #8\n"
"str d31, [%[c_ptr7]], #8\n"
: [a_ptr] "+r"(a_ptr),
[b_ptr] "+r"(b_ptr),
[k] "+r"(k),
[c_ptr0] "+r"(c_ptr0),
[c_ptr1] "+r"(c_ptr1),
[c_ptr2] "+r"(c_ptr2),
[c_ptr3] "+r"(c_ptr3),
[c_ptr4] "+r"(c_ptr4),
[c_ptr5] "+r"(c_ptr5),
[c_ptr6] "+r"(c_ptr6),
[c_ptr7] "+r"(c_ptr7)
: [bias_ptr] "r"(bias_local),
[has_beta] "r"(has_beta),
[beta] "r"(beta),
[alpha] "r"(alpha),
[tail] "r"(tail),
[flag_act] "r"(flag_act)
: "cc","memory",
"v0","v1","v2","v3","v4","v5","v6","v7",
"v8","v9","v10","v11","v12","v13",
"v14","v15","v16","v17","v18","v19",
"v20","v21","v22","v23","v24","v25",
"v26","v27","v28","v29","v30","v31");
// clang-format on
if (flag_p_remain && (xb == bblocks - 1)) {
for (int i = 0; i < remain; ++i) {
*pout0++ = cout0[i];
*pout1++ = cout1[i];
*pout2++ = cout2[i];
*pout3++ = cout3[i];
*pout4++ = cout4[i];
*pout5++ = cout5[i];
*pout6++ = cout6[i];
*pout7++ = cout7[i];
}
}
}
}
}
}
#undef FMLA_N8X6
#else
void sgemm_prepacked_4x8_a35(bool is_transB,
int M,
int N,
int K,
const float* A_packed,
const float* B,
int ldb,
float beta,
float* C,
int ldc,
const float* bias,
bool has_bias,
const operators::ActivationParam act_param,
ARMContext* ctx) {
size_t l2_cache = ctx->llc_size() > 0 ? ctx->llc_size() : 512 * 1024;
auto* workspace = ctx->workspace_data<float>();
int threads = ctx->threads();
auto act_type = act_param.active_type;
float alpha[4] = {0.f, 0.f, 0.f, 0.f};
int flag_act = 0x00; // relu: 1, relu6: 2, leakey: 3
if (act_param.has_active) {
if (act_type == lite_api::ActivationType::kRelu) {
flag_act = 0x01;
} else if (act_type == lite_api::ActivationType::kRelu6) {
flag_act = 0x02;
float local_alpha = act_param.Relu_clipped_coef;
alpha[0] = local_alpha;
alpha[1] = local_alpha;
alpha[2] = local_alpha;
alpha[3] = local_alpha;
} else if (act_type == lite_api::ActivationType::kLeakyRelu) {
flag_act = 0x03;
float local_alpha = act_param.Leaky_relu_alpha;
alpha[0] = local_alpha;
alpha[1] = local_alpha;
alpha[2] = local_alpha;
alpha[3] = local_alpha;
}
}
X_BLOCK_COMPUTE(l2_cache, MBLOCK_A73, NBLOCK, M, N, K)
int k_num = 2;
int k_pre = ((K + k_num - 1) / k_num) - 1;
int tail_pre = (K & (k_num - 1));
if (tail_pre == 0) {
tail_pre = k_num;
}
bool flag_p_remain = false;
int remain = 0;
//! merge tail_pre and flag_act
tail_pre = (tail_pre << 2 | flag_act);
int has_beta = fabsf(beta) > 1e-8f ? 1 : 0;
//! apanel is pre_compute outside gemm
for (unsigned int x0 = 0; x0 < N; x0 += x_block) {
unsigned int xmax = x0 + x_block;
if (xmax > N) {
xmax = N;
}
int bblocks = (xmax - x0 + NBLOCK - 1) / NBLOCK;
remain = xmax - x0 - (bblocks - 1) * NBLOCK;
if (remain > 0) {
flag_p_remain = true;
}
//! load bpanel
auto b_pannel = static_cast<float*>(workspace);
if (is_transB) {
loadb_trans(b_pannel, B, ldb, 0, K, x0, xmax);
} else {
loadb(b_pannel, B, ldb, 0, K, x0, xmax);
}
#pragma omp parallel for num_threads(threads)
for (unsigned int y = 0; y < M; y += MBLOCK_A73) {
unsigned int ymax = y + MBLOCK_A73;
if (ymax > M) {
ymax = M;
}
float cout0[NBLOCK];
float cout1[NBLOCK];
float cout2[NBLOCK];
float cout3[NBLOCK];
float bias_local[4] = {0};
if (has_bias) {
bias_local[0] = bias[y];
bias_local[1] = bias[y + 1];
bias_local[2] = bias[y + 2];
bias_local[3] = bias[y + 3];
}
float* c_ptr0 = C + y * ldc + x0;
float* c_ptr1 = c_ptr0 + ldc;
float* c_ptr2 = c_ptr1 + ldc;
float* c_ptr3 = c_ptr2 + ldc;
float* pout0 = c_ptr0;
float* pout1 = c_ptr1;
float* pout2 = c_ptr2;
float* pout3 = c_ptr3;
const float* a_ptr_l = A_packed + y * K;
const float* b_ptr = b_pannel;
for (int xb = 0; xb < bblocks; xb++) {
if ((y + 3) >= ymax) {
switch ((y + 3) - ymax) {
case 2:
c_ptr1 = cout1;
case 1:
c_ptr2 = cout1;
case 0:
c_ptr3 = cout1;
default:
break;
}
}
if (flag_p_remain && (xb == bblocks - 1)) {
pout0 = c_ptr0;
pout1 = c_ptr1;
pout2 = c_ptr2;
pout3 = c_ptr3;
c_ptr0 = cout0;
c_ptr1 = cout1;
c_ptr2 = cout2;
c_ptr3 = cout3;
if (has_beta) {
for (int i = 0; i < remain; ++i) {
cout0[i] = pout0[i];
cout1[i] = pout1[i];
cout2[i] = pout2[i];
cout3[i] = pout3[i];
}
}
}
const float* a_ptr = a_ptr_l;
int tails = tail_pre;
int k = k_pre;
// clang-format off
asm volatile(
"pld [%[a_ptr]] @ preload a, 64byte\n"
"vld1.32 {d6-d7}, [%[bias_ptr]] @ load bias\n"
"pld [%[b_ptr]] @ preload b\n"
"vldr d0, [%[a_ptr]] \n"
"vdup.32 q8, d6[0] @ add bias to out00\n"
"vldr d4, [%[b_ptr]] \n"
"vdup.32 q9, d6[0] @ add bias to out01\n"
"vldr d1, [%[a_ptr], #0x08] \n"
"vdup.32 q10, d6[1] @ add bias to out10\n"
"vldr d5, [%[b_ptr], #0x08] \n"
"vdup.32 q11, d6[1] @ add bias to out11\n"
"pld [%[a_ptr], #64] @ preload a\n"
"vdup.32 q12, d7[0] @ add bias to out20\n"
"pld [%[b_ptr], #64] @ preload b\n"
"vdup.32 q13, d7[0] @ add bias to out21\n"
"pld [%[a_ptr], #128] @ preload a\n"
"cmp %[beta], #0\n" // check beta == 0
"vdup.32 q14, d7[1] @ add bias to out30\n"
"pld [%[b_ptr], #128] @ preload b\n"
"vdup.32 q15, d7[1] @ add bias to out31\n"
"pld [%[b_ptr], #192] @ preload b\n"
"beq 11f\n"
// process beta
"vdup.32 q4, %[beta]\n"
"vld1.32 {d0-d3}, [%[c_ptr0]]\n"
"vld1.32 {d4-d7}, [%[c_ptr1]]\n"
"vmla.f32 q8, q0, q4\n"
"vmla.f32 q9, q1, q4\n"
"vld1.32 {d0-d3}, [%[c_ptr2]]\n"
"vmla.f32 q10, q2, q4\n"
"vmla.f32 q11, q3, q4\n"
"vld1.32 {d4-d7}, [%[c_ptr3]]\n"
"vmla.f32 q12, q0, q4\n"
"vmla.f32 q13, q1, q4\n"
"vmla.f32 q14, q2, q4\n"
"vmla.f32 q15, q3, q4\n"
"vld1.32 {d0-d1}, [%[a_ptr] :128] @ load a0~a3\n"
"vld1.32 {d4-d5}, [%[b_ptr] :128] @ load b1\n"
"11: \n" /* check loop count */
"cmp %[k], #0 @ check k==0 \n"
"beq 0f @ jump to tail\n"
"1: @ main loop for k\n"
/* Unroll 0*/
"vldr d6, [%[b_ptr], #0x10] \n"
"vmla.f32 q8, q2, d0[0]\n"
"ldr r0, [%[b_ptr], #0x18] \n"
"vmla.f32 q10, q2, d0[1]\n"
"ldr r1, [%[b_ptr], #0x1c] \n"
"vmla.f32 q12, q2, d1[0]\n"
"vldr d2, [%[a_ptr], #0x10] \n"
"vmov d7, r0, r1 \n"
"vmla.f32 q14, q2, d1[1]\n"
"ldr r0, [%[a_ptr], #0x18] \n"
"vmla.f32 q9, q3, d0[0]\n"
"ldr r1, [%[a_ptr], #0x1c] \n"
"vmla.f32 q11, q3, d0[1]\n"
"vldr d8, [%[b_ptr], #0x20] \n"
"vmov d3, r0, r1 \n"
"ldr r0, [%[b_ptr], #0x28] \n"
"vmla.f32 q13, q3, d1[0]\n"
"ldr r1, [%[b_ptr], #0x2c] \n"
"vmla.f32 q15, q3, d1[1]\n"
"vldr d10, [%[b_ptr], #0x30] \n"
"vmov d9, r0, r1 \n"
/* Unroll 1 */
"vmla.f32 q8, q4, d2[0]\n"
"ldr r0, [%[b_ptr], #0x38] \n"
"vmla.f32 q10, q4, d2[1]\n"
"ldr r1, [%[b_ptr], #0x3c] \n"
"pld [%[a_ptr], #128] @ preload b\n"
"vmla.f32 q12, q4, d3[0]\n"
"vldr d0, [%[a_ptr], #0x20] \n"
"vmov d11, r0, r1 \n"
"ldr r0, [%[a_ptr], #0x28] \n"
"vmla.f32 q14, q4, d3[1]\n"
"ldr r1, [%[a_ptr], #0x2c] \n"
"pld [%[b_ptr], #192] @ preload b\n"
"vmla.f32 q9, q5, d2[0]\n"
"vldr d4, [%[b_ptr], #0x40] \n"
"vmov d1, r0, r1 \n"
"vmla.f32 q11, q5, d2[1]\n"
"ldr r0, [%[b_ptr], #0x48] \n"
"vmla.f32 q13, q5, d3[0]\n"
"ldr r1, [%[b_ptr], #0x4c] \n"
"subs %[k], %[k], #1 @ k--\n"
"add %[b_ptr], %[b_ptr], #0x40 \n"
"vmla.f32 q15, q5, d3[1]\n"
"vmov d5, r0, r1 \n"
"add %[a_ptr], %[a_ptr], #0x20 \n"
"bne 1b @ jump to main loop\n"
"0: @ process tail\n"
"sub %[tails], %[tails], #4 @ tail--\n"
"cmp %[tails], #4 @ cmp with act bits\n"
"blt 3f @ jump to tail = 1\n"
/* Unroll 0*/
"vldr d6, [%[b_ptr], #0x10] \n"
"vmla.f32 q8, q2, d0[0]\n"
"ldr r0, [%[b_ptr], #0x18] \n"
"vmla.f32 q10, q2, d0[1]\n"
"ldr r1, [%[b_ptr], #0x1c] \n"
"vmla.f32 q12, q2, d1[0]\n"
"vldr d2, [%[a_ptr], #0x10] \n"
"vmov d7, r0, r1 \n"
"vmla.f32 q14, q2, d1[1]\n"
"ldr r0, [%[a_ptr], #0x18] \n"
"vmla.f32 q9, q3, d0[0]\n"
"ldr r1, [%[a_ptr], #0x1c] \n"
"vmla.f32 q11, q3, d0[1]\n"
"vldr d8, [%[b_ptr], #0x20] \n"
"vmov d3, r0, r1 \n"
"vmla.f32 q13, q3, d1[0]\n"
"ldr r0, [%[b_ptr], #0x28] \n"
"vmla.f32 q15, q3, d1[1]\n"
"ldr r1, [%[b_ptr], #0x2c] \n"
"vldr d10, [%[b_ptr], #0x30] \n"
"vmov d9, r0, r1 \n"
/* Unroll 1 */
"vmla.f32 q8, q4, d2[0]\n"
"ldr r0, [%[b_ptr], #0x38] \n"
"vmla.f32 q10, q4, d2[1]\n"
"ldr r1, [%[b_ptr], #0x3c] \n"
"vmla.f32 q12, q4, d3[0]\n"
"vmov d11, r0, r1 \n"
"vmla.f32 q14, q4, d3[1]\n"
"sub %[tails], %[tails], #4 @ tail--\n"
"vmla.f32 q9, q5, d2[0]\n"
"add %[b_ptr], %[b_ptr], #0x40 \n"
"vmla.f32 q11, q5, d2[1]\n"
"vmla.f32 q13, q5, d3[0]\n"
"add %[a_ptr], %[a_ptr], #0x20 \n"
"vmla.f32 q15, q5, d3[1]\n"
"b 2f\n"
/* tails==1 final tail */
"3: @ tail=1\n"
"vmla.f32 q8, q2, d0[0]\n"
"vldr d6, [%[b_ptr], #0x10]\n"
"vmla.f32 q10, q2, d0[1]\n"
"ldr r0, [%[b_ptr], #0x18] \n"
"vmla.f32 q12, q2, d1[0]\n"
"ldr r1, [%[b_ptr], #0x1c] \n"
"vmla.f32 q14, q2, d1[1]\n"
"vmov d7, r0, r1 \n"
"add %[a_ptr], %[a_ptr], #0x10 \n"
"vmla.f32 q9, q3, d0[0]\n"
"vmla.f32 q11, q3, d0[1]\n"
"add %[b_ptr], %[b_ptr], #0x20 \n"
"vmla.f32 q13, q3, d1[0]\n"
"vmla.f32 q15, q3, d1[1]\n"
"2: @ check relu\n"
//! relu
"cmp %[tails], #1 @ check if has relu\n"
"bne 6f @ jump if not relu \n"
"vmov.u32 q0, #0 @ for relu\n"
"vmax.f32 q8, q8, q0 @ for relu\n"
"vmax.f32 q9, q9, q0 @ for relu\n"
"vmax.f32 q10, q10, q0 @ for relu\n"
"vmax.f32 q11, q11, q0 @ for relu\n"
"vmax.f32 q12, q12, q0 @ for relu\n"
"vmax.f32 q13, q13, q0 @ for relu\n"
"vmax.f32 q14, q14, q0 @ for relu\n"
"vmax.f32 q15, q15, q0 @ for relu\n"
"b 10f @ relu end\n"
"6: @ no relu \n"
"cmp %[tails], #0 @ check no act\n"
"beq 10f @ no act end \n"
//! relu6
"cmp %[tails], #2 @ check if has relu6\n"
"bne 7f @ jump if no relu6 \n"
"vmov.u32 q0, #0 @ for relu6\n"
"vld1.f32 {d2-d3}, [%[alpha]] @ load relu6 alpha\n"
"vmax.f32 q8, q8, q0 @ for relu6\n"
"vmax.f32 q9, q9, q0 @ for relu6\n"
"vmax.f32 q10, q10, q0 @ for relu6\n"
"vmax.f32 q11, q11, q0 @ for relu6\n"
"vmax.f32 q12, q12, q0 @ for relu6\n"
"vmax.f32 q13, q13, q0 @ for relu6\n"
"vmax.f32 q14, q14, q0 @ for relu6\n"
"vmax.f32 q15, q15, q0 @ for relu6\n"
"vmin.f32 q8, q8, q1 @ for relu6\n"
"vmin.f32 q9, q9, q1 @ for relu6\n"
"vmin.f32 q10, q10, q1 @ for relu6\n"
"vmin.f32 q11, q11, q1 @ for relu6\n"
"vmin.f32 q12, q12, q1 @ for relu6\n"
"vmin.f32 q13, q13, q1 @ for relu6\n"
"vmin.f32 q14, q14, q1 @ for relu6\n"
"vmin.f32 q15, q15, q1 @ for relu6\n"
"b 10f @ relu6 end \n"
//! leakey relu
"7: @ otherwise is leakey relu\n"
"vmov.u32 q0, #0 @ for leakey relu \n"
"vld1.f32 {d2-d3}, [%[alpha]] @ load leakey relu alpha\n"
"vcge.f32 q2, q8, q0 @ vcgeq_u32 \n"
"vmul.f32 q3, q8, q1 @ vmulq_f32 \n"
"vbif q8, q3, q2 @ choose \n"
"vcge.f32 q2, q9, q0 @ vcgeq_u32 \n"
"vmul.f32 q3, q9, q1 @ vmulq_f32 \n"
"vbif q9, q3, q2 @ choose \n"
"vcge.f32 q2, q10, q0 @ vcgeq_u32 \n"
"vmul.f32 q3, q10, q1 @ vmulq_f32 \n"
"vbif q10, q3, q2 @ choose \n"
"vcge.f32 q2, q11, q0 @ vcgeq_u32 \n"
"vmul.f32 q3, q11, q1 @ vmulq_f32 \n"
"vbif q11, q3, q2 @ choose \n"
"vcge.f32 q2, q12, q0 @ vcgeq_u32 \n"
"vmul.f32 q3, q12, q1 @ vmulq_f32 \n"
"vbif q12, q3, q2 @ choose \n"
"vcge.f32 q2, q13, q0 @ vcgeq_u32 \n"
"vmul.f32 q3, q13, q1 @ vmulq_f32 \n"
"vbif q13, q3, q2 @ choose \n"
"vcge.f32 q2, q14, q0 @ vcgeq_u32 \n"
"vmul.f32 q3, q14, q1 @ vmulq_f32 \n"
"vbif q14, q3, q2 @ choose \n"
"vcge.f32 q2, q15, q0 @ vcgeq_u32 \n"
"vmul.f32 q3, q15, q1 @ vmulq_f32 \n"
"vbif q15, q3, q2 @ choose \n"
"10: @ act end \n"
"vst1.32 {d16-d19}, [%[c_ptr0]]! @ store r0\n"
"vst1.32 {d20-d23}, [%[c_ptr1]]! @ store r1\n"
"vst1.32 {d24-d27}, [%[c_ptr2]]! @ store r2\n"
"vst1.32 {d28-d31}, [%[c_ptr3]]! @ store r3\n"
: [a_ptr] "+r"(a_ptr),
[b_ptr] "+r"(b_ptr),
[c_ptr0] "+r"(c_ptr0),
[c_ptr1] "+r"(c_ptr1),
[c_ptr2] "+r"(c_ptr2),
[c_ptr3] "+r"(c_ptr3),
[k] "+r"(k),
[tails] "+r"(tails)
: [bias_ptr] "r"(bias_local),
[beta] "r"(beta),
[alpha] "r"(alpha)
: "r0", "r1", "q0","q1","q2","q3",
"q4","q5","q6","q7","q8","q9","q10",
"q11","q12","q13","q14","q15","cc","memory");
// clang-format on
if (flag_p_remain && (xb == bblocks - 1)) {
for (int i = 0; i < remain; ++i) {
*pout0++ = cout0[i];
*pout1++ = cout1[i];
*pout2++ = cout2[i];
*pout3++ = cout3[i];
}
}
}
}
}
}
#endif
} // namespace math
} // namespace arm
} // namespace lite
} // namespace paddle
|
GeometryConverter.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 <unordered_set>
#include <ifcpp/model/BasicTypes.h>
#include <ifcpp/model/BuildingModel.h>
#include <ifcpp/model/StatusCallback.h>
#include <ifcpp/IFC4/include/IfcCurtainWall.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 "IncludeCarveHeaders.h"
#include "GeometryInputData.h"
#include "RepresentationConverter.h"
#include "CSG_Adapter.h"
class GeometryConverter : public StatusCallback
{
protected:
shared_ptr<BuildingModel> m_ifc_model;
shared_ptr<GeometrySettings> m_geom_settings;
shared_ptr<RepresentationConverter> m_representation_converter;
std::map<int, shared_ptr<ProductShapeData> > m_product_shape_data;
std::map<int, shared_ptr<BuildingObject> > m_map_outside_spatial_structure;
double m_recent_progress = 0;
double m_csg_eps = 1.5e-05;
std::map<int, std::vector<shared_ptr<StatusCallback::Message> > > m_messages;
#ifdef ENABLE_OPENMP
Mutex m_writelock_messages;
#endif
public:
// getters and setters
shared_ptr<BuildingModel>& getBuildingModel() { return m_ifc_model; }
shared_ptr<RepresentationConverter>& getRepresentationConverter() { return m_representation_converter; }
shared_ptr<GeometrySettings>& getGeomSettings() { return m_geom_settings; }
std::map<int, shared_ptr<ProductShapeData> >& getShapeInputData() { return m_product_shape_data; }
std::map<int, shared_ptr<BuildingObject> >& getObjectsOutsideSpatialStructure() { return m_map_outside_spatial_structure; }
GeometryConverter( shared_ptr<BuildingModel>& ifc_model )
{
m_ifc_model = ifc_model;
m_geom_settings = shared_ptr<GeometrySettings>( new GeometrySettings() );
resetNumVerticesPerCircle();
shared_ptr<UnitConverter>& unit_converter = m_ifc_model->getUnitConverter();
m_representation_converter = shared_ptr<RepresentationConverter>( new RepresentationConverter( m_geom_settings, unit_converter ) );
// redirect all messages to this->messageTarget
m_ifc_model->setMessageTarget( this );
m_representation_converter->setMessageTarget( this );
}
virtual ~GeometryConverter() {}
void resetModel()
{
progressTextCallback( L"Unloading model, cleaning up memory..." );
clearInputCache();
m_recent_progress = 0.0;
m_ifc_model->clearCache();
m_ifc_model->clearIfcModel();
progressTextCallback( L"Unloading model done" );
progressValueCallback( 0.0, "parse" );
#ifdef _DEBUG
GeomDebugDump::clearMeshsetDump();
#endif
}
void clearInputCache()
{
m_product_shape_data.clear();
m_map_outside_spatial_structure.clear();
m_representation_converter->clearCache();
m_messages.clear();
}
void resetNumVerticesPerCircle()
{
m_geom_settings->resetNumVerticesPerCircle();
}
void setCsgEps(double eps)
{
m_csg_eps = eps;
}
void setModel( shared_ptr<BuildingModel> model )
{
if( m_ifc_model )
{
m_ifc_model->unsetMessageCallBack();
}
clearInputCache();
m_ifc_model = model;
m_representation_converter->clearCache();
m_representation_converter->setUnitConverter( m_ifc_model->getUnitConverter() );
m_ifc_model->setMessageTarget( this );
}
void resolveProjectStructure( shared_ptr<ProductShapeData>& product_data )
{
if( !product_data )
{
return;
}
if( product_data->m_ifc_object_definition.expired() )
{
return;
}
shared_ptr<IfcObjectDefinition> ifc_object_def( product_data->m_ifc_object_definition );
const int entity_id = ifc_object_def->m_entity_id;
product_data->m_added_to_spatial_structure = true;
const std::vector<weak_ptr<IfcRelAggregates> >& vec_IsDecomposedBy = ifc_object_def->m_IsDecomposedBy_inverse;
for( size_t ii = 0; ii < vec_IsDecomposedBy.size(); ++ii )
{
const weak_ptr<IfcRelAggregates>& rel_aggregates_weak_ptr = vec_IsDecomposedBy[ii];
if( rel_aggregates_weak_ptr.expired() )
{
continue;
}
shared_ptr<IfcRelAggregates> rel_aggregates( rel_aggregates_weak_ptr );
if( rel_aggregates )
{
const std::vector<shared_ptr<IfcObjectDefinition> >& vec_related_objects = rel_aggregates->m_RelatedObjects;
for( size_t jj = 0; jj < vec_related_objects.size(); ++jj )
{
const shared_ptr<IfcObjectDefinition>& related_obj_def = vec_related_objects[jj];
if( related_obj_def )
{
auto it_product_map = m_product_shape_data.find( related_obj_def->m_entity_id );
if( it_product_map != m_product_shape_data.end() )
{
shared_ptr<ProductShapeData>& related_product_shape = it_product_map->second;
if( related_product_shape )
{
product_data->addChildProduct( related_product_shape, product_data );
resolveProjectStructure( related_product_shape );
}
}
}
}
}
}
shared_ptr<IfcSpatialStructureElement> spatial_ele = dynamic_pointer_cast<IfcSpatialStructureElement>(ifc_object_def);
if( spatial_ele )
{
const std::vector<weak_ptr<IfcRelContainedInSpatialStructure> >& vec_contains = spatial_ele->m_ContainsElements_inverse;
for( size_t ii = 0; ii < vec_contains.size(); ++ii )
{
const weak_ptr<IfcRelContainedInSpatialStructure>& rel_contained_weak_ptr = vec_contains[ii];
if( rel_contained_weak_ptr.expired() )
{
continue;
}
shared_ptr<IfcRelContainedInSpatialStructure> rel_contained( rel_contained_weak_ptr );
if( rel_contained )
{
const std::vector<shared_ptr<IfcProduct> >& vec_related_elements = rel_contained->m_RelatedElements;
for( size_t jj = 0; jj < vec_related_elements.size(); ++jj )
{
const shared_ptr<IfcProduct>& related_product = vec_related_elements[jj];
if( related_product )
{
auto it_product_map = m_product_shape_data.find( related_product->m_entity_id );
if( it_product_map != m_product_shape_data.end() )
{
shared_ptr<ProductShapeData>& related_product_shape = it_product_map->second;
if( related_product_shape )
{
product_data->addChildProduct( related_product_shape, product_data );
resolveProjectStructure( related_product_shape );
}
}
}
}
}
}
}
// TODO: handle IfcRelAssignsToProduct
}
void readAppearanceFromPropertySet( const shared_ptr<IfcPropertySet>& prop_set, shared_ptr<ProductShapeData>& product_shape )
{
if( !prop_set )
{
return;
}
for( auto& ifc_property : prop_set->m_HasProperties )
{
if( !ifc_property )
{
continue;
}
shared_ptr<IfcSimpleProperty> simple_property = dynamic_pointer_cast<IfcSimpleProperty>(ifc_property);
if( simple_property )
{
// ENTITY IfcSimpleProperty ABSTRACT SUPERTYPE OF(ONEOF( IfcPropertyBoundedValue, IfcPropertyEnumeratedValue, IfcPropertyListValue,
// IfcPropertyReferenceValue, IfcPropertySingleValue, IfcPropertyTableValue))
shared_ptr<IfcIdentifier> property_name = simple_property->m_Name;
std::wstring name_str = property_name->m_value;
if( name_str.compare( L"LayerName" ) == 0 )
{
// TODO: implement layers
}
shared_ptr<IfcText> description = simple_property->m_Description;
shared_ptr<IfcPropertySingleValue> property_single_value = dynamic_pointer_cast<IfcPropertySingleValue>(simple_property);
if( property_single_value )
{
//shared_ptr<IfcValue>& nominal_value = property_single_value->m_NominalValue; //optional
//shared_ptr<IfcUnit>& unit = property_single_value->m_Unit; //optional
}
continue;
}
shared_ptr<IfcComplexProperty> complex_property = dynamic_pointer_cast<IfcComplexProperty>(ifc_property);
if( complex_property )
{
if( !complex_property->m_UsageName ) continue;
if( complex_property->m_UsageName->m_value.compare( L"Color" ) == 0 )
{
vec4 vec_color;
m_representation_converter->getStylesConverter()->convertIfcComplexPropertyColor( complex_property, vec_color );
shared_ptr<AppearanceData> appearance_data( new AppearanceData( -1 ) );
if( !appearance_data )
{
throw OutOfMemoryException( __FUNC__ );
}
appearance_data->m_apply_to_geometry_type = AppearanceData::GEOM_TYPE_ANY;
appearance_data->m_color_ambient.setColor( vec_color );
appearance_data->m_color_diffuse.setColor( vec_color );
appearance_data->m_color_specular.setColor( vec_color );
appearance_data->m_shininess = 35.f;
product_shape->addAppearance( appearance_data );
}
}
}
}
/*\brief method convertGeometry: Creates geometry for Carve from previously loaded BuildingModel model.
**/
void convertGeometry()
{
progressTextCallback( L"Creating geometry..." );
progressValueCallback( 0, "geometry" );
m_product_shape_data.clear();
m_map_outside_spatial_structure.clear();
m_representation_converter->clearCache();
if( !m_ifc_model )
{
return;
}
shared_ptr<ProductShapeData> ifc_project_data;
std::vector<shared_ptr<IfcObjectDefinition> > vec_object_defs;
double length_to_meter_factor = 1.0;
if( m_ifc_model->getUnitConverter() )
{
length_to_meter_factor = m_ifc_model->getUnitConverter()->getLengthInMeterFactor();
}
carve::setEpsilon( m_csg_eps );
const std::map<int, shared_ptr<BuildingEntity> >& map_entities = m_ifc_model->getMapIfcEntities();
for( auto it = map_entities.begin(); it != map_entities.end(); ++it )
{
shared_ptr<BuildingEntity> obj = it->second;
shared_ptr<IfcObjectDefinition> object_def = dynamic_pointer_cast<IfcObjectDefinition>(obj);
if( object_def )
{
vec_object_defs.push_back( object_def );
}
}
// create geometry for for each IfcProduct independently, spatial structure will be resolved later
std::map<int, shared_ptr<ProductShapeData> >* map_products_ptr = &m_product_shape_data;
const int num_products = (int)vec_object_defs.size();
#ifdef ENABLE_OPENMP
Mutex writelock_map;
Mutex writelock_ifc_project;
#pragma omp parallel firstprivate(num_products) shared(map_products_ptr)
{
// time for one product may vary significantly, so schedule not so many
#pragma omp for schedule(dynamic,40)
#endif
for( int i = 0; i < num_products; ++i )
{
shared_ptr<IfcObjectDefinition> ifc_object_def = vec_object_defs[i];
const int entity_id = ifc_object_def->m_entity_id;
shared_ptr<ProductShapeData> product_geom_input_data( new ProductShapeData( entity_id ) );
product_geom_input_data->m_ifc_object_definition = ifc_object_def;
std::stringstream thread_err;
if( !m_geom_settings->getRenderObjectFilter()(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 = product_geom_input_data;
}
try
{
convertIfcProductShape( product_geom_input_data );
}
catch( OutOfMemoryException& e )
{
throw e;
}
catch( BuildingException& e )
{
thread_err << e.what();
}
catch( carve::exception& e )
{
thread_err << e.str();
}
catch( std::exception& e )
{
thread_err << e.what();
}
catch( ... )
{
thread_err << "undefined error, product id " << entity_id;
}
{
#ifdef ENABLE_OPENMP
ScopedLock scoped_lock( writelock_map );
#endif
map_products_ptr->insert( std::make_pair( entity_id, product_geom_input_data ) );
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, "geometry" );
m_recent_progress = progress;
}
}
}
#ifdef ENABLE_OPENMP
} // implicit barrier
#endif
// subtract openings in related objects, such as IFCBUILDINGELEMENTPART connected to a window through IFCRELAGGREGATES
for( auto it = map_products_ptr->begin(); it != map_products_ptr->end(); ++it )
{
shared_ptr<ProductShapeData> product_geom_input_data = it->second;
try
{
subtractOpeningsInRelatedObjects(product_geom_input_data);
}
catch( OutOfMemoryException& e )
{
throw e;
}
catch( BuildingException& e )
{
messageCallback(e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "");
}
catch( carve::exception& e )
{
messageCallback(e.str(), StatusCallback::MESSAGE_TYPE_ERROR, "");
}
catch( std::exception& e )
{
messageCallback(e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "");
}
catch( ... )
{
messageCallback("undefined error", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__);
}
}
try
{
// now resolve spatial structure
if( ifc_project_data )
{
resolveProjectStructure( ifc_project_data );
}
// check if there are entities that are not in spatial structure
for( auto it_product_shapes = m_product_shape_data.begin(); it_product_shapes != m_product_shape_data.end(); ++it_product_shapes )
{
shared_ptr<ProductShapeData> product_shape = it_product_shapes->second;
if( !product_shape )
{
continue;
}
if( !product_shape->m_added_to_spatial_structure )
{
if( !product_shape->m_ifc_object_definition.expired() )
{
shared_ptr<IfcObjectDefinition> ifc_product( product_shape->m_ifc_object_definition );
shared_ptr<IfcFeatureElementSubtraction> opening = dynamic_pointer_cast<IfcFeatureElementSubtraction>(ifc_product);
if( !m_geom_settings->getRenderObjectFilter()(ifc_product) )
{
continue;
}
m_map_outside_spatial_structure[ifc_product->m_entity_id] = ifc_product;
}
}
}
}
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__ );
}
m_representation_converter->getProfileCache()->clearProfileCache();
progressTextCallback( L"Loading file done" );
progressValueCallback( 1.0, "geometry" );
}
//\brief method convertIfcProduct: Creates geometry objects (meshset with connected vertex-edge-face graph) 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 convertIfcProductShape( shared_ptr<ProductShapeData>& product_shape )
{
if( product_shape->m_ifc_object_definition.expired() )
{
return;
}
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;
}
if( !ifc_product->m_Representation )
{
return;
}
double length_factor = 1.0;
if( m_ifc_model )
{
if( m_ifc_model->getUnitConverter() )
{
length_factor = m_ifc_model->getUnitConverter()->getLengthInMeterFactor();
}
}
// evaluate IFC geometry
shared_ptr<IfcProductRepresentation>& product_representation = ifc_product->m_Representation;
std::vector<shared_ptr<IfcRepresentation> >& vec_representations = product_representation->m_Representations;
for( size_t i_representations = 0; i_representations < vec_representations.size(); ++i_representations )
{
const shared_ptr<IfcRepresentation>& representation = vec_representations[i_representations];
if( !representation )
{
continue;
}
try
{
shared_ptr<RepresentationData> representation_data( new RepresentationData() );
m_representation_converter->convertIfcRepresentation( representation, representation_data );
product_shape->m_vec_representations.push_back( representation_data );
representation_data->m_parent_product = product_shape;
}
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, "" );
}
}
// IfcProduct has an ObjectPlacement that can be local or global
product_shape->m_object_placement = ifc_product->m_ObjectPlacement;
if( ifc_product->m_ObjectPlacement )
{
// IfcPlacement2Matrix follows related placements in case of local coordinate systems
std::unordered_set<IfcObjectPlacement*> placement_already_applied;
m_representation_converter->getPlacementConverter()->convertIfcObjectPlacement( ifc_product->m_ObjectPlacement, product_shape, placement_already_applied, false );
}
// handle openings
std::vector<shared_ptr<ProductShapeData> > vec_opening_data;
const shared_ptr<IfcElement> ifc_element = dynamic_pointer_cast<IfcElement>(ifc_product);
if( ifc_element )
{
m_representation_converter->subtractOpenings(ifc_element, product_shape);
}
// Fetch the IFCProduct relationships
if( ifc_product->m_IsDefinedBy_inverse.size() > 0 )
{
std::vector<weak_ptr<IfcRelDefinesByProperties> >& vec_IsDefinedBy_inverse = ifc_product->m_IsDefinedBy_inverse;
for( size_t i = 0; i < vec_IsDefinedBy_inverse.size(); ++i )
{
shared_ptr<IfcRelDefinesByProperties> rel_def( vec_IsDefinedBy_inverse[i] );
shared_ptr<IfcPropertySetDefinitionSelect> relating_property_definition_select = rel_def->m_RelatingPropertyDefinition;
if( relating_property_definition_select )
{
// TYPE IfcPropertySetDefinitionSelect = SELECT (IfcPropertySetDefinition ,IfcPropertySetDefinitionSet);
shared_ptr<IfcPropertySetDefinition> property_set_def = dynamic_pointer_cast<IfcPropertySetDefinition>(relating_property_definition_select);
if( property_set_def )
{
shared_ptr<IfcPropertySet> property_set = dynamic_pointer_cast<IfcPropertySet>(property_set_def);
if( property_set )
{
readAppearanceFromPropertySet( property_set, product_shape );
}
continue;
}
shared_ptr<IfcPropertySetDefinitionSet> property_set_def_set = dynamic_pointer_cast<IfcPropertySetDefinitionSet>(relating_property_definition_select);
if( property_set_def_set )
{
std::vector<shared_ptr<IfcPropertySetDefinition> >& vec_propterty_set_def = property_set_def_set->m_vec;
std::vector<shared_ptr<IfcPropertySetDefinition> >::iterator it_property_set_def;
for( it_property_set_def = vec_propterty_set_def.begin(); it_property_set_def != vec_propterty_set_def.end(); ++it_property_set_def )
{
shared_ptr<IfcPropertySetDefinition> property_set_def2 = (*it_property_set_def);
if( property_set_def2 )
{
shared_ptr<IfcPropertySet> property_set = dynamic_pointer_cast<IfcPropertySet>(property_set_def2);
if( property_set )
{
readAppearanceFromPropertySet( property_set, product_shape );
}
}
}
continue;
}
}
}
}
}
void subtractOpeningsInRelatedObjects(shared_ptr<ProductShapeData>& product_shape)
{
if( product_shape->m_ifc_object_definition.expired() )
{
return;
}
shared_ptr<IfcObjectDefinition> ifc_object_def(product_shape->m_ifc_object_definition);
shared_ptr<IfcElement> ifc_element = dynamic_pointer_cast<IfcElement>(ifc_object_def);
if( !ifc_element )
{
return;
}
if( ifc_element->m_HasOpenings_inverse.size() == 0 )
{
return;
}
// collect aggregated objects
const std::vector<weak_ptr<IfcRelAggregates> >& vec_decomposed_by = ifc_element->m_IsDecomposedBy_inverse;
for( auto& decomposed_by : vec_decomposed_by )
{
if( decomposed_by.expired() )
{
continue;
}
shared_ptr<IfcRelAggregates> decomposed_by_aggregates(decomposed_by);
std::vector<shared_ptr<IfcObjectDefinition> >& vec_related_objects = decomposed_by_aggregates->m_RelatedObjects;
for( auto& related_object : vec_related_objects )
{
if( !related_object )
{
continue;
}
if( related_object->m_entity_id >= 0 )
{
auto it_find_related_shape = m_product_shape_data.find(related_object->m_entity_id);
if( it_find_related_shape != m_product_shape_data.end() )
{
shared_ptr<ProductShapeData>& related_product_shape = it_find_related_shape->second;
m_representation_converter->subtractOpenings(ifc_element, related_product_shape);
}
}
}
}
}
virtual void messageTarget( void* ptr, shared_ptr<StatusCallback::Message> m )
{
GeometryConverter* myself = (GeometryConverter*)ptr;
if( myself )
{
if( m->m_entity )
{
#ifdef ENABLE_OPENMP
ScopedLock lock( myself->m_writelock_messages );
#endif
// make sure that the same message for one entity does not appear several times
const int entity_id = m->m_entity->m_entity_id;
auto it = myself->m_messages.find( entity_id );
if( it != myself->m_messages.end() )
{
std::vector<shared_ptr<StatusCallback::Message> >& vec_message_for_entity = it->second;
for( size_t i = 0; i < vec_message_for_entity.size(); ++i )
{
shared_ptr<StatusCallback::Message>& existing_message = vec_message_for_entity[i];
if( existing_message->m_message_text.compare( m->m_message_text ) == 0 )
{
// same message for same entity is already there, so ignore message
return;
}
}
vec_message_for_entity.push_back( m );
}
else
{
std::vector<shared_ptr<StatusCallback::Message> >& vec = myself->m_messages.insert( std::make_pair( entity_id, std::vector<shared_ptr<StatusCallback::Message> >() ) ).first->second;
vec.push_back( m );
}
}
myself->messageCallback( m );
}
}
};
|
pr88203-2.c | /* PR c++/88203 */
/* { dg-do compile } */
/* { dg-additional-options "-std=gnu99" { target c } } */
/* { dg-additional-options "-std=gnu++11" { target c++ } } */
void foo (const char *, const char *);
#pragma omp declare target to (foo)
void
f1 (void)
{
#pragma omp parallel default(none)
foo (__FUNCTION__, __PRETTY_FUNCTION__);
}
void
f2 (void)
{
#pragma omp parallel default(none) shared(__FUNCTION__, __PRETTY_FUNCTION__)
foo (__FUNCTION__, __PRETTY_FUNCTION__);
#pragma omp parallel default(none) shared(__FUNCTION__) firstprivate(__PRETTY_FUNCTION__)
foo (__FUNCTION__, __PRETTY_FUNCTION__);
}
void
f3 (void)
{
#pragma omp parallel default(none) firstprivate(__FUNCTION__, __PRETTY_FUNCTION__)
foo (__FUNCTION__, __PRETTY_FUNCTION__);
#pragma omp parallel default(none) firstprivate(__FUNCTION__), shared(__PRETTY_FUNCTION__)
foo (__FUNCTION__, __PRETTY_FUNCTION__);
}
void
f4 (void)
{
foo (__FUNCTION__, __PRETTY_FUNCTION__);
#pragma omp parallel default(none)
foo (__FUNCTION__, __PRETTY_FUNCTION__);
}
void
f5 (void)
{
foo (__FUNCTION__, __PRETTY_FUNCTION__);
#pragma omp parallel default(none) shared(__FUNCTION__, __PRETTY_FUNCTION__)
foo (__FUNCTION__, __PRETTY_FUNCTION__);
}
void
f6 (void)
{
foo (__FUNCTION__, __PRETTY_FUNCTION__);
#pragma omp parallel default(none) firstprivate(__FUNCTION__, __PRETTY_FUNCTION__)
foo (__FUNCTION__, __PRETTY_FUNCTION__);
}
void
f7 (void)
{
#pragma omp target map(to: __FUNCTION__, __PRETTY_FUNCTION__)
foo (__FUNCTION__, __PRETTY_FUNCTION__);
#pragma omp task depend(inout:__FUNCTION__, __PRETTY_FUNCTION__)
foo (__FUNCTION__, __PRETTY_FUNCTION__);
}
|
GB_matvec_type.c | //------------------------------------------------------------------------------
// GB_matvec_type: return the type of a matrix
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
#include "GB.h"
GrB_Info GB_matvec_type // get the type of a matrix
(
GrB_Type *type, // returns the type of the matrix
const GrB_Matrix A, // matrix to query
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GB_RETURN_IF_NULL (type) ;
ASSERT_MATRIX_OK (A, "A for type", GB0) ;
//--------------------------------------------------------------------------
// return the type
//--------------------------------------------------------------------------
(*type) = A->type ;
#pragma omp flush
return (GrB_SUCCESS) ;
}
|
perturbations.c | /** @file perturbations.c Documented perturbation module
*
* Julien Lesgourgues, 23.09.2010
*
* Deals with the perturbation evolution.
* This module has two purposes:
*
* - at the beginning; to initialize the perturbations, i.e. to
* integrate the perturbation equations, and store temporarily the terms
* contributing to the source functions as a function of conformal
* time. Then, to perform a few manipulations of these terms in order to
* infer the actual source functions \f$ S^{X} (k, \tau) \f$, and to
* store them as a function of conformal time inside an interpolation
* table.
*
* - at any time in the code; to evaluate the source functions at a
* given conformal time (by interpolating within the interpolation
* table).
*
* Hence the following functions can be called from other modules:
*
* -# perturb_init() at the beginning (but after background_init() and thermodynamics_init())
* -# perturb_sources_at_tau() at any later time
* -# perturb_free() at the end, when no more calls to perturb_sources_at_tau() are needed
*/
#include "perturbations.h"
/**
* Source function \f$ S^{X} (k, \tau) \f$ at a given conformal time tau.
*
* Evaluate source functions at given conformal time tau by reading
* the pre-computed table and interpolating.
*
* @param ppt Input: pointer to perturbation structure containing interpolation tables
* @param index_md Input: index of requested mode
* @param index_ic Input: index of requested initial condition
* @param index_type Input: index of requested source function type
* @param tau Input: any value of conformal time
* @param psource Output: vector (already allocated) of source function as a function of k
* @return the error status
*/
int perturb_sources_at_tau(
struct perturbs * ppt,
int index_md,
int index_ic,
int index_type,
double tau,
double * psource
) {
/** Summary: */
/** - interpolate in pre-computed table contained in ppt */
class_call(array_interpolate_two_bis(ppt->tau_sampling,
1,
0,
ppt->sources[index_md][index_ic*ppt->tp_size[index_md]+index_type],
ppt->k_size[index_md],
ppt->tau_size,
tau,
psource,
ppt->k_size[index_md],
ppt->error_message),
ppt->error_message,
ppt->error_message);
return _SUCCESS_;
}
/**
* Initialize the perturbs structure, and in particular the table of source functions.
*
* Main steps:
*
* - given the values of the flags describing which kind of
* perturbations should be considered (modes: scalar/vector/tensor,
* initial conditions, type of source functions needed...),
* initialize indices and wavenumber list
*
* - define the time sampling for the output source functions
*
* - for each mode (scalar/vector/tensor): initialize the indices of
* relevant perturbations, integrate the differential system,
* compute and store the source functions.
*
* @param ppr Input: pointer to precision structure
* @param pba Input: pointer to background structure
* @param pth Input: pointer to thermodynamics structure
* @param ppt Output: Initialized perturbation structure
* @return the error status
*/
int perturb_init(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt
) {
/** Summary: */
/** - define local variables */
/* running index for modes */
int index_md;
/* running index for initial conditions */
int index_ic;
/* running index for wavenumbers */
int index_k;
/* pointer to one struct perturb_workspace per thread (one if no openmp) */
struct perturb_workspace ** pppw;
/* number of threads (always one if no openmp) */
int number_of_threads=1;
/* index of the thread (always 0 if no openmp) */
int thread=0;
/* This code can be optionally compiled with the openmp option for parallel computation.
Inside parallel regions, the use of the command "return" is forbidden.
For error management, instead of "return _FAILURE_", we will set the variable below
to "abort = _TRUE_". This will lead to a "return _FAILURE_" just after leaving the
parallel region. */
int abort;
/* unsigned integer that will be set to the size of the workspace */
size_t sz;
#ifdef _OPENMP
/* instrumentation times */
double tstart, tstop, tspent;
#endif
/** - perform preliminary checks */
if (ppt->has_perturbations == _FALSE_) {
if (ppt->perturbations_verbose > 0)
printf("No sources requested. Perturbation module skipped.\n");
return _SUCCESS_;
}
else {
if (ppt->perturbations_verbose > 0)
printf("Computing sources\n");
}
class_test((ppt->gauge == synchronous) && (pba->has_cdm == _FALSE_),
ppt->error_message,
"In the synchronous gauge, it is not self-consistent to assume no CDM: the later is used to define the initial timelike hypersurface. You can either add a negligible amount of CDM or switch to newtonian gauge");
class_test ((ppr->tight_coupling_approximation < first_order_MB) ||
(ppr->tight_coupling_approximation > compromise_CLASS),
ppt->error_message,
"your tight_coupling_approximation is set to %d, out of range defined in perturbations.h",ppr->tight_coupling_approximation);
class_test ((ppr->radiation_streaming_approximation < rsa_null) ||
(ppr->radiation_streaming_approximation > rsa_none),
ppt->error_message,
"your radiation_streaming_approximation is set to %d, out of range defined in perturbations.h",ppr->radiation_streaming_approximation);
if (pba->has_ur == _TRUE_) {
class_test ((ppr->ur_fluid_approximation < ufa_mb) ||
(ppr->ur_fluid_approximation > ufa_none),
ppt->error_message,
"your ur_fluid_approximation is set to %d, out of range defined in perturbations.h",ppr->ur_fluid_approximation);
}
if (pba->has_ncdm == _TRUE_) {
class_test ((ppr->ncdm_fluid_approximation < ncdmfa_mb) ||
(ppr->ncdm_fluid_approximation > ncdmfa_none),
ppt->error_message,
"your ncdm_fluid_approximation is set to %d, out of range defined in perturbations.h",ppr->ncdm_fluid_approximation);
}
/* if (pba->has_fld == _TRUE_) {*/
if ( 0 ) { // commented out so that no dark energy perturbations are included
class_test(pba->w0_fld+pba->wa_fld >= 0.,
ppt->error_message,
"So far, the fluid is meant to be negligible at early time, and not to be important for defining the initial conditions of other species. You are using parameters for which this assumption may break down, so maybe it's the case to fully implement the fluid in the initial condition routine");
class_test((pba->w0_fld==-1.) && (pba->wa_fld==0.),
ppt->error_message,
"Your choice of a fluid with (w0,wa)=(-1,0) is not valid due to instabilities in the unphysical perturbations of such a fluid. Try instead with a plain cosmological constant");
class_test(((pba->w0_fld + pba->wa_fld +1.0)*(pba->w0_fld+1.0)) < 0.0,
ppt->error_message,
"w crosses -1 between the infinite past and today, and this would lead to divergent perturbation equations for the fluid.");
}
if (pba->has_dcdm == _TRUE_) {
class_test((ppt->has_cdi == _TRUE_) || (ppt->has_bi == _TRUE_) || (ppt->has_nid == _TRUE_) || (ppt->has_niv == _TRUE_),
ppt->error_message,
"Non-adiabatic initial conditions not coded in presence of decaying dark matter");
}
class_test(ppt->has_vectors == _TRUE_,
ppt->error_message,
"Vectors not coded yet");
if ((ppt->has_niv == _TRUE_) && (ppt->perturbations_verbose > 0)) {
printf("Warning: the niv initial conditions in CLASS (and also in CAMB) should still be double-checked: if you want to do it and send feedback, you are welcome!\n");
}
if (ppt->has_tensors == _TRUE_) {
ppt->evolve_tensor_ur = _FALSE_;
ppt->evolve_tensor_ncdm = _FALSE_;
switch (ppt->tensor_method) {
case (tm_photons_only):
break;
case (tm_massless_approximation):
if ((pba->has_ur == _TRUE_) || (pba->has_ncdm == _TRUE_))
ppt->evolve_tensor_ur = _TRUE_;
break;
case (tm_exact):
if (pba->has_ur == _TRUE_)
ppt->evolve_tensor_ur = _TRUE_;
if (pba->has_ncdm == _TRUE_)
ppt->evolve_tensor_ncdm = _TRUE_;
break;
}
}
/** - initialize all indices and lists in perturbs structure using perturb_indices_of_perturbs() */
class_call(perturb_indices_of_perturbs(ppr,
pba,
pth,
ppt),
ppt->error_message,
ppt->error_message);
if (ppt->z_max_pk > pth->z_rec) {
class_test(ppt->has_cmb == _TRUE_,
ppt->error_message,
"You requested a very high z_pk=%e, higher than z_rec=%e. This works very well when you don't ask for a calculation of the CMB source function(s). Remove any CMB from your output and try e.g. with 'output=mTk' or 'output=mTk,vTk'",
ppt->z_max_pk,
pth->z_rec);
class_test(ppt->has_source_delta_m == _TRUE_,
ppt->error_message,
"You requested a very high z_pk=%e, higher than z_rec=%e. This works very well when you ask only transfer functions, e.g. with 'output=mTk' or 'output=mTk,vTk'. But if you need the total matter (e.g. with 'mPk', 'dCl', etc.) there is an issue with the calculation of delta_m at very early times. By default, delta_m is a gauge-invariant variable (the density fluctuation in comoving gauge) and this quantity is hard to get accurately at very early times. The solution is to define delta_m as the density fluctuation in the current gauge, synchronous or newtonian. For the moment this must be done manually by commenting the line 'ppw->delta_m += 3. *ppw->pvecback[pba->index_bg_a]*ppw->pvecback[pba->index_bg_H] * ppw->theta_m/k2;' in perturb_sources(). In the future there will be an option for doing it in an easier way.",
ppt->z_max_pk,
pth->z_rec);
}
/** - define the common time sampling for all sources using
perturb_timesampling_for_sources() */
class_call(perturb_timesampling_for_sources(ppr,
pba,
pth,
ppt),
ppt->error_message,
ppt->error_message);
/** - if we want to store perturbations, write titles and allocate storage */
class_call(perturb_prepare_output(pba,ppt),
ppt->error_message,
ppt->error_message);
/** - create an array of workspaces in multi-thread case */
#ifdef _OPENMP
#pragma omp parallel
{
number_of_threads = omp_get_num_threads();
}
#endif
class_alloc(pppw,number_of_threads * sizeof(struct perturb_workspace *),ppt->error_message);
/** - loop over modes (scalar, tensors, etc). For each mode: */
for (index_md = 0; index_md < ppt->md_size; index_md++) {
if (ppt->perturbations_verbose > 1)
printf("Evolving mode %d/%d\n",index_md+1,ppt->md_size);
abort = _FALSE_;
sz = sizeof(struct perturb_workspace);
#pragma omp parallel \
shared(pppw,ppr,pba,pth,ppt,index_md,abort,number_of_threads) \
private(thread) \
num_threads(number_of_threads)
{
#ifdef _OPENMP
thread=omp_get_thread_num();
#endif
/** - --> (a) create a workspace (one per thread in multi-thread case) */
class_alloc_parallel(pppw[thread],sz,ppt->error_message);
/** - --> (b) initialize indices of vectors of perturbations with perturb_indices_of_current_vectors() */
class_call_parallel(perturb_workspace_init(ppr,
pba,
pth,
ppt,
index_md,
pppw[thread]),
ppt->error_message,
ppt->error_message);
} /* end of parallel region */
if (abort == _TRUE_) return _FAILURE_;
/** - --> (c) loop over initial conditions and wavenumbers; for each of them, evolve perturbations and compute source functions with perturb_solve() */
for (index_ic = 0; index_ic < ppt->ic_size[index_md]; index_ic++) {
if (ppt->perturbations_verbose > 1)
printf("Evolving ic %d/%d\n",index_ic+1,ppt->ic_size[index_md]);
if (ppt->perturbations_verbose > 1)
printf("evolving %d wavenumbers\n",ppt->k_size[index_md]);
abort = _FALSE_;
#pragma omp parallel \
shared(pppw,ppr,pba,pth,ppt,index_md,index_ic,abort,number_of_threads) \
private(index_k,thread,tstart,tstop,tspent) \
num_threads(number_of_threads)
{
#ifdef _OPENMP
thread=omp_get_thread_num();
tspent=0.;
#endif
#pragma omp for schedule (dynamic)
/* integrating backwards is slightly more optimal for parallel runs */
//for (index_k = 0; index_k < ppt->k_size; index_k++) {
for (index_k = ppt->k_size[index_md]-1; index_k >=0; index_k--) {
if ((ppt->perturbations_verbose > 2) && (abort == _FALSE_)) {
printf("evolving mode k=%e /Mpc (%d/%d)",ppt->k[index_md][index_k],index_k+1,ppt->k_size[index_md]);
if (pba->sgnK != 0)
printf(" (for scalar modes, corresponds to nu=%e)",sqrt(ppt->k[index_md][index_k]*ppt->k[index_md][index_k]+pba->K)/sqrt(pba->sgnK*pba->K));
printf("\n");
}
#ifdef _OPENMP
tstart = omp_get_wtime();
#endif
class_call_parallel(perturb_solve(ppr,
pba,
pth,
ppt,
index_md,
index_ic,
index_k,
pppw[thread]),
ppt->error_message,
ppt->error_message);
#ifdef _OPENMP
tstop = omp_get_wtime();
tspent += tstop-tstart;
#endif
#pragma omp flush(abort)
} /* end of loop over wavenumbers */
#ifdef _OPENMP
if (ppt->perturbations_verbose>1)
printf("In %s: time spent in parallel region (loop over k's) = %e s for thread %d\n",
__func__,tspent,omp_get_thread_num());
#endif
} /* end of parallel region */
if (abort == _TRUE_) return _FAILURE_;
} /* end of loop over initial conditions */
abort = _FALSE_;
#pragma omp parallel \
shared(pppw,ppt,index_md,abort,number_of_threads) \
private(thread) \
num_threads(number_of_threads)
{
#ifdef _OPENMP
thread=omp_get_thread_num();
#endif
class_call_parallel(perturb_workspace_free(ppt,index_md,pppw[thread]),
ppt->error_message,
ppt->error_message);
} /* end of parallel region */
if (abort == _TRUE_) return _FAILURE_;
} /* end loop over modes */
free(pppw);
return _SUCCESS_;
}
/**
* Free all memory space allocated by perturb_init().
*
* To be called at the end of each run, only when no further calls to
* perturb_sources_at_tau() are needed.
*
* @param ppt Input: perturbation structure to be freed
* @return the error status
*/
int perturb_free(
struct perturbs * ppt
) {
int index_md,index_ic,index_type;
int filenum;
if (ppt->has_perturbations == _TRUE_) {
for (index_md = 0; index_md < ppt->md_size; index_md++) {
for (index_ic = 0; index_ic < ppt->ic_size[index_md]; index_ic++) {
for (index_type = 0; index_type < ppt->tp_size[index_md]; index_type++) {
free(ppt->sources[index_md][index_ic*ppt->tp_size[index_md]+index_type]);
}
}
free(ppt->sources[index_md]);
free(ppt->k[index_md]);
}
free(ppt->tau_sampling);
free(ppt->tp_size);
free(ppt->ic_size);
free(ppt->k);
free(ppt->k_size_cmb);
free(ppt->k_size_cl);
free(ppt->k_size);
free(ppt->sources);
/** Stuff related to perturbations output: */
/** - Free non-NULL pointers */
if (ppt->index_k_output_values != NULL)
free(ppt->index_k_output_values);
for (filenum = 0; filenum<_MAX_NUMBER_OF_K_FILES_; filenum++) {
if (ppt->scalar_perturbations_data[filenum] != NULL)
free(ppt->scalar_perturbations_data[filenum]);
if (ppt->vector_perturbations_data[filenum] != NULL)
free(ppt->vector_perturbations_data[filenum]);
if (ppt->tensor_perturbations_data[filenum] != NULL)
free(ppt->tensor_perturbations_data[filenum]);
}
}
return _SUCCESS_;
}
/**
* Initialize all indices and allocate most arrays in perturbs structure.
*
* @param ppr Input: pointer to precision structure
* @param pba Input: pointer to background structure
* @param pth Input: pointer to thermodynamics structure
* @param ppt Input/Output: Initialized perturbation structure
* @return the error status
*/
int perturb_indices_of_perturbs(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt
) {
/** Summary: */
/** - define local variables */
int index_type;
int index_md;
int index_ic;
int index_type_common;
/** - count modes (scalar, vector, tensor) and assign corresponding indices */
index_md = 0;
class_define_index(ppt->index_md_scalars,ppt->has_scalars,index_md,1);
class_define_index(ppt->index_md_vectors,ppt->has_vectors,index_md,1);
class_define_index(ppt->index_md_tensors,ppt->has_tensors,index_md,1);
ppt->md_size = index_md;
class_test(index_md == 0,
ppt->error_message,
"you should have at least one out of {scalars, vectors, tensors} !!!");
/** - allocate array of number of types for each mode, ppt->tp_size[index_md] */
class_alloc(ppt->tp_size,ppt->md_size*sizeof(int),ppt->error_message);
/** - allocate array of number of initial conditions for each mode, ppt->ic_size[index_md] */
class_alloc(ppt->ic_size,ppt->md_size*sizeof(int),ppt->error_message);
/** - allocate array of arrays of source functions for each mode, ppt->source[index_md] */
class_alloc(ppt->sources,ppt->md_size * sizeof(double *),ppt->error_message);
/** - initialization of all flags to false (will eventually be set to true later) */
ppt->has_cmb = _FALSE_;
ppt->has_lss = _FALSE_;
ppt->has_source_t = _FALSE_;
ppt->has_source_p = _FALSE_;
ppt->has_source_delta_m = _FALSE_;
ppt->has_source_delta_g = _FALSE_;
ppt->has_source_delta_b = _FALSE_;
ppt->has_source_delta_cdm = _FALSE_;
ppt->has_source_delta_dcdm = _FALSE_;
ppt->has_source_delta_fld = _FALSE_;
ppt->has_source_delta_scf = _FALSE_;
ppt->has_source_delta_dr = _FALSE_;
ppt->has_source_delta_ur = _FALSE_;
ppt->has_source_delta_ncdm = _FALSE_;
ppt->has_source_theta_m = _FALSE_;
ppt->has_source_theta_g = _FALSE_;
ppt->has_source_theta_b = _FALSE_;
ppt->has_source_theta_cdm = _FALSE_;
ppt->has_source_theta_dcdm = _FALSE_;
ppt->has_source_theta_fld = _FALSE_;
ppt->has_source_theta_scf = _FALSE_;
ppt->has_source_theta_dr = _FALSE_;
ppt->has_source_theta_ur = _FALSE_;
ppt->has_source_theta_ncdm = _FALSE_;
ppt->has_source_phi = _FALSE_;
ppt->has_source_phi_prime = _FALSE_;
ppt->has_source_phi_plus_psi = _FALSE_;
ppt->has_source_psi = _FALSE_;
/** - source flags and indices, for sources that all modes have in
common (temperature, polarization, ...). For temperature, the
term t2 is always non-zero, while other terms are non-zero only
for scalars and vectors. For polarization, the term e is always
non-zero, while the term b is only for vectors and tensors. */
if (ppt->has_cl_cmb_temperature == _TRUE_) {
ppt->has_source_t = _TRUE_;
ppt->has_cmb = _TRUE_;
}
if (ppt->has_cl_cmb_polarization == _TRUE_) {
ppt->has_source_p = _TRUE_;
ppt->has_cmb = _TRUE_;
}
index_type = 0;
class_define_index(ppt->index_tp_t2,ppt->has_source_t,index_type,1);
class_define_index(ppt->index_tp_p,ppt->has_source_p,index_type,1);
index_type_common = index_type;
/* indices for perturbed recombination */
class_define_index(ppt->index_tp_perturbed_recombination_delta_temp,ppt->has_perturbed_recombination,index_type,1);
class_define_index(ppt->index_tp_perturbed_recombination_delta_chi,ppt->has_perturbed_recombination,index_type,1);
/** - define k values with perturb_get_k_list() */
class_call(perturb_get_k_list(ppr,
pba,
pth,
ppt),
ppt->error_message,
ppt->error_message);
/** - loop over modes. Initialize flags and indices which are specific to each mode. */
for (index_md = 0; index_md < ppt->md_size; index_md++) {
/** - (a) scalars */
if (_scalars_) {
/** - --> source flags and indices, for sources that are specific to scalars */
if ((ppt->has_cl_cmb_lensing_potential == _TRUE_) || (ppt->has_cl_lensing_potential)) {
ppt->has_lss = _TRUE_;
ppt->has_source_phi_plus_psi = _TRUE_;
}
if ((ppt->has_pk_matter == _TRUE_) || (ppt->has_nl_corrections_based_on_delta_m)) {
ppt->has_lss = _TRUE_;
ppt->has_source_delta_m = _TRUE_;
}
if (ppt->has_density_transfers == _TRUE_) {
ppt->has_lss = _TRUE_;
ppt->has_source_delta_g = _TRUE_;
ppt->has_source_delta_b = _TRUE_;
if (pba->has_cdm == _TRUE_)
ppt->has_source_delta_cdm = _TRUE_;
if (pba->has_dcdm == _TRUE_)
ppt->has_source_delta_dcdm = _TRUE_;
/* if (pba->has_fld == _TRUE_)*/
/* ppt->has_source_delta_fld = _TRUE_;*/
if (pba->has_scf == _TRUE_)
ppt->has_source_delta_scf = _TRUE_;
if (pba->has_ur == _TRUE_)
ppt->has_source_delta_ur = _TRUE_;
if (pba->has_dr == _TRUE_)
ppt->has_source_delta_dr = _TRUE_;
if (pba->has_ncdm == _TRUE_)
ppt->has_source_delta_ncdm = _TRUE_;
// Thanks to the following lines, (phi,psi) are also stored as sources
// (Obtained directly in newtonian gauge, infereed from (h,eta) in synchronous gauge).
// If density transfer functions are requested in the (default) CLASS format,
// (phi, psi) will be appended to the delta_i's in the final output.
ppt->has_source_phi = _TRUE_;
ppt->has_source_psi = _TRUE_;
}
if (ppt->has_velocity_transfers == _TRUE_) {
ppt->has_lss = _TRUE_;
ppt->has_source_theta_g = _TRUE_;
ppt->has_source_theta_b = _TRUE_;
if ((pba->has_cdm == _TRUE_) && (ppt->gauge != synchronous))
ppt->has_source_theta_cdm = _TRUE_;
if (pba->has_dcdm == _TRUE_)
ppt->has_source_theta_dcdm = _TRUE_;
/* if (pba->has_fld == _TRUE_)*/
/* ppt->has_source_theta_fld = _TRUE_;*/
if (pba->has_scf == _TRUE_)
ppt->has_source_theta_scf = _TRUE_;
if (pba->has_ur == _TRUE_)
ppt->has_source_theta_ur = _TRUE_;
if (pba->has_dr == _TRUE_)
ppt->has_source_theta_dr = _TRUE_;
if (pba->has_ncdm == _TRUE_)
ppt->has_source_theta_ncdm = _TRUE_;
}
if (ppt->has_cl_number_count == _TRUE_) {
ppt->has_lss = _TRUE_;
if (ppt->has_nc_density == _TRUE_) {
ppt->has_source_delta_m = _TRUE_;
}
if (ppt->has_nc_rsd == _TRUE_) {
ppt->has_source_theta_m = _TRUE_;
}
if (ppt->has_nc_lens == _TRUE_) {
ppt->has_source_phi_plus_psi = _TRUE_;
}
if (ppt->has_nc_gr == _TRUE_) {
ppt->has_source_phi = _TRUE_;
ppt->has_source_psi = _TRUE_;
ppt->has_source_phi_prime = _TRUE_;
ppt->has_source_phi_plus_psi = _TRUE_;
}
}
index_type = index_type_common;
class_define_index(ppt->index_tp_t0, ppt->has_source_t, index_type,1);
class_define_index(ppt->index_tp_t1, ppt->has_source_t, index_type,1);
class_define_index(ppt->index_tp_delta_m, ppt->has_source_delta_m, index_type,1);
class_define_index(ppt->index_tp_delta_g, ppt->has_source_delta_g, index_type,1);
class_define_index(ppt->index_tp_delta_b, ppt->has_source_delta_b, index_type,1);
class_define_index(ppt->index_tp_delta_cdm, ppt->has_source_delta_cdm, index_type,1);
class_define_index(ppt->index_tp_delta_dcdm, ppt->has_source_delta_dcdm,index_type,1);
class_define_index(ppt->index_tp_delta_fld, ppt->has_source_delta_fld, index_type,1);
class_define_index(ppt->index_tp_delta_scf, ppt->has_source_delta_scf, index_type,1);
class_define_index(ppt->index_tp_delta_dr, ppt->has_source_delta_dr, index_type,1);
class_define_index(ppt->index_tp_delta_ur, ppt->has_source_delta_ur, index_type,1);
class_define_index(ppt->index_tp_delta_ncdm1,ppt->has_source_delta_ncdm,index_type,pba->N_ncdm);
class_define_index(ppt->index_tp_theta_m, ppt->has_source_theta_m, index_type,1);
class_define_index(ppt->index_tp_theta_g, ppt->has_source_theta_g, index_type,1);
class_define_index(ppt->index_tp_theta_b, ppt->has_source_theta_b, index_type,1);
class_define_index(ppt->index_tp_theta_cdm, ppt->has_source_theta_cdm, index_type,1);
class_define_index(ppt->index_tp_theta_dcdm, ppt->has_source_theta_dcdm,index_type,1);
class_define_index(ppt->index_tp_theta_fld, ppt->has_source_theta_fld, index_type,1);
class_define_index(ppt->index_tp_theta_scf, ppt->has_source_theta_scf, index_type,1);
class_define_index(ppt->index_tp_theta_dr, ppt->has_source_theta_dr, index_type,1);
class_define_index(ppt->index_tp_theta_ur, ppt->has_source_theta_ur, index_type,1);
class_define_index(ppt->index_tp_theta_ncdm1,ppt->has_source_theta_ncdm,index_type,pba->N_ncdm);
class_define_index(ppt->index_tp_phi, ppt->has_source_phi, index_type,1);
class_define_index(ppt->index_tp_phi_prime, ppt->has_source_phi_prime, index_type,1);
class_define_index(ppt->index_tp_phi_plus_psi,ppt->has_source_phi_plus_psi,index_type,1);
class_define_index(ppt->index_tp_psi, ppt->has_source_psi, index_type,1);
ppt->tp_size[index_md] = index_type;
class_test(index_type == 0,
ppt->error_message,
"inconsistent input: you asked for scalars, so you should have at least one non-zero scalar source type (temperature, polarization, lensing/gravitational potential, ...). Please adjust your input.");
/** - --> count scalar initial conditions (for scalars: ad, cdi, nid, niv; for tensors: only one) and assign corresponding indices */
index_ic = 0;
class_define_index(ppt->index_ic_ad, ppt->has_ad, index_ic,1);
class_define_index(ppt->index_ic_bi, ppt->has_bi, index_ic,1);
class_define_index(ppt->index_ic_cdi,ppt->has_cdi,index_ic,1);
class_define_index(ppt->index_ic_nid,ppt->has_nid,index_ic,1);
class_define_index(ppt->index_ic_niv,ppt->has_niv,index_ic,1);
ppt->ic_size[index_md] = index_ic;
class_test(index_ic == 0,
ppt->error_message,
"you should have at least one adiabatic or isocurvature initial condition...} !!!");
}
/** - (b) vectors */
if (_vectors_) {
/** - --> source flags and indices, for sources that are specific to vectors */
index_type = index_type_common;
class_define_index(ppt->index_tp_t1,ppt->has_source_t,index_type,1);
ppt->tp_size[index_md] = index_type;
/*
class_test(index_type == 0,
ppt->error_message,
"inconsistent input: you asked for vectors, so you should have at least one non-zero vector source type (temperature or polarization). Please adjust your input.");
*/
/** - --> initial conditions for vectors*/
index_ic = 0;
/* not coded yet */
ppt->ic_size[index_md] = index_ic;
}
/** - (c) tensors */
if (_tensors_) {
/** - --> source flags and indices, for sources that are specific to tensors */
index_type = index_type_common;
/* nothing specific, unlike for vectors and scalars! */
ppt->tp_size[index_md] = index_type;
/*
class_test(index_type == 0,
ppt->error_message,
"inconsistent input: you asked for tensors, so you should have at least one non-zero tensor source type (temperature or polarization). Please adjust your input.");
*/
/** - --> only one initial condition for tensors*/
index_ic = 0;
class_define_index(ppt->index_ic_ten,_TRUE_,index_ic,1);
ppt->ic_size[index_md] = index_ic;
}
/** - (d) for each mode, allocate array of arrays of source functions for each initial conditions and wavenumber, (ppt->source[index_md])[index_ic][index_type] */
class_alloc(ppt->sources[index_md],
ppt->ic_size[index_md] * ppt->tp_size[index_md] * sizeof(double *),
ppt->error_message);
}
return _SUCCESS_;
}
/**
* Define time sampling for source functions.
*
* For each type, compute the list of values of tau at which sources
* will be sampled. Knowing the number of tau values, allocate all
* arrays of source functions.
*
* @param ppr Input: pointer to precision structure
* @param pba Input: pointer to background structure
* @param pth Input: pointer to thermodynamics structure
* @param ppt Input/Output: Initialized perturbation structure
* @return the error status
*/
int perturb_timesampling_for_sources(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt
) {
/** Summary: */
/** - define local variables */
int counter;
int index_md;
int index_type;
int index_ic;
int last_index_back;
int last_index_thermo;
int first_index_back;
int first_index_thermo;
double tau;
double tau_ini;
double tau_lower;
double tau_upper;
double tau_mid;
double timescale_source;
double rate_thermo;
double rate_isw_squared;
double a_prime_over_a;
double a_primeprime_over_a;
double * pvecback;
double * pvecthermo;
/** - allocate background/thermodynamics vectors */
class_alloc(pvecback,pba->bg_size_short*sizeof(double),ppt->error_message);
class_alloc(pvecthermo,pth->th_size*sizeof(double),ppt->error_message);
/** - first, just count the number of sampling points in order to allocate the array containing all values */
/** - (a) if CMB requested, first sampling point = when the universe
stops being opaque; otherwise, start sampling gravitational
potential at recombination [however, if perturbed recombination
is requested, we also need to start the system before
recombination. Otherwise, the initial conditions for gas
temperature and ionization fraction perturbations (delta_T = 1/3
delta_b, delta_x_e) are not valid]. */
if ((ppt->has_cmb == _TRUE_)||(ppt->has_perturbed_recombination == _TRUE_)) {
/* using bisection, search time tau such that the ratio of thermo
to Hubble time scales tau_c/tau_h=aH/kappa' is equal to
start_sources_at_tau_c_over_tau_h */
tau_lower = pth->tau_ini;
class_call(background_at_tau(pba,
tau_lower,
pba->short_info,
pba->inter_normal,
&first_index_back,
pvecback),
pba->error_message,
ppt->error_message);
class_call(thermodynamics_at_z(pba,
pth,
1./pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
pth->inter_normal,
&first_index_thermo,
pvecback,
pvecthermo),
pth->error_message,
ppt->error_message);
class_test(pvecback[pba->index_bg_a]*
pvecback[pba->index_bg_H]/
pvecthermo[pth->index_th_dkappa] >
ppr->start_sources_at_tau_c_over_tau_h,
ppt->error_message,
"your choice of initial time for computing sources is inappropriate: it corresponds to an earlier time than the one at which the integration of thermodynamical variables started (tau=%g). You should increase either 'start_sources_at_tau_c_over_tau_h' or 'recfast_z_initial'\n",
tau_lower);
tau_upper = pth->tau_rec;
class_call(background_at_tau(pba,
tau_upper,
pba->short_info,
pba->inter_normal,
&first_index_back,
pvecback),
pba->error_message,
ppt->error_message);
class_call(thermodynamics_at_z(pba,
pth,
1./pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
pth->inter_normal,
&first_index_thermo,
pvecback,
pvecthermo),
pth->error_message,
ppt->error_message);
class_test(pvecback[pba->index_bg_a]*
pvecback[pba->index_bg_H]/
pvecthermo[pth->index_th_dkappa] <
ppr->start_sources_at_tau_c_over_tau_h,
ppt->error_message,
"your choice of initial time for computing sources is inappropriate: it corresponds to a time after recombination. You should decrease 'start_sources_at_tau_c_over_tau_h'\n");
tau_mid = 0.5*(tau_lower + tau_upper);
while (tau_upper - tau_lower > ppr->tol_tau_approx) {
class_call(background_at_tau(pba,
tau_mid,
pba->short_info,
pba->inter_normal,
&first_index_back,
pvecback),
pba->error_message,
ppt->error_message);
class_call(thermodynamics_at_z(pba,
pth,
1./pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
pth->inter_normal,
&first_index_thermo,
pvecback,
pvecthermo),
pth->error_message,
ppt->error_message);
if (pvecback[pba->index_bg_a]*
pvecback[pba->index_bg_H]/
pvecthermo[pth->index_th_dkappa] >
ppr->start_sources_at_tau_c_over_tau_h)
tau_upper = tau_mid;
else
tau_lower = tau_mid;
tau_mid = 0.5*(tau_lower + tau_upper);
}
tau_ini = tau_mid;
}
else {
/* check the time corresponding to the highest redshift requested in output plus one */
class_call(background_tau_of_z(pba,
ppt->z_max_pk+1,
&tau_ini),
pba->error_message,
ppt->error_message);
/* obsolete: previous choice was to start always at recombination time */
/* tau_ini = pth->tau_rec; */
/* set values of first_index_back/thermo */
class_call(background_at_tau(pba,
tau_ini,
pba->short_info,
pba->inter_normal,
&first_index_back,
pvecback),
pba->error_message,
ppt->error_message);
class_call(thermodynamics_at_z(pba,
pth,
1./pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
pth->inter_normal,
&first_index_thermo,
pvecback,
pvecthermo),
pth->error_message,
ppt->error_message);
}
/** - (b) next sampling point = previous + ppr->perturb_sampling_stepsize * timescale_source, where:
- --> if CMB requested:
timescale_source1 = \f$ |g/\dot{g}| = |\dot{\kappa}-\ddot{\kappa}/\dot{\kappa}|^{-1} \f$;
timescale_source2 = \f$ |2\ddot{a}/a-(\dot{a}/a)^2|^{-1/2} \f$ (to sample correctly the late ISW effect; and
timescale_source=1/(1/timescale_source1+1/timescale_source2); repeat till today.
- --> if CMB not requested:
timescale_source = 1/aH; repeat till today.
*/
counter = 1;
last_index_back = first_index_back;
last_index_thermo = first_index_thermo;
tau = tau_ini;
while (tau < pba->conformal_age) {
class_call(background_at_tau(pba,
tau,
pba->short_info,
pba->inter_closeby,
&last_index_back,
pvecback),
pba->error_message,
ppt->error_message);
class_call(thermodynamics_at_z(pba,
pth,
1./pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
pth->inter_closeby,
&last_index_thermo,
pvecback,
pvecthermo),
pth->error_message,
ppt->error_message);
if (ppt->has_cmb == _TRUE_) {
/* variation rate of thermodynamics variables */
rate_thermo = pvecthermo[pth->index_th_rate];
/* variation rate of metric due to late ISW effect (important at late times) */
a_prime_over_a = pvecback[pba->index_bg_H] * pvecback[pba->index_bg_a];
a_primeprime_over_a = pvecback[pba->index_bg_H_prime] * pvecback[pba->index_bg_a]
+ 2. * a_prime_over_a * a_prime_over_a;
rate_isw_squared = fabs(2.*a_primeprime_over_a-a_prime_over_a*a_prime_over_a);
/* compute rate */
timescale_source = sqrt(rate_thermo*rate_thermo+rate_isw_squared);
}
else {
/* variation rate given by Hubble time */
a_prime_over_a = pvecback[pba->index_bg_H] * pvecback[pba->index_bg_a];
timescale_source = a_prime_over_a;
}
/* check it is non-zero */
class_test(timescale_source == 0.,
ppt->error_message,
"null evolution rate, integration is diverging");
/* compute inverse rate */
timescale_source = 1./timescale_source;
class_test(fabs(ppr->perturb_sampling_stepsize*timescale_source/tau) < ppr->smallest_allowed_variation,
ppt->error_message,
"integration step =%e < machine precision : leads either to numerical error or infinite loop",ppr->perturb_sampling_stepsize*timescale_source);
tau = tau + ppr->perturb_sampling_stepsize*timescale_source;
counter++;
}
/** - --> infer total number of time steps, ppt->tau_size */
ppt->tau_size = counter;
/** - --> allocate array of time steps, ppt->tau_sampling[index_tau] */
class_alloc(ppt->tau_sampling,ppt->tau_size * sizeof(double),ppt->error_message);
/** - --> repeat the same steps, now filling the array with each tau value: */
/** - --> (b.1.) first sampling point = when the universe stops being opaque */
counter = 0;
ppt->tau_sampling[counter]=tau_ini;
/** - --> (b.2.) next sampling point = previous + ppr->perturb_sampling_stepsize * timescale_source, where
timescale_source1 = \f$ |g/\dot{g}| = |\dot{\kappa}-\ddot{\kappa}/\dot{\kappa}|^{-1} \f$;
timescale_source2 = \f$ |2\ddot{a}/a-(\dot{a}/a)^2|^{-1/2} \f$ (to sample correctly the late ISW effect; and
timescale_source=1/(1/timescale_source1+1/timescale_source2); repeat till today.
If CMB not requested:
timescale_source = 1/aH; repeat till today. */
last_index_back = first_index_back;
last_index_thermo = first_index_thermo;
tau = tau_ini;
while (tau < pba->conformal_age) {
class_call(background_at_tau(pba,
tau,
pba->short_info,
pba->inter_closeby,
&last_index_back,
pvecback),
pba->error_message,
ppt->error_message);
class_call(thermodynamics_at_z(pba,
pth,
1./pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
pth->inter_closeby,
&last_index_thermo,
pvecback,
pvecthermo),
pth->error_message,
ppt->error_message);
if (ppt->has_cmb == _TRUE_) {
/* variation rate of thermodynamics variables */
rate_thermo = pvecthermo[pth->index_th_rate];
/* variation rate of metric due to late ISW effect (important at late times) */
a_prime_over_a = pvecback[pba->index_bg_H] * pvecback[pba->index_bg_a];
a_primeprime_over_a = pvecback[pba->index_bg_H_prime] * pvecback[pba->index_bg_a]
+ 2. * a_prime_over_a * a_prime_over_a;
rate_isw_squared = fabs(2.*a_primeprime_over_a-a_prime_over_a*a_prime_over_a);
/* compute rate */
timescale_source = sqrt(rate_thermo*rate_thermo+rate_isw_squared);
}
else {
a_prime_over_a = pvecback[pba->index_bg_H] * pvecback[pba->index_bg_a];
timescale_source = a_prime_over_a;
}
/* check it is non-zero */
class_test(timescale_source == 0.,
ppt->error_message,
"null evolution rate, integration is diverging");
/* compute inverse rate */
timescale_source = 1./timescale_source;
class_test(fabs(ppr->perturb_sampling_stepsize*timescale_source/tau) < ppr->smallest_allowed_variation,
ppt->error_message,
"integration step =%e < machine precision : leads either to numerical error or infinite loop",ppr->perturb_sampling_stepsize*timescale_source);
tau = tau + ppr->perturb_sampling_stepsize*timescale_source;
counter++;
ppt->tau_sampling[counter]=tau;
}
/** - last sampling point = exactly today */
ppt->tau_sampling[counter] = pba->conformal_age;
free(pvecback);
free(pvecthermo);
/** - loop over modes, initial conditions and types. For each of
them, allocate array of source functions. */
for (index_md = 0; index_md < ppt->md_size; index_md++) {
for (index_ic = 0; index_ic < ppt->ic_size[index_md]; index_ic++) {
for (index_type = 0; index_type < ppt->tp_size[index_md]; index_type++) {
class_alloc(ppt->sources[index_md][index_ic*ppt->tp_size[index_md]+index_type],
ppt->k_size[index_md] * ppt->tau_size * sizeof(double),
ppt->error_message);
}
}
}
return _SUCCESS_;
}
/**
* Define the number of comoving wavenumbers using the information
* passed in the precision structure.
*
* @param ppr Input: pointer to precision structure
* @param pba Input: pointer to background structure
* @param pth Input: pointer to thermodynamics structure
* @param ppt Input: pointer to perturbation structure
* @return the error status
*/
int perturb_get_k_list(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt
) {
int index_k, index_k_output, index_mode;
double k,k_min=0.,k_rec,step,tau1;
double * k_max_cmb;
double * k_max_cl;
double k_max=0.;
double scale2;
double *tmp_k_list;
int newk_size, index_newk, add_k_output_value;
/** Summary: */
class_test(ppr->k_step_transition == 0.,
ppt->error_message,
"stop to avoid division by zero");
class_test(pth->rs_rec == 0.,
ppt->error_message,
"stop to avoid division by zero");
/** - allocate arrays related to k list for each mode */
class_alloc(ppt->k_size_cmb,
ppt->md_size*sizeof(int),
ppt->error_message);
class_alloc(ppt->k_size_cl,
ppt->md_size*sizeof(int),
ppt->error_message);
class_alloc(ppt->k_size,
ppt->md_size*sizeof(int),
ppt->error_message);
class_alloc(ppt->k,
ppt->md_size*sizeof(double*),
ppt->error_message);
class_calloc(k_max_cmb,
ppt->md_size,
sizeof(double),
ppt->error_message);
class_calloc(k_max_cl,
ppt->md_size,
sizeof(double),
ppt->error_message);
/** - scalar modes */
if (ppt->has_scalars == _TRUE_) {
/* first value */
if (pba->sgnK == 0) {
/* K<0 (flat) : start close to zero */
k_min=ppr->k_min_tau0/pba->conformal_age;
}
else if (pba->sgnK == -1) {
/* K<0 (open) : start close to sqrt(-K)
(in transfer modules, for scalars, this will correspond to q close to zero;
for vectors and tensors, this value is even smaller than the minimum necessary value) */
k_min=sqrt(-pba->K+pow(ppr->k_min_tau0/pba->conformal_age/pth->angular_rescaling,2));
}
else if (pba->sgnK == 1) {
/* K>0 (closed): start from q=sqrt(k2+(1+m)K) equal to 3sqrt(K), i.e. k=sqrt((8-m)K) */
k_min = sqrt((8.-1.e-4)*pba->K);
}
/** - --> find k_max (as well as k_max_cmb[ppt->index_md_scalars], k_max_cl[ppt->index_md_scalars]) */
k_rec = 2. * _PI_ / pth->rs_rec; /* comoving scale corresponding to sound horizon at recombination */
k_max_cmb[ppt->index_md_scalars] = k_min;
k_max_cl[ppt->index_md_scalars] = k_min;
k_max = k_min;
if (ppt->has_cls == _TRUE_) {
/* find k_max_cmb[ppt->index_md_scalars] : */
/* choose a k_max_cmb[ppt->index_md_scalars] corresponding to a wavelength on the last
scattering surface seen today under an angle smaller than
pi/lmax: this is equivalent to
k_max_cl[ppt->index_md_scalars]*[comvoving.ang.diameter.distance] > l_max */
k_max_cmb[ppt->index_md_scalars] = ppr->k_max_tau0_over_l_max*ppt->l_scalar_max
/pba->conformal_age/pth->angular_rescaling;
k_max_cl[ppt->index_md_scalars] = k_max_cmb[ppt->index_md_scalars];
k_max = k_max_cmb[ppt->index_md_scalars];
/* find k_max_cl[ppt->index_md_scalars] : */
/* if we need density/lensing Cl's, we must impose a stronger condition,
such that the minimum wavelength on the shell corresponding
to the center of smallest redshift bin is seen under an
angle smaller than pi/lmax. So we must multiply our previous
k_max_cl[ppt->index_md_scalars] by the ratio tau0/(tau0-tau[center of smallest
redshift bin]). Note that we could do the same with the
lensing potential if we needed a very precise C_l^phi-phi at
large l. We don't do it by default, because the lensed ClT,
ClE would be marginally affected. */
if ((ppt->has_cl_number_count == _TRUE_) || (ppt->has_cl_lensing_potential == _TRUE_)) {
class_call(background_tau_of_z(pba,
ppt->selection_mean[0],
&tau1),
pba->error_message,
ppt->error_message);
k_max_cl[ppt->index_md_scalars] = MAX(k_max_cl[ppt->index_md_scalars],ppr->k_max_tau0_over_l_max*ppt->l_lss_max/(pba->conformal_age-tau1)); // to be very accurate we should use angular diameter distance to given redshift instead of comoving radius: would implement corrections depending on curvature
k_max = k_max_cl[ppt->index_md_scalars];
}
}
/* find k_max: */
if ((ppt->has_pk_matter == _TRUE_) || (ppt->has_density_transfers == _TRUE_) || (ppt->has_velocity_transfers == _TRUE_))
k_max = MAX(k_max,ppt->k_max_for_pk);
if (ppt->has_nl_corrections_based_on_delta_m == _TRUE_)
k_max = MAX(k_max,ppr->halofit_min_k_max);
/** - --> test that result for k_min, k_max make sense */
class_test(k_min<0.,
ppt->error_message,
"buggy definition of k_min");
class_test(k_max<0.,
ppt->error_message,
"buggy definition of k_max");
class_test(k_max<k_min,
ppt->error_message,
"buggy definition of k_min and/or k_max");
/* if K>0, the transfer function will be calculated for discrete
integer values of nu=3,4,5,... where nu=sqrt(k2+(1+m)K) and
m=0,1,2 for scalars/vectors/tensors. However we are free to
define in the perturbation module some arbitrary values of k:
later on, the transfer module will interpolate at values of k
corresponding exactly to integer values of nu. Hence, apart
from the value of k_min and the step size in the vicinity of
k_min, we define exactly the same sampling in the three cases
K=0, K<0, K>0 */
/* allocate array with, for the moment, the largest possible size */
class_alloc(ppt->k[ppt->index_md_scalars],
((int)((k_max_cmb[ppt->index_md_scalars]-k_min)/k_rec/MIN(ppr->k_step_super,ppr->k_step_sub))+
(int)(MAX(ppr->k_per_decade_for_pk,ppr->k_per_decade_for_bao)*log(k_max/k_min)/log(10.))+3)
*sizeof(double),ppt->error_message);
/* first value */
index_k=0;
k = k_min;
ppt->k[ppt->index_md_scalars][index_k] = k;
index_k++;
/* values until k_max_cmb[ppt->index_md_scalars] */
while (k < k_max_cmb[ppt->index_md_scalars]) {
/* the linear step is not constant, it has a step-like shape,
centered around the characteristic scale set by the sound
horizon at recombination (associated to the comoving wavenumber
k_rec) */
step = (ppr->k_step_super
+ 0.5 * (tanh((k-k_rec)/k_rec/ppr->k_step_transition)+1.)
* (ppr->k_step_sub-ppr->k_step_super)) * k_rec;
/* there is one other thing to take into account in the step
size. There are two other characteristic scales that matter for
the sampling: the Hubble scale today, k0=a0H0, and eventually
curvature scale sqrt(|K|). We define "scale2" as the sum of the
squared Hubble radius and squared curvature radius. We need to
increase the sampling for k<sqrt(scale2), in order to get the
first mutipoles accurate enough. The formula below reduces it
gradually in the k-->0 limit, by up to a factor 10. The actual
stepsize is still fixed by k_step_super, this is just a
reduction factor. */
scale2 = pow(pba->a_today*pba->H0,2)+fabs(pba->K);
step *= (k*k/scale2+1.)/(k*k/scale2+1./ppr->k_step_super_reduction);
class_test(step / k < ppr->smallest_allowed_variation,
ppt->error_message,
"k step =%e < machine precision : leads either to numerical error or infinite loop",
step * k_rec);
k += step;
class_test(k <= ppt->k[ppt->index_md_scalars][index_k-1],
ppt->error_message,
"consecutive values of k should differ and should be in growing order");
ppt->k[ppt->index_md_scalars][index_k] = k;
index_k++;
}
ppt->k_size_cmb[ppt->index_md_scalars] = index_k;
/* values until k_max_cl[ppt->index_md_scalars] */
while (k < k_max_cl[ppt->index_md_scalars]) {
k *= pow(10.,1./(ppr->k_per_decade_for_pk
+(ppr->k_per_decade_for_bao-ppr->k_per_decade_for_pk)
*(1.-tanh(pow((log(k)-log(ppr->k_bao_center*k_rec))/log(ppr->k_bao_width),4)))));
ppt->k[ppt->index_md_scalars][index_k] = k;
index_k++;
}
ppt->k_size_cl[ppt->index_md_scalars] = index_k;
/* values until k_max */
while (k < k_max) {
k *= pow(10.,1./(ppr->k_per_decade_for_pk
+(ppr->k_per_decade_for_bao-ppr->k_per_decade_for_pk)
*(1.-tanh(pow((log(k)-log(ppr->k_bao_center*k_rec))/log(ppr->k_bao_width),4)))));
ppt->k[ppt->index_md_scalars][index_k] = k;
index_k++;
}
ppt->k_size[ppt->index_md_scalars] = index_k;
class_realloc(ppt->k[ppt->index_md_scalars],
ppt->k[ppt->index_md_scalars],
ppt->k_size[ppt->index_md_scalars]*sizeof(double),
ppt->error_message);
}
/** - vector modes */
if (ppt->has_vectors == _TRUE_) {
/* first value */
if (pba->sgnK == 0) {
/* K<0 (flat) : start close to zero */
k_min=ppr->k_min_tau0/pba->conformal_age;
}
else if (pba->sgnK == -1) {
/* K<0 (open) : start close to sqrt(-K)
(in transfer modules, for scalars, this will correspond to q close to zero;
for vectors and tensors, this value is even smaller than the minimum necessary value) */
k_min=sqrt(-pba->K+pow(ppr->k_min_tau0/pba->conformal_age/pth->angular_rescaling,2));
}
else if (pba->sgnK == 1) {
/* K>0 (closed): start from q=sqrt(k2+(1+m)K) equal to 3sqrt(K), i.e. k=sqrt((8-m)K) */
k_min = sqrt((7.-1.e-4)*pba->K);
}
/** - --> find k_max (as well as k_max_cmb[ppt->index_md_vectors], k_max_cl[ppt->index_md_vectors]) */
k_rec = 2. * _PI_ / pth->rs_rec; /* comoving scale corresponding to sound horizon at recombination */
k_max_cmb[ppt->index_md_vectors] = k_min;
k_max_cl[ppt->index_md_vectors] = k_min;
k_max = k_min;
if (ppt->has_cls == _TRUE_) {
/* find k_max_cmb: */
/* choose a k_max_cmb corresponding to a wavelength on the last
scattering surface seen today under an angle smaller than
pi/lmax: this is equivalent to
k_max_cl*[comvoving.ang.diameter.distance] > l_max */
k_max_cmb[ppt->index_md_vectors] = ppr->k_max_tau0_over_l_max*ppt->l_vector_max
/pba->conformal_age/pth->angular_rescaling;
k_max_cl[ppt->index_md_vectors] = k_max_cmb[ppt->index_md_vectors];
k_max = k_max_cmb[ppt->index_md_vectors];
}
/** - --> test that result for k_min, k_max make sense */
class_test(k_min<0.,
ppt->error_message,
"buggy definition of k_min");
class_test(k_max<0.,
ppt->error_message,
"buggy definition of k_max");
class_test(k_max<k_min,
ppt->error_message,
"buggy definition of k_min and/or k_max");
/* if K>0, the transfer function will be calculated for discrete
integer values of nu=3,4,5,... where nu=sqrt(k2+(1+m)K) and
m=0,1,2 for scalars/vectors/tensors. However we are free to
define in the perturbation module some arbitrary values of k:
later on, the transfer module will interpolate at values of k
corresponding exactly to integer values of nu. Hence, apart
from the value of k_min and the step size in the vicinity of
k_min, we define exactly the same sampling in the three cases
K=0, K<0, K>0 */
/* allocate array with, for the moment, the largest possible size */
class_alloc(ppt->k[ppt->index_md_vectors],
((int)((k_max_cmb[ppt->index_md_vectors]-k_min)/k_rec/MIN(ppr->k_step_super,ppr->k_step_sub))+1)
*sizeof(double),ppt->error_message);
/* first value */
index_k=0;
k = k_min;
ppt->k[ppt->index_md_vectors][index_k] = k;
index_k++;
/* values until k_max_cmb[ppt->index_md_vectors] */
while (k < k_max_cmb[ppt->index_md_vectors]) {
/* the linear step is not constant, it has a step-like shape,
centered around the characteristic scale set by the sound
horizon at recombination (associated to the comoving wavenumber
k_rec) */
step = (ppr->k_step_super
+ 0.5 * (tanh((k-k_rec)/k_rec/ppr->k_step_transition)+1.)
* (ppr->k_step_sub-ppr->k_step_super)) * k_rec;
/* there is one other thing to take into account in the step
size. There are two other characteristic scales that matter for
the sampling: the Hubble scale today, k0=a0H0, and eventually
curvature scale sqrt(|K|). We define "scale2" as the sum of the
squared Hubble radius and squared curvature radius. We need to
increase the sampling for k<sqrt(scale2), in order to get the
first mutipoles accurate enough. The formula below reduces it
gradually in the k-->0 limit, by up to a factor 10. The actual
stepsize is still fixed by k_step_super, this is just a
reduction factor. */
scale2 = pow(pba->a_today*pba->H0,2)+fabs(pba->K);
step *= (k*k/scale2+1.)/(k*k/scale2+1./ppr->k_step_super_reduction);
class_test(step / k < ppr->smallest_allowed_variation,
ppt->error_message,
"k step =%e < machine precision : leads either to numerical error or infinite loop",
step * k_rec);
k += step;
class_test(k <= ppt->k[ppt->index_md_scalars][index_k-1],
ppt->error_message,
"consecutive values of k should differ and should be in growing order");
ppt->k[ppt->index_md_vectors][index_k] = k;
index_k++;
}
ppt->k_size_cmb[ppt->index_md_vectors] = index_k;
ppt->k_size_cl[ppt->index_md_vectors] = index_k;
ppt->k_size[ppt->index_md_vectors] = index_k;
class_realloc(ppt->k[ppt->index_md_vectors],
ppt->k[ppt->index_md_vectors],
ppt->k_size[ppt->index_md_vectors]*sizeof(double),
ppt->error_message);
}
/** - tensor modes */
if (ppt->has_tensors == _TRUE_) {
/* first value */
if (pba->sgnK == 0) {
/* K<0 (flat) : start close to zero */
k_min=ppr->k_min_tau0/pba->conformal_age;
}
else if (pba->sgnK == -1) {
/* K<0 (open) : start close to sqrt(-K)
(in transfer modules, for scalars, this will correspond to q close to zero;
for vectors and tensors, this value is even smaller than the minimum necessary value) */
k_min=sqrt(-pba->K+pow(ppr->k_min_tau0/pba->conformal_age/pth->angular_rescaling,2));
}
else if (pba->sgnK == 1) {
/* K>0 (closed): start from q=sqrt(k2+(1+m)K) equal to 3sqrt(K), i.e. k=sqrt((8-m)K) */
k_min = sqrt((6.-1.e-4)*pba->K);
}
/** - --> find k_max (as well as k_max_cmb[ppt->index_md_tensors], k_max_cl[ppt->index_md_tensors]) */
k_rec = 2. * _PI_ / pth->rs_rec; /* comoving scale corresponding to sound horizon at recombination */
k_max_cmb[ppt->index_md_tensors] = k_min;
k_max_cl[ppt->index_md_tensors] = k_min;
k_max = k_min;
if (ppt->has_cls == _TRUE_) {
/* find k_max_cmb[ppt->index_md_tensors]: */
/* choose a k_max_cmb[ppt->index_md_tensors] corresponding to a wavelength on the last
scattering surface seen today under an angle smaller than
pi/lmax: this is equivalent to
k_max_cl[ppt->index_md_tensors]*[comvoving.ang.diameter.distance] > l_max */
k_max_cmb[ppt->index_md_tensors] = ppr->k_max_tau0_over_l_max*ppt->l_tensor_max
/pba->conformal_age/pth->angular_rescaling;
k_max_cl[ppt->index_md_tensors] = k_max_cmb[ppt->index_md_tensors];
k_max = k_max_cmb[ppt->index_md_tensors];
}
/** - --> test that result for k_min, k_max make sense */
class_test(k_min<0.,
ppt->error_message,
"buggy definition of k_min");
class_test(k_max<0.,
ppt->error_message,
"buggy definition of k_max");
class_test(k_max<k_min,
ppt->error_message,
"buggy definition of k_min and/or k_max");
/* if K>0, the transfer function will be calculated for discrete
integer values of nu=3,4,5,... where nu=sqrt(k2+(1+m)K) and
m=0,1,2 for scalars/vectors/tensors. However we are free to
define in the perturbation module some arbitrary values of k:
later on, the transfer module will interpolate at values of k
corresponding exactly to integer values of nu. Hence, apart
from the value of k_min and the step size in the vicinity of
k_min, we define exactly the same sampling in the three cases
K=0, K<0, K>0 */
/* allocate array with, for the moment, the largest possible size */
class_alloc(ppt->k[ppt->index_md_tensors],
((int)((k_max_cmb[ppt->index_md_tensors]-k_min)/k_rec/MIN(ppr->k_step_super,ppr->k_step_sub))+1)
*sizeof(double),ppt->error_message);
/* first value */
index_k=0;
k = k_min;
ppt->k[ppt->index_md_tensors][index_k] = k;
index_k++;
/* values until k_max_cmb[ppt->index_md_tensors] */
while (k < k_max_cmb[ppt->index_md_tensors]) {
/* the linear step is not constant, it has a step-like shape,
centered around the characteristic scale set by the sound
horizon at recombination (associated to the comoving wavenumber
k_rec) */
step = (ppr->k_step_super
+ 0.5 * (tanh((k-k_rec)/k_rec/ppr->k_step_transition)+1.)
* (ppr->k_step_sub-ppr->k_step_super)) * k_rec;
/* there is one other thing to take into account in the step
size. There are two other characteristic scales that matter for
the sampling: the Hubble scale today, k0=a0H0, and eventually
curvature scale sqrt(|K|). We define "scale2" as the sum of the
squared Hubble radius and squared curvature radius. We need to
increase the sampling for k<sqrt(scale2), in order to get the
first mutipoles accurate enough. The formula below reduces it
gradually in the k-->0 limit, by up to a factor 10. The actual
stepsize is still fixed by k_step_super, this is just a
reduction factor. */
scale2 = pow(pba->a_today*pba->H0,2)+fabs(pba->K);
step *= (k*k/scale2+1.)/(k*k/scale2+1./ppr->k_step_super_reduction);
class_test(step / k < ppr->smallest_allowed_variation,
ppt->error_message,
"k step =%e < machine precision : leads either to numerical error or infinite loop",
step * k_rec);
k += step;
class_test(k <= ppt->k[ppt->index_md_tensors][index_k-1],
ppt->error_message,
"consecutive values of k should differ and should be in growing order");
ppt->k[ppt->index_md_tensors][index_k] = k;
index_k++;
}
ppt->k_size_cmb[ppt->index_md_tensors] = index_k;
ppt->k_size_cl[ppt->index_md_tensors] = index_k;
ppt->k_size[ppt->index_md_tensors] = index_k;
class_realloc(ppt->k[ppt->index_md_tensors],
ppt->k[ppt->index_md_tensors],
ppt->k_size[ppt->index_md_tensors]*sizeof(double),
ppt->error_message);
}
/** - If user asked for k_output_values, add those to all k lists: */
if (ppt->k_output_values_num>0) {
/* Allocate storage */
class_alloc(ppt->index_k_output_values,sizeof(double)*ppt->md_size*ppt->k_output_values_num,ppt->error_message);
/** - --> Find indices in ppt->k[index_md] corresponding to 'k_output_values'.
We are assuming that ppt->k is sorted and growing, and we have made sure
that ppt->k_output_values is also sorted and growing.*/
for (index_mode=0; index_mode<ppt->md_size; index_mode++) {
newk_size = ppt->k_size[index_mode]+ppt->k_output_values_num;
class_alloc(tmp_k_list,sizeof(double)*newk_size,ppt->error_message);
index_k=0;
index_k_output=0;
for (index_newk=0; index_newk<newk_size; index_newk++) {
/** - --> Decide if we should add k_output_value now. This has to be this complicated, since we
can only compare the k-values when both indices are in range.*/
if (index_k >= ppt->k_size[index_mode])
add_k_output_value = _TRUE_;
else if (index_k_output >= ppt->k_output_values_num)
add_k_output_value = _FALSE_;
else if (ppt->k_output_values[index_k_output] < ppt->k[index_mode][index_k])
add_k_output_value = _TRUE_;
else
add_k_output_value = _FALSE_;
if (add_k_output_value == _TRUE_) {
tmp_k_list[index_newk] = ppt->k_output_values[index_k_output];
ppt->index_k_output_values[index_mode*ppt->k_output_values_num+index_k_output]=index_newk;
index_k_output++;
}
else {
tmp_k_list[index_newk] = ppt->k[index_mode][index_k];
index_k++;
}
}
free(ppt->k[index_mode]);
ppt->k[index_mode] = tmp_k_list;
ppt->k_size[index_mode] = newk_size;
index_k = newk_size-1;
while (ppt->k[index_mode][index_k] > k_max_cl[index_mode])
index_k--;
ppt->k_size_cl[index_mode] = MIN(index_k+2,ppt->k_size[index_mode]);
index_k = newk_size-1;
while (ppt->k[index_mode][index_k] > k_max_cmb[index_mode])
index_k--;
ppt->k_size_cmb[index_mode] = MIN(index_k+2,ppt->k_size[index_mode]);
/** - --> The two MIN statements are here because in a normal run, the cl and cmb
arrays contain a single k value larger than their respective k_max.
We are mimicking this behavior. */
}
}
/* For testing, can be useful to print the k list in a file:
FILE * out=fopen("output/k","w");
for (index_k=0; index_k < ppt->k_size[0]; index_k++) {
fprintf(out,"%e\n",ppt->k[0][index_k],pba->K);
}
fclose(out);
*/
/** - finally, find the global k_min and k_max for the ensemble of all modes 9scalars, vectors, tensors) */
ppt->k_min = _HUGE_;
ppt->k_max = 0.;
if (ppt->has_scalars == _TRUE_) {
ppt->k_min = MIN(ppt->k_min,ppt->k[ppt->index_md_scalars][0]); /* first value, inferred from perturbations structure */
ppt->k_max = MAX(ppt->k_max,ppt->k[ppt->index_md_scalars][ppt->k_size[ppt->index_md_scalars]-1]); /* last value, inferred from perturbations structure */
}
if (ppt->has_vectors == _TRUE_) {
ppt->k_min = MIN(ppt->k_min,ppt->k[ppt->index_md_vectors][0]); /* first value, inferred from perturbations structure */
ppt->k_max = MAX(ppt->k_max,ppt->k[ppt->index_md_vectors][ppt->k_size[ppt->index_md_vectors]-1]); /* last value, inferred from perturbations structure */
}
if (ppt->has_tensors == _TRUE_) {
ppt->k_min = MIN(ppt->k_min,ppt->k[ppt->index_md_tensors][0]); /* first value, inferred from perturbations structure */
ppt->k_max = MAX(ppt->k_max,ppt->k[ppt->index_md_tensors][ppt->k_size[ppt->index_md_tensors]-1]); /* last value, inferred from perturbations structure */
}
free(k_max_cmb);
free(k_max_cl);
return _SUCCESS_;
}
/**
* Initialize a perturb_workspace structure. All fields are allocated
* here, with the exception of the perturb_vector '-->pv' field, which
* is allocated separately in perturb_vector_init. We allocate one
* such perturb_workspace structure per thread and per mode
* (scalar/../tensor). Then, for each thread, all initial conditions
* and wavenumbers will use the same workspace.
*
* @param ppr Input: pointer to precision structure
* @param pba Input: pointer to background structure
* @param pth Input: pointer to the thermodynamics structure
* @param ppt Input: pointer to the perturbation structure
* @param index_md Input: index of mode under consideration (scalar/.../tensor)
* @param ppw Input/Output: pointer to perturb_workspace structure which fields are allocated or filled here
* @return the error status
*/
int perturb_workspace_init(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt,
int index_md,
struct perturb_workspace * ppw
) {
/** Summary: */
/** - define local variables */
int index_mt=0;
int index_ap;
int l;
/** - Compute maximum l_max for any multipole */;
if (_scalars_) {
ppw->max_l_max = MAX(ppr->l_max_g, ppr->l_max_pol_g);
if (pba->has_ur == _TRUE_) ppw->max_l_max = MAX(ppw->max_l_max, ppr->l_max_ur);
if (pba->has_ncdm == _TRUE_) ppw->max_l_max = MAX(ppw->max_l_max, ppr->l_max_ncdm);
if (pba->has_dr == _TRUE_) ppw->max_l_max = MAX(ppw->max_l_max, ppr->l_max_dr);
}
if (_tensors_) {
ppw->max_l_max = MAX(ppr->l_max_g_ten, ppr->l_max_pol_g_ten);
if (pba->has_ur == _TRUE_) ppw->max_l_max = MAX(ppw->max_l_max, ppr->l_max_ur);
if (pba->has_ncdm == _TRUE_) ppw->max_l_max = MAX(ppw->max_l_max, ppr->l_max_ncdm);
}
/** - Allocate \f$ s_l\f$[ ] array for freestreaming of multipoles (see arXiv:1305.3261) and initialize
to 1.0, which is the K=0 value. */
class_alloc(ppw->s_l, sizeof(double)*(ppw->max_l_max+1),ppt->error_message);
for (l=0; l<=ppw->max_l_max; l++) {
ppw->s_l[l] = 1.0;
}
/** - define indices of metric perturbations obeying constraint
equations (this can be done once and for all, because the
vector of metric perturbations is the same whatever the
approximation scheme, unlike the vector of quantities to
be integrated, which is allocated separately in
perturb_vector_init) */
if (_scalars_) {
/* newtonian gauge */
if (ppt->gauge == newtonian) {
class_define_index(ppw->index_mt_psi,_TRUE_,index_mt,1); /* psi */
class_define_index(ppw->index_mt_phi_prime,_TRUE_,index_mt,1); /* phi' */
}
/* synchronous gauge (note that eta is counted in the vector of
quantities to be integrated, while here we only consider
quantities obeying to constraint equations) */
if (ppt->gauge == synchronous) {
class_define_index(ppw->index_mt_h_prime,_TRUE_,index_mt,1); /* h' */
class_define_index(ppw->index_mt_h_prime_prime,_TRUE_,index_mt,1); /* h'' */
class_define_index(ppw->index_mt_eta_prime,_TRUE_,index_mt,1); /* eta' */
class_define_index(ppw->index_mt_alpha,_TRUE_,index_mt,1); /* alpha = (h' + 6 tau') / (2 k**2) */
class_define_index(ppw->index_mt_alpha_prime,_TRUE_,index_mt,1); /* alpha' */
}
}
if (_vectors_) {
/* newtonian gauge */
if (ppt->gauge == newtonian) {
class_define_index(ppw->index_mt_V_prime,_TRUE_,index_mt,1);
}
if (ppt->gauge == synchronous) {
class_define_index(ppw->index_mt_hv_prime_prime,_TRUE_,index_mt,1);
}
}
if (_tensors_) {
class_define_index(ppw->index_mt_gw_prime_prime,_TRUE_,index_mt,1);
}
ppw->mt_size = index_mt;
/** - allocate some workspace in which we will store temporarily the
values of background, thermodynamics, metric and source
quantities at a given time */
class_alloc(ppw->pvecback,pba->bg_size_normal*sizeof(double),ppt->error_message);
class_alloc(ppw->pvecthermo,pth->th_size*sizeof(double),ppt->error_message);
class_alloc(ppw->pvecmetric,ppw->mt_size*sizeof(double),ppt->error_message);
/** - count number of approximations, initialize their indices, and allocate their flags */
index_ap=0;
class_define_index(ppw->index_ap_tca,_TRUE_,index_ap,1);
class_define_index(ppw->index_ap_rsa,_TRUE_,index_ap,1);
if (_scalars_) {
class_define_index(ppw->index_ap_ufa,pba->has_ur,index_ap,1);
class_define_index(ppw->index_ap_ncdmfa,pba->has_ncdm,index_ap,1);
}
ppw->ap_size=index_ap;
if (ppw->ap_size > 0)
class_alloc(ppw->approx,ppw->ap_size*sizeof(int),ppt->error_message);
/** - For definiteness, initialize approximation flags to arbitrary
values (correct values are overwritten in
pertub_find_approximation_switches) */
if (_scalars_) {
ppw->approx[ppw->index_ap_tca]=(int)tca_on;
ppw->approx[ppw->index_ap_rsa]=(int)rsa_off;
if (pba->has_ur == _TRUE_) {
ppw->approx[ppw->index_ap_ufa]=(int)ufa_off;
}
if (pba->has_ncdm == _TRUE_) {
ppw->approx[ppw->index_ap_ncdmfa]=(int)ncdmfa_off;
}
}
if (_tensors_) {
ppw->approx[ppw->index_ap_tca]=(int)tca_on;
ppw->approx[ppw->index_ap_rsa]=(int)rsa_off;
}
/** - allocate fields where some of the perturbations are stored */
if (_scalars_) {
if ((ppt->has_density_transfers == _TRUE_) || (ppt->has_velocity_transfers == _TRUE_) || (ppt->has_source_delta_m == _TRUE_)) {
class_alloc(ppw->delta_ncdm,pba->N_ncdm*sizeof(double),ppt->error_message);
class_alloc(ppw->theta_ncdm,pba->N_ncdm*sizeof(double),ppt->error_message);
class_alloc(ppw->shear_ncdm,pba->N_ncdm*sizeof(double),ppt->error_message);
}
}
return _SUCCESS_;
}
/**
* Free the perturb_workspace structure (with the exception of the
* perturb_vector '-->pv' field, which is freed separately in
* perturb_vector_free).
*
* @param ppt Input: pointer to the perturbation structure
* @param index_md Input: index of mode under consideration (scalar/.../tensor)
* @param ppw Input: pointer to perturb_workspace structure to be freed
* @return the error status
*/
int perturb_workspace_free (
struct perturbs * ppt,
int index_md,
struct perturb_workspace * ppw
) {
free(ppw->s_l);
free(ppw->pvecback);
free(ppw->pvecthermo);
free(ppw->pvecmetric);
if (ppw->ap_size > 0)
free(ppw->approx);
if (_scalars_) {
if ((ppt->has_density_transfers == _TRUE_) || (ppt->has_velocity_transfers == _TRUE_) || (ppt->has_source_delta_m == _TRUE_)) {
free(ppw->delta_ncdm);
free(ppw->theta_ncdm);
free(ppw->shear_ncdm);
}
}
free(ppw);
return _SUCCESS_;
}
/**
* Solve the perturbation evolution for a given mode, initial
* condition and wavenumber, and compute the corresponding source
* functions.
*
* For a given mode, initial condition and wavenumber, this function
* finds the time ranges over which the perturbations can be described
* within a given approximation. For each such range, it initializes
* (or redistributes) perturbations using perturb_vector_init(), and
* integrates over time. Whenever a "source sampling time" is passed,
* the source terms are computed and stored in the source table using
* perturb_sources().
*
* @param ppr Input: pointer to precision structure
* @param pba Input: pointer to background structure
* @param pth Input: pointer to the thermodynamics structure
* @param ppt Input/Output: pointer to the perturbation structure (output source functions S(k,tau) written here)
* @param index_md Input: index of mode under consideration (scalar/.../tensor)
* @param index_ic Input: index of initial condition under consideration (ad, iso...)
* @param index_k Input: index of wavenumber
* @param ppw Input: pointer to perturb_workspace structure containing index values and workspaces
* @return the error status
*/
int perturb_solve(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt,
int index_md,
int index_ic,
int index_k,
struct perturb_workspace * ppw
) {
/** Summary: */
/** - define local variables */
/* contains all fixed parameters, indices and workspaces used by the perturb_derivs function */
struct perturb_parameters_and_workspace ppaw;
/* conformal time */
double tau,tau_lower,tau_upper,tau_mid;
/* multipole */
int l;
/* index running over time */
int index_tau;
/* number of values in the tau_sampling array that should be considered for a given mode */
int tau_actual_size;
/* running index over types (temperature, etc) */
int index_type;
/* Fourier mode */
double k;
/* number of time intervals where the approximation scheme is uniform */
int interval_number;
/* index running over such time intervals */
int index_interval;
/* number of time intervals where each particular approximation is uniform */
int * interval_number_of;
/* edge of intervals where approximation scheme is uniform: tau_ini, tau_switch_1, ..., tau_end */
double * interval_limit;
/* array of approximation scheme within each interval: interval_approx[index_interval][index_ap] */
int ** interval_approx;
/* index running over approximations */
int index_ap;
/* approximation scheme within previous interval: previous_approx[index_ap] */
int * previous_approx;
int n_ncdm,is_early_enough;
/* function pointer to ODE evolver and names of possible evolvers */
extern int evolver_rk();
extern int evolver_ndf15();
int (*generic_evolver)();
/* Related to the perturbation output */
int (*perhaps_print_variables)();
int index_ikout;
/** - initialize indices relevant for back/thermo tables search */
ppw->last_index_back=0;
ppw->last_index_thermo=0;
ppw->inter_mode = pba->inter_normal;
/** - get wavenumber value */
k = ppt->k[index_md][index_k];
class_test(k == 0.,
ppt->error_message,
"stop to avoid division by zero");
/** - If non-zero curvature, update array of free-streaming coefficients ppw->s_l */
if (pba->has_curvature == _TRUE_) {
for (l = 0; l<=ppw->max_l_max; l++) {
ppw->s_l[l] = sqrt(MAX(1.0-pba->K*(l*l-1.0)/k/k,0.));
}
}
/** - maximum value of tau for which sources are calculated for this wavenumber */
/* by default, today */
tau_actual_size = ppt->tau_size;
/** - using bisection, compute minimum value of tau for which this
wavenumber is integrated */
/* will be at least the first time in the background table */
tau_lower = pba->tau_table[0];
class_call(background_at_tau(pba,
tau_lower,
pba->normal_info,
pba->inter_normal,
&(ppw->last_index_back),
ppw->pvecback),
pba->error_message,
ppt->error_message);
class_call(thermodynamics_at_z(pba,
pth,
1./ppw->pvecback[pba->index_bg_a]-1.,
pth->inter_normal,
&(ppw->last_index_thermo),
ppw->pvecback,
ppw->pvecthermo),
pth->error_message,
ppt->error_message);
/* check that this initial time is indeed OK given imposed
conditions on kappa' and on k/aH */
class_test(ppw->pvecback[pba->index_bg_a]*
ppw->pvecback[pba->index_bg_H]/
ppw->pvecthermo[pth->index_th_dkappa] >
ppr->start_small_k_at_tau_c_over_tau_h, ppt->error_message, "your choice of initial time for integrating wavenumbers is inappropriate: it corresponds to a time before that at which the background has been integrated. You should increase 'start_small_k_at_tau_c_over_tau_h' up to at least %g, or decrease 'a_ini_over_a_today_default'\n",
ppw->pvecback[pba->index_bg_a]*
ppw->pvecback[pba->index_bg_H]/
ppw->pvecthermo[pth->index_th_dkappa]);
class_test(k/ppw->pvecback[pba->index_bg_a]/ppw->pvecback[pba->index_bg_H] >
ppr->start_large_k_at_tau_h_over_tau_k,
ppt->error_message,
"your choice of initial time for integrating wavenumbers is inappropriate: it corresponds to a time before that at which the background has been integrated. You should increase 'start_large_k_at_tau_h_over_tau_k' up to at least %g, or decrease 'a_ini_over_a_today_default'\n",
ppt->k[index_md][ppt->k_size[index_md]-1]/ppw->pvecback[pba->index_bg_a]/ ppw->pvecback[pba->index_bg_H]);
if (pba->has_ncdm == _TRUE_) {
for (n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
class_test(fabs(ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm]/ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]-1./3.)>ppr->tol_ncdm_initial_w,
ppt->error_message,
"your choice of initial time for integrating wavenumbers is inappropriate: it corresponds to a time at which the ncdm species number %d is not ultra-relativistic anymore, with w=%g, p=%g and rho=%g\n",
n_ncdm,
ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm]/ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm],
ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm],
ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]);
}
}
/* is at most the time at which sources must be sampled */
tau_upper = ppt->tau_sampling[0];
/* start bisection */
tau_mid = 0.5*(tau_lower + tau_upper);
while ((tau_upper - tau_lower)/tau_lower > ppr->tol_tau_approx) {
is_early_enough = _TRUE_;
class_call(background_at_tau(pba,
tau_mid,
pba->normal_info,
pba->inter_normal,
&(ppw->last_index_back),
ppw->pvecback),
pba->error_message,
ppt->error_message);
/* if there are non-cold relics, check that they are relativistic enough */
if (pba->has_ncdm == _TRUE_) {
for (n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
if (fabs(ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm]/ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]-1./3.) > ppr->tol_ncdm_initial_w)
is_early_enough = _FALSE_;
}
}
/* also check that the two conditions on (aH/kappa') and (aH/k) are fulfilled */
if (is_early_enough == _TRUE_) {
class_call(thermodynamics_at_z(pba,
pth,
1./ppw->pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
pth->inter_normal,
&(ppw->last_index_thermo),
ppw->pvecback,
ppw->pvecthermo),
pth->error_message,
ppt->error_message);
if ((ppw->pvecback[pba->index_bg_a]*
ppw->pvecback[pba->index_bg_H]/
ppw->pvecthermo[pth->index_th_dkappa] >
ppr->start_small_k_at_tau_c_over_tau_h) ||
(k/ppw->pvecback[pba->index_bg_a]/ppw->pvecback[pba->index_bg_H] >
ppr->start_large_k_at_tau_h_over_tau_k))
is_early_enough = _FALSE_;
}
if (is_early_enough == _TRUE_)
tau_lower = tau_mid;
else
tau_upper = tau_mid;
tau_mid = 0.5*(tau_lower + tau_upper);
}
tau = tau_mid;
/** - find the number of intervals over which approximation scheme is constant */
class_alloc(interval_number_of,ppw->ap_size*sizeof(int),ppt->error_message);
ppw->inter_mode = pba->inter_normal;
class_call(perturb_find_approximation_number(ppr,
pba,
pth,
ppt,
index_md,
k,
ppw,
tau,
ppt->tau_sampling[tau_actual_size-1],
&interval_number,
interval_number_of),
ppt->error_message,
ppt->error_message);
class_alloc(interval_limit,(interval_number+1)*sizeof(double),ppt->error_message);
class_alloc(interval_approx,interval_number*sizeof(int*),ppt->error_message);
for (index_interval=0; index_interval<interval_number; index_interval++)
class_alloc(interval_approx[index_interval],ppw->ap_size*sizeof(int),ppt->error_message);
class_call(perturb_find_approximation_switches(ppr,
pba,
pth,
ppt,
index_md,
k,
ppw,
tau,
ppt->tau_sampling[tau_actual_size-1],
ppr->tol_tau_approx,
interval_number,
interval_number_of,
interval_limit,
interval_approx),
ppt->error_message,
ppt->error_message);
free(interval_number_of);
/** - fill the structure containing all fixed parameters, indices
and workspaces needed by perturb_derivs */
ppaw.ppr = ppr;
ppaw.pba = pba;
ppaw.pth = pth;
ppaw.ppt = ppt;
ppaw.index_md = index_md;
ppaw.index_ic = index_ic;
ppaw.index_k = index_k;
ppaw.k = k;
ppaw.ppw = ppw;
ppaw.ppw->inter_mode = pba->inter_closeby;
ppaw.ppw->last_index_back = 0;
ppaw.ppw->last_index_thermo = 0;
/** - check whether we need to print perturbations to a file for this wavenumber */
perhaps_print_variables = NULL;
ppw->index_ikout = -1;
for (index_ikout=0; index_ikout<ppt->k_output_values_num; index_ikout++) {
if (ppt->index_k_output_values[index_md*ppt->k_output_values_num+index_ikout] == index_k) {
ppw->index_ikout = index_ikout;
perhaps_print_variables = perturb_print_variables;
/* class_call(perturb_prepare_output_file(
pba,ppt,ppw,index_ikout,index_md),
ppt->error_message,
ppt->error_message);
*/
}
}
/** - loop over intervals over which approximation scheme is uniform. For each interval: */
for (index_interval=0; index_interval<interval_number; index_interval++) {
/** - --> (a) fix the approximation scheme */
for (index_ap=0; index_ap<ppw->ap_size; index_ap++)
ppw->approx[index_ap]=interval_approx[index_interval][index_ap];
/** - --> (b) get the previous approximation scheme. If the current
interval starts from the initial time tau_ini, the previous
approximation is set to be a NULL pointer, so that the
function perturb_vector_init() knows that perturbations must
be initialized */
if (index_interval==0) {
previous_approx=NULL;
}
else {
previous_approx=interval_approx[index_interval-1];
}
/** - --> (c) define the vector of perturbations to be integrated
over. If the current interval starts from the initial time
tau_ini, fill the vector with initial conditions for each
mode. If it starts from an approximation switching point,
redistribute correctly the perturbations from the previous to
the new vector of perturbations. */
class_call(perturb_vector_init(ppr,
pba,
pth,
ppt,
index_md,
index_ic,
k,
interval_limit[index_interval],
ppw,
previous_approx),
ppt->error_message,
ppt->error_message);
/** - --> (d) integrate the perturbations over the current interval. */
if(ppr->evolver == rk) {
generic_evolver = evolver_rk;
}
else {
generic_evolver = evolver_ndf15;
}
class_call(generic_evolver(perturb_derivs,
interval_limit[index_interval],
interval_limit[index_interval+1],
ppw->pv->y,
ppw->pv->used_in_sources,
ppw->pv->pt_size,
&ppaw,
ppr->tol_perturb_integration,
ppr->smallest_allowed_variation,
perturb_timescale,
ppr->perturb_integration_stepsize,
ppt->tau_sampling,
tau_actual_size,
perturb_sources,
perhaps_print_variables,
ppt->error_message),
ppt->error_message,
ppt->error_message);
}
/** - if perturbations were printed in a file, close the file */
//if (perhaps_print_variables != NULL)
// fclose(ppw->perturb_output_file);
/** - fill the source terms array with zeros for all times between
the last integrated time tau_max and tau_today. */
for (index_tau = tau_actual_size; index_tau < ppt->tau_size; index_tau++) {
for (index_type = 0; index_type < ppt->tp_size[index_md]; index_type++) {
ppt->sources[index_md]
[index_ic * ppt->tp_size[index_md] + index_type]
[index_tau * ppt->k_size[index_md] + index_k] = 0.;
}
}
/** - free quantities allocated at the beginning of the routine */
class_call(perturb_vector_free(ppw->pv),
ppt->error_message,
ppt->error_message);
for (index_interval=0; index_interval<interval_number; index_interval++)
free(interval_approx[index_interval]);
free(interval_approx);
free(interval_limit);
return _SUCCESS_;
}
int perturb_prepare_output(struct background * pba,
struct perturbs * ppt) {
int n_ncdm;
char tmp[40];
ppt->scalar_titles[0]='\0';
ppt->vector_titles[0]='\0';
ppt->tensor_titles[0]='\0';
if (ppt->k_output_values_num > 0) {
/** Write titles for all perturbations that we would like to print/store. */
if (ppt->has_scalars == _TRUE_) {
class_store_columntitle(ppt->scalar_titles,"tau [Mpc]",_TRUE_);
class_store_columntitle(ppt->scalar_titles,"a",_TRUE_);
class_store_columntitle(ppt->scalar_titles,"delta_g",_TRUE_);
class_store_columntitle(ppt->scalar_titles,"theta_g",_TRUE_);
class_store_columntitle(ppt->scalar_titles,"shear_g",_TRUE_);
class_store_columntitle(ppt->scalar_titles,"pol0_g",_TRUE_);
class_store_columntitle(ppt->scalar_titles,"pol1_g",_TRUE_);
class_store_columntitle(ppt->scalar_titles,"pol2_g",_TRUE_);
class_store_columntitle(ppt->scalar_titles,"delta_b",_TRUE_);
class_store_columntitle(ppt->scalar_titles,"theta_b",_TRUE_);
class_store_columntitle(ppt->scalar_titles,"psi",_TRUE_);
class_store_columntitle(ppt->scalar_titles,"phi",_TRUE_);
/* Perturbed recombination */
class_store_columntitle(ppt->scalar_titles,"delta_Tb",ppt->has_perturbed_recombination);
class_store_columntitle(ppt->scalar_titles,"delta_chi",ppt->has_perturbed_recombination);
/* Ultrarelativistic species */
class_store_columntitle(ppt->scalar_titles,"delta_ur",pba->has_ur);
class_store_columntitle(ppt->scalar_titles,"theta_ur",pba->has_ur);
class_store_columntitle(ppt->scalar_titles,"shear_ur",pba->has_ur);
/* Cold dark matter */
class_store_columntitle(ppt->scalar_titles,"delta_cdm",pba->has_cdm);
class_store_columntitle(ppt->scalar_titles,"theta_cdm",pba->has_cdm);
/* Non-cold dark matter */
if ((pba->has_ncdm == _TRUE_) && ((ppt->has_density_transfers == _TRUE_) || (ppt->has_velocity_transfers == _TRUE_) || (ppt->has_source_delta_m == _TRUE_))) {
for(n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
sprintf(tmp,"delta_ncdm[%d]",n_ncdm);
class_store_columntitle(ppt->scalar_titles,tmp,_TRUE_);
sprintf(tmp,"theta_ncdm[%d]",n_ncdm);
class_store_columntitle(ppt->scalar_titles,tmp,_TRUE_);
sprintf(tmp,"shear_ncdm[%d]",n_ncdm);
class_store_columntitle(ppt->scalar_titles,tmp,_TRUE_);
sprintf(tmp,"cs2_ncdm[%d]",n_ncdm);
class_store_columntitle(ppt->scalar_titles,tmp,_TRUE_);
}
}
/* Decaying cold dark matter */
class_store_columntitle(ppt->scalar_titles, "delta_dcdm", pba->has_dcdm);
class_store_columntitle(ppt->scalar_titles, "theta_dcdm", pba->has_dcdm);
/* Decay radiation */
class_store_columntitle(ppt->scalar_titles, "delta_dr", pba->has_dr);
class_store_columntitle(ppt->scalar_titles, "theta_dr", pba->has_dr);
class_store_columntitle(ppt->scalar_titles, "shear_dr", pba->has_dr);
/* Scalar field scf */
class_store_columntitle(ppt->scalar_titles, "delta_scf", pba->has_scf);
class_store_columntitle(ppt->scalar_titles, "theta_scf", pba->has_scf);
ppt->number_of_scalar_titles =
get_number_of_titles(ppt->scalar_titles);
}
if (ppt->has_tensors == _TRUE_) {
class_store_columntitle(ppt->tensor_titles,"tau [Mpc]",_TRUE_);
class_store_columntitle(ppt->tensor_titles,"a",_TRUE_);
class_store_columntitle(ppt->tensor_titles,"delta_g",_TRUE_);
class_store_columntitle(ppt->tensor_titles,"shear_g",_TRUE_);
class_store_columntitle(ppt->tensor_titles,"l4_g",_TRUE_);
class_store_columntitle(ppt->tensor_titles,"pol0_g",_TRUE_);
class_store_columntitle(ppt->tensor_titles,"pol2_g",_TRUE_);
class_store_columntitle(ppt->tensor_titles,"pol4_g",_TRUE_);
class_store_columntitle(ppt->tensor_titles,"H (gw)",_TRUE_);
class_store_columntitle(ppt->tensor_titles,"Hdot (gwdot)",_TRUE_);
class_store_columntitle(ppt->tensor_titles,"delta_ur",ppt->evolve_tensor_ur);
class_store_columntitle(ppt->tensor_titles,"shear_ur",ppt->evolve_tensor_ur);
class_store_columntitle(ppt->tensor_titles,"l4_ur",ppt->evolve_tensor_ur);
if (ppt->evolve_tensor_ncdm == _TRUE_) {
for(n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
sprintf(tmp,"delta_ncdm[%d]",n_ncdm);
class_store_columntitle(ppt->tensor_titles,tmp,_TRUE_);
sprintf(tmp,"theta_ncdm[%d]",n_ncdm);
class_store_columntitle(ppt->tensor_titles,tmp,_TRUE_);
sprintf(tmp,"shear_ncdm[%d]",n_ncdm);
class_store_columntitle(ppt->tensor_titles,tmp,_TRUE_);
}
}
ppt->number_of_tensor_titles =
get_number_of_titles(ppt->tensor_titles);
}
}
return _SUCCESS_;
}
/**
* For a given mode and wavenumber, find the number of intervals of
* time between tau_ini and tau_end such that the approximation
* scheme (and the number of perturbation equations) is uniform.
*
* @param ppr Input: pointer to precision structure
* @param pba Input: pointer to background structure
* @param pth Input: pointer to the thermodynamics structure
* @param ppt Input: pointer to the perturbation structure
* @param index_md Input: index of mode under consideration (scalar/.../tensor)
* @param k Input: index of wavenumber
* @param ppw Input: pointer to perturb_workspace structure containing index values and workspaces
* @param tau_ini Input: initial time of the perturbation integration
* @param tau_end Input: final time of the perturbation integration
* @param interval_number Output: total number of intervals
* @param interval_number_of Output: number of intervals with respect to each particular approximation
* @return the error status
*/
int perturb_find_approximation_number(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt,
int index_md,
double k,
struct perturb_workspace * ppw,
double tau_ini,
double tau_end,
int * interval_number,
int * interval_number_of /* interval_number_of[index_ap] (already allocated) */
) {
/** Summary: */
/* index running over approximations */
int index_ap;
/* value of a given approximation at tau_ini and tau_end */
int flag_ini,flag_end;
/** - fix default number of intervals to one (if no approximation switch) */
*interval_number=1;
/** - loop over each approximation and add the number of approximation switching times */
for (index_ap=0; index_ap<ppw->ap_size; index_ap++) {
class_call(perturb_approximations(ppr,
pba,
pth,
ppt,
index_md,
k,
tau_ini,
ppw),
ppt->error_message,
ppt->error_message);
flag_ini = ppw->approx[index_ap];
class_call(perturb_approximations(ppr,
pba,
pth,
ppt,
index_md,
k,
tau_end,
ppw),
ppt->error_message,
ppt->error_message);
flag_end = ppw->approx[index_ap];
class_test(flag_end<flag_ini,
ppt->error_message,
"For each approximation scheme, the declaration of approximation labels in the enumeration must follow chronological order, e.g: enum approx_flags {flag1, flag2, flag3} with flag1 being the initial one and flag3 the final one");
*interval_number += flag_end-flag_ini;
interval_number_of[index_ap] = flag_end-flag_ini+1;
}
return _SUCCESS_;
}
/**
* For a given mode and wavenumber, find the values of time at which
* the approximation changes.
*
* @param ppr Input: pointer to precision structure
* @param pba Input: pointer to background structure
* @param pth Input: pointer to the thermodynamics structure
* @param ppt Input: pointer to the perturbation structure
* @param index_md Input: index of mode under consideration (scalar/.../tensor)
* @param k Input: index of wavenumber
* @param ppw Input: pointer to perturb_workspace structure containing index values and workspaces
* @param tau_ini Input: initial time of the perturbation integration
* @param tau_end Input: final time of the perturbation integration
* @param precision Input: tolerance on output values
* @param interval_number Input: total number of intervals
* @param interval_number_of Input: number of intervals with respect to each particular approximation
* @param interval_limit Output: value of time at the boundary of the intervals: tau_ini, tau_switch1, ..., tau_end
* @param interval_approx Output: value of approximations in each interval
* @return the error status
*/
int perturb_find_approximation_switches(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt,
int index_md,
double k,
struct perturb_workspace * ppw,
double tau_ini,
double tau_end,
double precision,
int interval_number,
int * interval_number_of,
double * interval_limit, /* interval_limit[index_interval] (already allocated) */
int ** interval_approx /* interval_approx[index_interval][index_ap] (already allocated) */
) {
/** Summary: */
int index_ap;
int index_switch;
int index_switch_tot;
int num_switch;
double tau_min,lower_bound,upper_bound;
double mid=0;
double * unsorted_tau_switch;
double next_tau_switch;
int flag_ini;
int num_switching_at_given_time;
/** - write in output arrays the initial time and approximation */
interval_limit[0]=tau_ini;
class_call(perturb_approximations(ppr,
pba,
pth,
ppt,
index_md,
k,
tau_ini,
ppw),
ppt->error_message,
ppt->error_message);
for (index_ap=0; index_ap<ppw->ap_size; index_ap++)
interval_approx[0][index_ap]=ppw->approx[index_ap];
/** - if there are no approximation switches, just write final time and return */
if (interval_number == 1) {
interval_limit[1]=tau_end;
}
/** - if there are switches, consider approximations one after each
other. Find switching time by bisection. Store all switches in
arbitrary order in array unsorted_tau_switch[ ] */
else {
class_alloc(unsorted_tau_switch,(interval_number-1)*sizeof(double),ppt->error_message);
index_switch_tot=0;
for (index_ap=0; index_ap<ppw->ap_size; index_ap++) {
if (interval_number_of[index_ap] > 1) {
num_switch = interval_number_of[index_ap]-1;
tau_min = tau_ini;
flag_ini = interval_approx[0][index_ap];
for (index_switch=0; index_switch<num_switch; index_switch++) {
lower_bound=tau_min;
upper_bound=tau_end;
mid = 0.5*(lower_bound+upper_bound);
while (upper_bound - lower_bound > precision) {
class_call(perturb_approximations(ppr,
pba,
pth,
ppt,
index_md,
k,
mid,
ppw),
ppt->error_message,
ppt->error_message);
if (ppw->approx[index_ap] > flag_ini+index_switch) {
upper_bound=mid;
}
else {
lower_bound=mid;
}
mid = 0.5*(lower_bound+upper_bound);
}
unsorted_tau_switch[index_switch_tot]=mid;
index_switch_tot++;
tau_min=mid;
}
}
}
class_test(index_switch_tot != (interval_number-1),
ppt->error_message,
"bug in approximation switch search routine: should have %d = %d",
index_switch_tot,interval_number-1);
/** - now sort interval limits in correct order */
index_switch_tot=1;
while (index_switch_tot < interval_number) {
next_tau_switch=tau_end;
for (index_switch=0; index_switch<interval_number-1; index_switch++) {
if ((unsorted_tau_switch[index_switch] > interval_limit[index_switch_tot-1]) &&
(unsorted_tau_switch[index_switch] < next_tau_switch)) {
next_tau_switch=unsorted_tau_switch[index_switch];
}
}
interval_limit[index_switch_tot]=next_tau_switch;
index_switch_tot++;
}
interval_limit[index_switch_tot]=tau_end;
class_test(index_switch_tot != interval_number,
ppt->error_message,
"most probably two approximation switching time were found to be equal, which cannot be handled\n");
/** - store each approximation in chronological order */
for (index_switch=1; index_switch<interval_number; index_switch++) {
class_call(perturb_approximations(ppr,
pba,
pth,
ppt,
index_md,
k,
0.5*(interval_limit[index_switch]+interval_limit[index_switch+1]),
ppw),
ppt->error_message,
ppt->error_message);
for (index_ap=0; index_ap<ppw->ap_size; index_ap++) {
interval_approx[index_switch][index_ap]=ppw->approx[index_ap];
/* check here that approximation does not go backward (remember
that by definition the value of an approximation can only
increase) */
class_test(interval_approx[index_switch][index_ap] < interval_approx[index_switch-1][index_ap],
ppt->error_message,
"The approximation with label %d is not defined correctly: it goes backward (from %d to %d) for k=%e and between tau=%e and %e; this cannot be handled\n",
index_ap,
interval_approx[index_switch-1][index_ap],
interval_approx[index_switch][index_ap],
k,
0.5*(interval_limit[index_switch-1]+interval_limit[index_switch]),
0.5*(interval_limit[index_switch]+interval_limit[index_switch+1])
);
}
/* check here that more than one approximation is not switched on at a given time */
num_switching_at_given_time=0;
for (index_ap=0; index_ap<ppw->ap_size; index_ap++) {
if (interval_approx[index_switch][index_ap] != interval_approx[index_switch-1][index_ap])
num_switching_at_given_time++;
}
class_test(num_switching_at_given_time != 1,
ppt->error_message,
"for k=%e, at tau=%g, you switch %d approximations at the same time, this cannot be handled. Usually happens in two cases: triggers for different approximations coincide, or one approx is reversible\n",
k,
interval_limit[index_switch],
num_switching_at_given_time);
if (ppt->perturbations_verbose>2) {
if (_scalars_) {
if ((interval_approx[index_switch-1][ppw->index_ap_tca]==(int)tca_on) &&
(interval_approx[index_switch][ppw->index_ap_tca]==(int)tca_off))
fprintf(stdout,"Mode k=%e: will switch off tight-coupling approximation at tau=%e\n",k,interval_limit[index_switch]);
//fprintf(stderr,"Mode k=%e: will switch off tight-coupling approximation at tau=%e\n",k,interval_limit[index_switch]); //TBC
if ((interval_approx[index_switch-1][ppw->index_ap_rsa]==(int)rsa_off) &&
(interval_approx[index_switch][ppw->index_ap_rsa]==(int)rsa_on))
fprintf(stdout,"Mode k=%e: will switch on radiation streaming approximation at tau=%e\n",k,interval_limit[index_switch]);
if (pba->has_ur == _TRUE_) {
if ((interval_approx[index_switch-1][ppw->index_ap_ufa]==(int)ufa_off) &&
(interval_approx[index_switch][ppw->index_ap_ufa]==(int)ufa_on)) {
fprintf(stdout,"Mode k=%e: will switch on ur fluid approximation at tau=%e\n",k,interval_limit[index_switch]);
}
}
if (pba->has_ncdm == _TRUE_) {
if ((interval_approx[index_switch-1][ppw->index_ap_ncdmfa]==(int)ncdmfa_off) &&
(interval_approx[index_switch][ppw->index_ap_ncdmfa]==(int)ncdmfa_on)) {
fprintf(stdout,"Mode k=%e: will switch on ncdm fluid approximation at tau=%e\n",k,interval_limit[index_switch]);
}
}
}
if (_tensors_) {
if ((interval_approx[index_switch-1][ppw->index_ap_tca]==(int)tca_on) &&
(interval_approx[index_switch][ppw->index_ap_tca]==(int)tca_off))
fprintf(stdout,"Mode k=%e: will switch off tight-coupling approximation for tensors at tau=%e\n",k,interval_limit[index_switch]);
if ((interval_approx[index_switch-1][ppw->index_ap_rsa]==(int)rsa_off) &&
(interval_approx[index_switch][ppw->index_ap_rsa]==(int)rsa_on))
fprintf(stdout,"Mode k=%e: will switch on radiation streaming approximation for tensors at tau=%e\n",k,interval_limit[index_switch]);
}
}
}
free(unsorted_tau_switch);
class_call(perturb_approximations(ppr,
pba,
pth,
ppt,
index_md,
k,
tau_end,
ppw),
ppt->error_message,
ppt->error_message);
}
return _SUCCESS_;
}
/**
* Initialize the field '-->pv' of a perturb_workspace structure, which
* is a perturb_vector structure. This structure contains indices and
* values of all quantities which need to be integrated with respect
* to time (and only them: quantities fixed analytically or obeying
* constraint equations are NOT included in this vector). This routine
* distinguishes between two cases:
*
* --> the input pa_old is set to the NULL pointer:
*
* This happens when we start integrating over a new wavenumber and we
* want to set initial conditions for the perturbations. Then, it is
* assumed that ppw-->pv is not yet allocated. This routine allocates
* it, defines all indices, and then fills the vector ppw-->pv-->y with
* the initial conditions defined in perturb_initial_conditions.
*
* --> the input pa_old is not set to the NULL pointer and describes
* some set of approximations:
*
* This happens when we need to change approximation scheme while
* integrating over a given wavenumber. The new approximation
* described by ppw-->pa is then different from pa_old. Then, this
* routine allocates a new vector with a new size and new index
* values; it fills this vector with initial conditions taken from the
* previous vector passed as an input in ppw-->pv, and eventually with
* some analytic approximations for the new variables appearing at
* this time; then the new vector comes in replacement of the old one,
* which is freed.
*
* @param ppr Input: pointer to precision structure
* @param pba Input: pointer to background structure
* @param pth Input: pointer to the thermodynamics structure
* @param ppt Input: pointer to the perturbation structure
* @param index_md Input: index of mode under consideration (scalar/.../tensor)
* @param index_ic Input: index of initial condition under consideration (ad, iso...)
* @param k Input: wavenumber
* @param tau Input: conformal time
* @param ppw Input/Output: workspace containing in input the approximation scheme, the background/thermodynamics/metric quantities, and eventually the previous vector y; and in output the new vector y.
* @param pa_old Input: NULL is we need to set y to initial conditions for a new wavenumber; points towards a perturb_approximations if we want to switch of approximation.
* @return the error status
*/
int perturb_vector_init(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt,
int index_md,
int index_ic,
double k,
double tau,
struct perturb_workspace * ppw, /* ppw->pv unallocated if pa_old = NULL, allocated and filled otherwise */
int * pa_old
) {
/** Summary: */
/** - define local variables */
struct perturb_vector * ppv;
int index_pt;
int l;
int n_ncdm,index_q,ncdm_l_size;
double rho_plus_p_ncdm,q,q2,epsilon,a,factor;
/** - allocate a new perturb_vector structure to which ppw-->pv will point at the end of the routine */
class_alloc(ppv,sizeof(struct perturb_vector),ppt->error_message);
/** - initialize pointers to NULL (they will be allocated later if
needed), relevant for perturb_vector_free() */
ppv->l_max_ncdm = NULL;
ppv->q_size_ncdm = NULL;
/** - define all indices in this new vector (depends on approximation scheme, described by the input structure ppw-->pa) */
index_pt = 0;
if (_scalars_) {
/* reject inconsistent values of the number of mutipoles in photon temperature hierarchy */
class_test(ppr->l_max_g < 4,
ppt->error_message,
"ppr->l_max_g should be at least 4, i.e. we must integrate at least over photon density, velocity, shear, third and fourth momentum");
/* reject inconsistent values of the number of mutipoles in photon polarization hierarchy */
class_test(ppr->l_max_pol_g < 4,
ppt->error_message,
"ppr->l_max_pol_g should be at least 4");
/* reject inconsistent values of the number of mutipoles in decay radiation hierarchy */
if (pba->has_dr == _TRUE_) {
class_test(ppr->l_max_dr < 4,
ppt->error_message,
"ppr->l_max_dr should be at least 4, i.e. we must integrate at least over neutrino/relic density, velocity, shear, third and fourth momentum");
}
/* reject inconsistent values of the number of mutipoles in ultra relativistic neutrino hierarchy */
if (pba->has_ur == _TRUE_) {
class_test(ppr->l_max_ur < 4,
ppt->error_message,
"ppr->l_max_ur should be at least 4, i.e. we must integrate at least over neutrino/relic density, velocity, shear, third and fourth momentum");
}
/* photons */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) { /* if radiation streaming approximation is off */
/* temperature */
ppv->l_max_g = ppr->l_max_g;
class_define_index(ppv->index_pt_delta_g,_TRUE_,index_pt,1); /* photon density */
class_define_index(ppv->index_pt_theta_g,_TRUE_,index_pt,1); /* photon velocity */
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) {
class_define_index(ppv->index_pt_shear_g,_TRUE_,index_pt,1); /* photon shear */
class_define_index(ppv->index_pt_l3_g,_TRUE_,index_pt,ppv->l_max_g-2); /* higher momenta */
/* polarization */
ppv->l_max_pol_g = ppr->l_max_pol_g;
class_define_index(ppv->index_pt_pol0_g,_TRUE_,index_pt,1);
class_define_index(ppv->index_pt_pol1_g,_TRUE_,index_pt,1);
class_define_index(ppv->index_pt_pol2_g,_TRUE_,index_pt,1);
class_define_index(ppv->index_pt_pol3_g,_TRUE_,index_pt,ppv->l_max_pol_g-2);
}
}
/* baryons */
class_define_index(ppv->index_pt_delta_b,_TRUE_,index_pt,1); /* baryon density */
class_define_index(ppv->index_pt_theta_b,_TRUE_,index_pt,1); /* baryon velocity */
/* cdm */
class_define_index(ppv->index_pt_delta_cdm,pba->has_cdm,index_pt,1); /* cdm density */
class_define_index(ppv->index_pt_theta_cdm,pba->has_cdm && (ppt->gauge == newtonian),index_pt,1); /* cdm velocity */
/* dcdm */
class_define_index(ppv->index_pt_delta_dcdm,pba->has_dcdm,index_pt,1); /* dcdm density */
class_define_index(ppv->index_pt_theta_dcdm,pba->has_dcdm,index_pt,1); /* dcdm velocity */
/* ultra relativistic decay radiation */
if (pba->has_dr==_TRUE_) {
ppv->l_max_dr = ppr->l_max_dr;
class_define_index(ppv->index_pt_F0_dr,_TRUE_,index_pt,ppv->l_max_dr+1); /* all momenta in Boltzmann hierarchy */
}
/* fluid */
// class_define_index(ppv->index_pt_delta_fld,pba->has_fld,index_pt,1); /* fluid density */
// class_define_index(ppv->index_pt_theta_fld,pba->has_fld,index_pt,1); /* fluid velocity */
/* scalar field */
class_define_index(ppv->index_pt_phi_scf,pba->has_scf,index_pt,1); /* scalar field density */
class_define_index(ppv->index_pt_phi_prime_scf,pba->has_scf,index_pt,1); /* scalar field velocity */
/* perturbed recombination: the indices are defined once tca is off. */
if ( (ppt->has_perturbed_recombination == _TRUE_) && (ppw->approx[ppw->index_ap_tca] == (int)tca_off) ) {
class_define_index(ppv->index_pt_perturbed_recombination_delta_temp,_TRUE_,index_pt,1);
class_define_index(ppv->index_pt_perturbed_recombination_delta_chi,_TRUE_,index_pt,1);
}
/* ultra relativistic neutrinos */
if (pba->has_ur && (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off)) {
class_define_index(ppv->index_pt_delta_ur,_TRUE_,index_pt,1); /* density of ultra-relativistic neutrinos/relics */
class_define_index(ppv->index_pt_theta_ur,_TRUE_,index_pt,1); /* velocity of ultra-relativistic neutrinos/relics */
class_define_index(ppv->index_pt_shear_ur,_TRUE_,index_pt,1); /* shear of ultra-relativistic neutrinos/relics */
if (ppw->approx[ppw->index_ap_ufa] == (int)ufa_off) {
ppv->l_max_ur = ppr->l_max_ur;
class_define_index(ppv->index_pt_l3_ur,_TRUE_,index_pt,ppv->l_max_ur-2); /* additional momenta in Boltzmann hierarchy (beyond l=0,1,2,3) */
}
}
/* non-cold dark matter */
if (pba->has_ncdm == _TRUE_) {
ppv->index_pt_psi0_ncdm1 = index_pt; /* density of ultra-relativistic neutrinos/relics */
ppv->N_ncdm = pba->N_ncdm;
class_alloc(ppv->l_max_ncdm,ppv->N_ncdm*sizeof(double),ppt->error_message);
class_alloc(ppv->q_size_ncdm,ppv->N_ncdm*sizeof(double),ppt->error_message);
for(n_ncdm = 0; n_ncdm < pba->N_ncdm; n_ncdm++) {
// Set value of ppv->l_max_ncdm:
if(ppw->approx[ppw->index_ap_ncdmfa] == (int)ncdmfa_off) {
/* reject inconsistent values of the number of mutipoles in ultra relativistic neutrino hierarchy */
class_test(ppr->l_max_ncdm < 4,
ppt->error_message,
"ppr->l_max_ncdm=%d should be at least 4, i.e. we must integrate at least over first four momenta of non-cold dark matter perturbed phase-space distribution",n_ncdm);
//Copy value from precision parameter:
ppv->l_max_ncdm[n_ncdm] = ppr->l_max_ncdm;
ppv->q_size_ncdm[n_ncdm] = pba->q_size_ncdm[n_ncdm];
}
else {
// In the fluid approximation, hierarchy is cut at lmax = 2 and q dependence is integrated out:
ppv->l_max_ncdm[n_ncdm] = 2;
ppv->q_size_ncdm[n_ncdm] = 1;
}
index_pt += (ppv->l_max_ncdm[n_ncdm]+1)*ppv->q_size_ncdm[n_ncdm];
}
}
/* metric (only quantities to be integrated, not those obeying constraint equations) */
/* metric perturbation eta of synchronous gauge */
class_define_index(ppv->index_pt_eta,ppt->gauge == synchronous,index_pt,1);
/* metric perturbation phi of newtonian gauge ( we could fix it
using Einstein equations as a constraint equation for phi, but
integration is numerically more stable if we actually evolve
phi) */
class_define_index(ppv->index_pt_phi,ppt->gauge == newtonian,index_pt,1);
}
if (_vectors_) {
/* Vector baryon velocity: v_b^{(1)}. */
class_define_index(ppv->index_pt_theta_b,_TRUE_,index_pt,1);
/* eventually reject inconsistent values of the number of mutipoles in photon temperature hierarchy and polarization*/
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) { /* if radiation streaming approximation is off */
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) { /* if tight-coupling approximation is off */
ppv->l_max_g = ppr->l_max_g_ten;
class_define_index(ppv->index_pt_delta_g,_TRUE_,index_pt,1); /* photon density */
class_define_index(ppv->index_pt_theta_g,_TRUE_,index_pt,1); /* photon velocity */
class_define_index(ppv->index_pt_shear_g,_TRUE_,index_pt,1); /* photon shear */
class_define_index(ppv->index_pt_l3_g,_TRUE_,index_pt,ppv->l_max_g-2); /* photon l=3 */
ppv->l_max_pol_g = ppr->l_max_pol_g_ten;
class_define_index(ppv->index_pt_pol0_g,_TRUE_,index_pt,1); /* photon polarization, l=0 */
class_define_index(ppv->index_pt_pol1_g,_TRUE_,index_pt,1); /* photon polarization, l=1 */
class_define_index(ppv->index_pt_pol2_g,_TRUE_,index_pt,1); /* photon polarization, l=2 */
class_define_index(ppv->index_pt_pol3_g,_TRUE_,index_pt,ppv->l_max_pol_g-2); /* photon polarization, l=3 */
}
}
/** - (a) metric perturbations V or \f$ h_v \f$ depending on gauge */
if (ppt->gauge == synchronous) {
class_define_index(ppv->index_pt_hv_prime,_TRUE_,index_pt,1);
}
if (ppt->gauge == newtonian) {
class_define_index(ppv->index_pt_V,_TRUE_,index_pt,1);
}
}
if (_tensors_) {
/* reject inconsistent values of the number of mutipoles in photon temperature hierarchy */
class_test(ppr->l_max_g_ten < 4,
ppt->error_message,
"ppr->l_max_g_ten should be at least 4, i.e. we must integrate at least over photon density, velocity, shear, third momentum");
/* reject inconsistent values of the number of mutipoles in photon polarization hierarchy */
class_test(ppr->l_max_pol_g_ten < 4,
ppt->error_message,
"ppr->l_max_pol_g_ten should be at least 4");
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) { /* if radiation streaming approximation is off */
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) { /* if tight-coupling approximation is off */
ppv->l_max_g = ppr->l_max_g_ten;
class_define_index(ppv->index_pt_delta_g,_TRUE_,index_pt,1); /* photon density */
class_define_index(ppv->index_pt_theta_g,_TRUE_,index_pt,1); /* photon velocity */
class_define_index(ppv->index_pt_shear_g,_TRUE_,index_pt,1); /* photon shear */
class_define_index(ppv->index_pt_l3_g,_TRUE_,index_pt,ppv->l_max_g-2); /* photon l=3 */
ppv->l_max_pol_g = ppr->l_max_pol_g_ten;
class_define_index(ppv->index_pt_pol0_g,_TRUE_,index_pt,1); /* photon polarization, l=0 */
class_define_index(ppv->index_pt_pol1_g,_TRUE_,index_pt,1); /* photon polarization, l=1 */
class_define_index(ppv->index_pt_pol2_g,_TRUE_,index_pt,1); /* photon polarization, l=2 */
class_define_index(ppv->index_pt_pol3_g,_TRUE_,index_pt,ppv->l_max_pol_g-2); /* photon polarization, l=3 */
}
}
/* ultra relativistic neutrinos */
class_define_index(ppv->index_pt_delta_ur,ppt->evolve_tensor_ur,index_pt,1); /* ur density */
class_define_index(ppv->index_pt_theta_ur,ppt->evolve_tensor_ur,index_pt,1); /* ur velocity */
class_define_index(ppv->index_pt_shear_ur,ppt->evolve_tensor_ur,index_pt,1); /* ur shear */
ppv->l_max_ur = ppr->l_max_ur;
class_define_index(ppv->index_pt_l3_ur,ppt->evolve_tensor_ur,index_pt,ppv->l_max_ur-2); /* additional momenta in Boltzmann hierarchy (beyond l=0,1,2,3) */
if (ppt->evolve_tensor_ncdm == _TRUE_) {
ppv->index_pt_psi0_ncdm1 = index_pt;
ppv->N_ncdm = pba->N_ncdm;
class_alloc(ppv->l_max_ncdm,ppv->N_ncdm*sizeof(double),ppt->error_message);
class_alloc(ppv->q_size_ncdm,ppv->N_ncdm*sizeof(double),ppt->error_message);
for(n_ncdm = 0; n_ncdm < pba->N_ncdm; n_ncdm++) {
// Set value of ppv->l_max_ncdm:
class_test(ppr->l_max_ncdm < 4,
ppt->error_message,
"ppr->l_max_ncdm=%d should be at least 4, i.e. we must integrate at least over first four momenta of non-cold dark matter perturbed phase-space distribution",n_ncdm);
//Copy value from precision parameter:
ppv->l_max_ncdm[n_ncdm] = ppr->l_max_ncdm;
ppv->q_size_ncdm[n_ncdm] = pba->q_size_ncdm[n_ncdm];
index_pt += (ppv->l_max_ncdm[n_ncdm]+1)*ppv->q_size_ncdm[n_ncdm];
}
}
/** - (b) metric perturbation h is a propagating degree of freedom, so h and hdot are included
in the vector of ordinary perturbations, no in that of metric perturbations */
class_define_index(ppv->index_pt_gw,_TRUE_,index_pt,1); /* tensor metric perturbation h (gravitational waves) */
class_define_index(ppv->index_pt_gwdot,_TRUE_,index_pt,1); /* its time-derivative */
}
ppv->pt_size = index_pt;
/** - allocate vectors for storing the values of all these
quantities and their time-derivatives at a given time */
class_calloc(ppv->y,ppv->pt_size,sizeof(double),ppt->error_message);
class_alloc(ppv->dy,ppv->pt_size*sizeof(double),ppt->error_message);
class_alloc(ppv->used_in_sources,ppv->pt_size*sizeof(int),ppt->error_message);
/** - specify which perturbations are needed in the evaluation of source terms */
/* take all of them by default */
for (index_pt=0; index_pt<ppv->pt_size; index_pt++)
ppv->used_in_sources[index_pt] = _TRUE_;
/* indicate which ones are not needed (this is just for saving time,
omitting perturbations in this list will not change the
results!) */
if (_scalars_) {
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) {
/* we don't need temperature multipoles above l=2 (but they are
defined only when rsa and tca are off) */
for (index_pt=ppv->index_pt_l3_g; index_pt <= ppv->index_pt_delta_g+ppv->l_max_g; index_pt++)
ppv->used_in_sources[index_pt]=_FALSE_;
/* for polarization, we only need l=0,2 (but l =1,3, ... are
defined only when rsa and tca are off) */
ppv->used_in_sources[ppv->index_pt_pol1_g]=_FALSE_;
for (index_pt=ppv->index_pt_pol3_g; index_pt <= ppv->index_pt_pol0_g+ppv->l_max_pol_g; index_pt++)
ppv->used_in_sources[index_pt]=_FALSE_;
}
}
if (pba->has_ur == _TRUE_) {
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
if (ppw->approx[ppw->index_ap_ufa] == (int)ufa_off) {
/* we don't need ur multipoles above l=2 (but they are
defined only when rsa and ufa are off) */
for (index_pt=ppv->index_pt_l3_ur; index_pt <= ppv->index_pt_delta_ur+ppv->l_max_ur; index_pt++)
ppv->used_in_sources[index_pt]=_FALSE_;
}
}
}
if (pba->has_ncdm == _TRUE_) {
/* we don't need ncdm multipoles above l=2 (but they are
defined only when ncdmfa is off) */
index_pt = ppv->index_pt_psi0_ncdm1;
for(n_ncdm = 0; n_ncdm < ppv-> N_ncdm; n_ncdm++) {
for(index_q=0; index_q < ppv->q_size_ncdm[n_ncdm]; index_q++) {
for(l=0; l<=ppv->l_max_ncdm[n_ncdm]; l++) {
if (l>2) ppv->used_in_sources[index_pt]=_FALSE_;
index_pt++;
}
}
}
}
}
if (_tensors_) {
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) { /* if radiation streaming approximation is off */
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) {
/* we don't need temperature multipoles above except l=0,2,4 */
ppv->used_in_sources[ppv->index_pt_theta_g]=_FALSE_;
ppv->used_in_sources[ppv->index_pt_l3_g]=_FALSE_;
for (index_pt=ppv->index_pt_delta_g+5; index_pt <= ppv->index_pt_delta_g+ppv->l_max_g; index_pt++)
ppv->used_in_sources[index_pt]=_FALSE_;
/* same for polarization, we only need l=0,2,4 */
ppv->used_in_sources[ppv->index_pt_pol1_g]=_FALSE_;
ppv->used_in_sources[ppv->index_pt_pol3_g]=_FALSE_;
for (index_pt=ppv->index_pt_pol0_g+5; index_pt <= ppv->index_pt_pol0_g+ppv->l_max_pol_g; index_pt++)
ppv->used_in_sources[index_pt]=_FALSE_;
}
}
/* we need h' but not h */
ppv->used_in_sources[ppv->index_pt_gw]=_FALSE_;
}
/** - case of setting initial conditions for a new wavenumber */
if (pa_old == NULL) {
if (ppt->perturbations_verbose>2)
fprintf(stdout,"Mode k=%e: initializing vector at tau=%e\n",k,tau);
if (_scalars_) {
/** - --> (a) check that current approximation scheme is consistent
with initial conditions */
class_test(ppw->approx[ppw->index_ap_rsa] == (int)rsa_on,
ppt->error_message,
"scalar initial conditions assume radiation streaming approximation turned off");
if (pba->has_ur == _TRUE_) {
class_test(ppw->approx[ppw->index_ap_ufa] == (int)ufa_on,
ppt->error_message,
"scalar initial conditions assume ur fluid approximation turned off");
}
if (pba->has_ncdm == _TRUE_) {
class_test(ppw->approx[ppw->index_ap_ncdmfa] == (int)ncdmfa_on,
ppt->error_message,
"scalar initial conditions assume ncdm fluid approximation turned off");
}
class_test(ppw->approx[ppw->index_ap_tca] == (int)tca_off,
ppt->error_message,
"scalar initial conditions assume tight-coupling approximation turned on");
}
if (_tensors_) {
class_test(ppw->approx[ppw->index_ap_tca] == (int)tca_off,
ppt->error_message,
"tensor initial conditions assume tight-coupling approximation turned on");
class_test(ppw->approx[ppw->index_ap_rsa] == (int)rsa_on,
ppt->error_message,
"tensor initial conditions assume radiation streaming approximation turned off");
}
/** - --> (b) let ppw-->pv points towards the perturb_vector structure
that we just created */
ppw->pv = ppv;
/** - --> (c) fill the vector ppw-->pv-->y with appropriate initial conditions */
class_call(perturb_initial_conditions(ppr,
pba,
ppt,
index_md,
index_ic,
k,
tau,
ppw),
ppt->error_message,
ppt->error_message);
}
/** - case of switching approximation while a wavenumber is being integrated */
else {
/** - --> (a) for the scalar mode: */
if (_scalars_) {
/** - ---> (a.1.) check that the change of approximation scheme makes
sense (note: before calling this routine there is already a
check that we wish to change only one approximation flag at
a time) */
class_test((pa_old[ppw->index_ap_tca] == (int)tca_off) && (ppw->approx[ppw->index_ap_tca] == (int)tca_on),
ppt->error_message,
"at tau=%g: the tight-coupling approximation can be switched off, not on",tau);
/** - ---> (a.2.) some variables (b, cdm, fld, ...) are not affected by
any approximation. They need to be reconducted whatever
the approximation switching is. We treat them here. Below
we will treat other variables case by case. */
ppv->y[ppv->index_pt_delta_b] =
ppw->pv->y[ppw->pv->index_pt_delta_b];
ppv->y[ppv->index_pt_theta_b] =
ppw->pv->y[ppw->pv->index_pt_theta_b];
if (pba->has_cdm == _TRUE_) {
ppv->y[ppv->index_pt_delta_cdm] =
ppw->pv->y[ppw->pv->index_pt_delta_cdm];
if (ppt->gauge == newtonian) {
ppv->y[ppv->index_pt_theta_cdm] =
ppw->pv->y[ppw->pv->index_pt_theta_cdm];
}
}
if (pba->has_dcdm == _TRUE_) {
ppv->y[ppv->index_pt_delta_dcdm] =
ppw->pv->y[ppw->pv->index_pt_delta_dcdm];
ppv->y[ppv->index_pt_theta_dcdm] =
ppw->pv->y[ppw->pv->index_pt_theta_dcdm];
}
if (pba->has_dr == _TRUE_) {
for (l=0; l <= ppv->l_max_dr; l++)
ppv->y[ppv->index_pt_F0_dr+l] =
ppw->pv->y[ppw->pv->index_pt_F0_dr+l];
}
/* if (pba->has_fld == _TRUE_) {*/
if ( 0 ) { // commented out so that no dark energy perturbations are included
ppv->y[ppv->index_pt_delta_fld] =
ppw->pv->y[ppw->pv->index_pt_delta_fld];
ppv->y[ppv->index_pt_theta_fld] =
ppw->pv->y[ppw->pv->index_pt_theta_fld];
}
if (pba->has_scf == _TRUE_) {
ppv->y[ppv->index_pt_phi_scf] =
ppw->pv->y[ppw->pv->index_pt_phi_scf];
ppv->y[ppv->index_pt_phi_prime_scf] =
ppw->pv->y[ppw->pv->index_pt_phi_prime_scf];
}
if (ppt->gauge == synchronous)
ppv->y[ppv->index_pt_eta] =
ppw->pv->y[ppw->pv->index_pt_eta];
if (ppt->gauge == newtonian)
ppv->y[ppv->index_pt_phi] =
ppw->pv->y[ppw->pv->index_pt_phi];
/* -- case of switching off tight coupling
approximation. Provide correct initial conditions to new set
of variables */
if ((pa_old[ppw->index_ap_tca] == (int)tca_on) && (ppw->approx[ppw->index_ap_tca] == (int)tca_off)) {
if (ppt->perturbations_verbose>2)
fprintf(stdout,"Mode k=%e: switch off tight-coupling approximation at tau=%e\n",k,tau);
ppv->y[ppv->index_pt_delta_g] =
ppw->pv->y[ppw->pv->index_pt_delta_g];
ppv->y[ppv->index_pt_theta_g] =
ppw->pv->y[ppw->pv->index_pt_theta_g];
/* tight-coupling approximation for shear_g (previously
computed in perturb_derivs: perturb_derivs is always
called at the end of generic_evolver, in order to update
all quantities in ppw to the time at which the
approximation is switched off) */
ppv->y[ppv->index_pt_shear_g] = ppw->tca_shear_g;
ppv->y[ppv->index_pt_l3_g] = 6./7.*k/ppw->pvecthermo[pth->index_th_dkappa]*ppw->s_l[3]*ppv->y[ppv->index_pt_shear_g]; /* second-order tight-coupling approximation for l=3 */
ppv->y[ppv->index_pt_pol0_g] = 2.5*ppv->y[ppv->index_pt_shear_g]; /* first-order tight-coupling approximation for polarization, l=0 */
ppv->y[ppv->index_pt_pol1_g] = k/ppw->pvecthermo[pth->index_th_dkappa]*(5.-2.*ppw->s_l[2])/6.*ppv->y[ppv->index_pt_shear_g]; /* second-order tight-coupling approximation for polarization, l=1 */
ppv->y[ppv->index_pt_pol2_g] = 0.5*ppv->y[ppv->index_pt_shear_g]; /* first-order tight-coupling approximation for polarization, l=2 */
ppv->y[ppv->index_pt_pol3_g] = k/ppw->pvecthermo[pth->index_th_dkappa]*3.*ppw->s_l[3]/14.*ppv->y[ppv->index_pt_shear_g]; /* second-order tight-coupling approximation for polarization, l=3 */
if (pba->has_ur == _TRUE_) {
ppv->y[ppv->index_pt_delta_ur] =
ppw->pv->y[ppw->pv->index_pt_delta_ur];
ppv->y[ppv->index_pt_theta_ur] =
ppw->pv->y[ppw->pv->index_pt_theta_ur];
ppv->y[ppv->index_pt_shear_ur] =
ppw->pv->y[ppw->pv->index_pt_shear_ur];
if (ppw->approx[ppw->index_ap_ufa] == (int)ufa_off) {
ppv->y[ppv->index_pt_l3_ur] =
ppw->pv->y[ppw->pv->index_pt_l3_ur];
for (l=4; l <= ppv->l_max_ur; l++)
ppv->y[ppv->index_pt_delta_ur+l] =
ppw->pv->y[ppw->pv->index_pt_delta_ur+l];
}
}
if (pba->has_ncdm == _TRUE_) {
index_pt = 0;
for(n_ncdm = 0; n_ncdm < ppv->N_ncdm; n_ncdm++) {
for(index_q=0; index_q < ppv->q_size_ncdm[n_ncdm]; index_q++) {
for(l=0; l<=ppv->l_max_ncdm[n_ncdm]; l++) {
// This is correct with or without ncdmfa, since ppv->lmax_ncdm is set accordingly.
ppv->y[ppv->index_pt_psi0_ncdm1+index_pt] =
ppw->pv->y[ppw->pv->index_pt_psi0_ncdm1+index_pt];
index_pt++;
}
}
}
}
/* perturbed recombination */
/* the initial conditions are set when tca is switched off (current block) */
if (ppt->has_perturbed_recombination == _TRUE_) {
ppv->y[ppv->index_pt_perturbed_recombination_delta_temp] = 1./3.*ppv->y[ppw->pv->index_pt_delta_b];
ppv->y[ppv->index_pt_perturbed_recombination_delta_chi] =0.;
}
} // end of block tca ON -> tca OFF
/* perturbed recombination */
/* For any other transition in the approximation scheme, we should just copy the value of the perturbations, provided tca is already off (otherwise the indices are not yet allocated). For instance, we do not want to copy the values in the (k,tau) region where both UFA and TCA are engaged.*/
if ((ppt->has_perturbed_recombination == _TRUE_)&&(pa_old[ppw->index_ap_tca]==(int)tca_off)) {
ppv->y[ppv->index_pt_perturbed_recombination_delta_temp] =
ppw->pv->y[ppw->pv->index_pt_perturbed_recombination_delta_temp];
ppv->y[ppv->index_pt_perturbed_recombination_delta_chi] =
ppw->pv->y[ppw->pv->index_pt_perturbed_recombination_delta_chi];
}
/* -- case of switching on radiation streaming
approximation. Provide correct initial conditions to new set
of variables */
if ((pa_old[ppw->index_ap_rsa] == (int)rsa_off) && (ppw->approx[ppw->index_ap_rsa] == (int)rsa_on)) {
if (ppt->perturbations_verbose>2)
fprintf(stdout,"Mode k=%e: switch on radiation streaming approximation at tau=%e with Omega_r=%g\n",k,tau,ppw->pvecback[pba->index_bg_Omega_r]);
if (pba->has_ncdm == _TRUE_) {
index_pt = 0;
for(n_ncdm = 0; n_ncdm < ppv->N_ncdm; n_ncdm++) {
for(index_q=0; index_q < ppv->q_size_ncdm[n_ncdm]; index_q++) {
for(l=0; l<=ppv->l_max_ncdm[n_ncdm]; l++) {
ppv->y[ppv->index_pt_psi0_ncdm1+index_pt] =
ppw->pv->y[ppw->pv->index_pt_psi0_ncdm1+index_pt];
index_pt++;
}
}
}
}
}
/* -- case of switching on ur fluid
approximation. Provide correct initial conditions to new set
of variables */
if (pba->has_ur == _TRUE_) {
if ((pa_old[ppw->index_ap_ufa] == (int)ufa_off) && (ppw->approx[ppw->index_ap_ufa] == (int)ufa_on)) {
if (ppt->perturbations_verbose>2)
fprintf(stdout,"Mode k=%e: switch on ur fluid approximation at tau=%e\n",k,tau);
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
ppv->y[ppv->index_pt_delta_g] =
ppw->pv->y[ppw->pv->index_pt_delta_g];
ppv->y[ppv->index_pt_theta_g] =
ppw->pv->y[ppw->pv->index_pt_theta_g];
}
if ((ppw->approx[ppw->index_ap_tca] == (int)tca_off) && (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off)) {
ppv->y[ppv->index_pt_shear_g] =
ppw->pv->y[ppw->pv->index_pt_shear_g];
ppv->y[ppv->index_pt_l3_g] =
ppw->pv->y[ppw->pv->index_pt_l3_g];
for (l = 4; l <= ppw->pv->l_max_g; l++) {
ppv->y[ppv->index_pt_delta_g+l] =
ppw->pv->y[ppw->pv->index_pt_delta_g+l];
}
ppv->y[ppv->index_pt_pol0_g] =
ppw->pv->y[ppw->pv->index_pt_pol0_g];
ppv->y[ppv->index_pt_pol1_g] =
ppw->pv->y[ppw->pv->index_pt_pol1_g];
ppv->y[ppv->index_pt_pol2_g] =
ppw->pv->y[ppw->pv->index_pt_pol2_g];
ppv->y[ppv->index_pt_pol3_g] =
ppw->pv->y[ppw->pv->index_pt_pol3_g];
for (l = 4; l <= ppw->pv->l_max_pol_g; l++) {
ppv->y[ppv->index_pt_pol0_g+l] =
ppw->pv->y[ppw->pv->index_pt_pol0_g+l];
}
}
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
ppv->y[ppv->index_pt_delta_ur] =
ppw->pv->y[ppw->pv->index_pt_delta_ur];
ppv->y[ppv->index_pt_theta_ur] =
ppw->pv->y[ppw->pv->index_pt_theta_ur];
ppv->y[ppv->index_pt_shear_ur] =
ppw->pv->y[ppw->pv->index_pt_shear_ur];
}
if (pba->has_ncdm == _TRUE_) {
index_pt = 0;
for(n_ncdm = 0; n_ncdm < ppv->N_ncdm; n_ncdm++) {
for(index_q=0; index_q < ppv->q_size_ncdm[n_ncdm]; index_q++) {
for(l=0; l<=ppv->l_max_ncdm[n_ncdm]; l++) {
/* This is correct even when ncdmfa == off, since ppv->l_max_ncdm and
ppv->q_size_ncdm is updated.*/
ppv->y[ppv->index_pt_psi0_ncdm1+index_pt] =
ppw->pv->y[ppw->pv->index_pt_psi0_ncdm1+index_pt];
index_pt++;
}
}
}
}
}
}
/* -- case of switching on ncdm fluid
approximation. Provide correct initial conditions to new set
of variables */
if (pba->has_ncdm == _TRUE_) {
if ((pa_old[ppw->index_ap_ncdmfa] == (int)ncdmfa_off) && (ppw->approx[ppw->index_ap_ncdmfa] == (int)ncdmfa_on)) {
if (ppt->perturbations_verbose>2)
fprintf(stdout,"Mode k=%e: switch on ncdm fluid approximation at tau=%e\n",k,tau);
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
ppv->y[ppv->index_pt_delta_g] =
ppw->pv->y[ppw->pv->index_pt_delta_g];
ppv->y[ppv->index_pt_theta_g] =
ppw->pv->y[ppw->pv->index_pt_theta_g];
}
if ((ppw->approx[ppw->index_ap_tca] == (int)tca_off) && (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off)) {
ppv->y[ppv->index_pt_shear_g] =
ppw->pv->y[ppw->pv->index_pt_shear_g];
ppv->y[ppv->index_pt_l3_g] =
ppw->pv->y[ppw->pv->index_pt_l3_g];
for (l = 4; l <= ppw->pv->l_max_g; l++) {
ppv->y[ppv->index_pt_delta_g+l] =
ppw->pv->y[ppw->pv->index_pt_delta_g+l];
}
ppv->y[ppv->index_pt_pol0_g] =
ppw->pv->y[ppw->pv->index_pt_pol0_g];
ppv->y[ppv->index_pt_pol1_g] =
ppw->pv->y[ppw->pv->index_pt_pol1_g];
ppv->y[ppv->index_pt_pol2_g] =
ppw->pv->y[ppw->pv->index_pt_pol2_g];
ppv->y[ppv->index_pt_pol3_g] =
ppw->pv->y[ppw->pv->index_pt_pol3_g];
for (l = 4; l <= ppw->pv->l_max_pol_g; l++) {
ppv->y[ppv->index_pt_pol0_g+l] =
ppw->pv->y[ppw->pv->index_pt_pol0_g+l];
}
}
if (pba->has_ur == _TRUE_) {
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
ppv->y[ppv->index_pt_delta_ur] =
ppw->pv->y[ppw->pv->index_pt_delta_ur];
ppv->y[ppv->index_pt_theta_ur] =
ppw->pv->y[ppw->pv->index_pt_theta_ur];
ppv->y[ppv->index_pt_shear_ur] =
ppw->pv->y[ppw->pv->index_pt_shear_ur];
if (ppw->approx[ppw->index_ap_ufa] == (int)ufa_off) {
ppv->y[ppv->index_pt_l3_ur] =
ppw->pv->y[ppw->pv->index_pt_l3_ur];
for (l=4; l <= ppv->l_max_ur; l++)
ppv->y[ppv->index_pt_delta_ur+l] =
ppw->pv->y[ppw->pv->index_pt_delta_ur+l];
}
}
}
a = ppw->pvecback[pba->index_bg_a];
index_pt = ppw->pv->index_pt_psi0_ncdm1;
for(n_ncdm = 0; n_ncdm < ppv->N_ncdm; n_ncdm++) {
// We are in the fluid approximation, so ncdm_l_size is always 3.
ncdm_l_size = ppv->l_max_ncdm[n_ncdm]+1;
rho_plus_p_ncdm = ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]+
ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm];
for(l=0; l<=2; l++) {
ppv->y[ppv->index_pt_psi0_ncdm1+ncdm_l_size*n_ncdm+l] = 0.0;
}
factor = pba->factor_ncdm[n_ncdm]*pow(pba->a_today/a,4);
for(index_q=0; index_q < ppw->pv->q_size_ncdm[n_ncdm]; index_q++) {
// Integrate over distributions:
q = pba->q_ncdm[n_ncdm][index_q];
q2 = q*q;
epsilon = sqrt(q2+a*a*pba->M_ncdm[n_ncdm]*pba->M_ncdm[n_ncdm]);
ppv->y[ppv->index_pt_psi0_ncdm1+ncdm_l_size*n_ncdm] +=
pba->w_ncdm[n_ncdm][index_q]*q2*epsilon*
ppw->pv->y[index_pt];
ppv->y[ppv->index_pt_psi0_ncdm1+ncdm_l_size*n_ncdm+1] +=
pba->w_ncdm[n_ncdm][index_q]*q2*q*
ppw->pv->y[index_pt+1];
ppv->y[ppv->index_pt_psi0_ncdm1+ncdm_l_size*n_ncdm+2] +=
pba->w_ncdm[n_ncdm][index_q]*q2*q2/epsilon*
ppw->pv->y[index_pt+2];
//Jump to next momentum bin in ppw->pv->y:
index_pt += (ppw->pv->l_max_ncdm[n_ncdm]+1);
}
ppv->y[ppv->index_pt_psi0_ncdm1+ncdm_l_size*n_ncdm] *=factor/ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm];
ppv->y[ppv->index_pt_psi0_ncdm1+ncdm_l_size*n_ncdm+1] *=k*factor/rho_plus_p_ncdm;
ppv->y[ppv->index_pt_psi0_ncdm1+ncdm_l_size*n_ncdm+2] *=2.0/3.0*factor/rho_plus_p_ncdm;
}
}
}
}
/** - --> (b) for the vector mode */
if (_vectors_) {
/** - ---> (b.1.) check that the change of approximation scheme makes
sense (note: before calling this routine there is already a
check that we wish to change only one approximation flag at
a time) */
class_test((pa_old[ppw->index_ap_tca] == (int)tca_off) && (ppw->approx[ppw->index_ap_tca] == (int)tca_on),
ppt->error_message,
"at tau=%g: the tight-coupling approximation can be switched off, not on",tau);
/** - ---> (b.2.) some variables (gw, gwdot, ...) are not affected by
any approximation. They need to be reconducted whatever
the approximation switching is. We treat them here. Below
we will treat other variables case by case. */
if (ppt->gauge == synchronous) {
ppv->y[ppv->index_pt_hv_prime] =
ppw->pv->y[ppw->pv->index_pt_hv_prime];
}
if (ppt->gauge == newtonian) {
ppv->y[ppv->index_pt_V] =
ppw->pv->y[ppw->pv->index_pt_V];
}
ppv->y[ppv->index_pt_theta_b] =
ppw->pv->y[ppw->pv->index_pt_theta_b];
/* -- case of switching off tight coupling
approximation. Provide correct initial conditions to new set
of variables */
if ((pa_old[ppw->index_ap_tca] == (int)tca_on) && (ppw->approx[ppw->index_ap_tca] == (int)tca_off)) {
if (ppt->perturbations_verbose>2)
fprintf(stdout,"Mode k=%e: switch off tight-coupling approximation at tau=%e\n",k,tau);
ppv->y[ppv->index_pt_delta_g] = 0.0; //TBC
//-4./3.*ppw->pv->y[ppw->pv->index_pt_gwdot]/ppw->pvecthermo[pth->index_th_dkappa];
ppv->y[ppv->index_pt_pol0_g] = 0.0; //TBC
//1./3.*ppw->pv->y[ppw->pv->index_pt_gwdot]/ppw->pvecthermo[pth->index_th_dkappa];
}
/* -- case of switching on radiation streaming
approximation. Provide correct initial conditions to new set
of variables */
if ((pa_old[ppw->index_ap_rsa] == (int)rsa_off) && (ppw->approx[ppw->index_ap_rsa] == (int)rsa_on)) {
if (ppt->perturbations_verbose>2)
fprintf(stdout,"Mode k=%e: switch on radiation streaming approximation at tau=%e with Omega_r=%g\n",k,tau,ppw->pvecback[pba->index_bg_Omega_r]);
}
}
/** - --> (c) for the tensor mode */
if (_tensors_) {
/** - ---> (c.1.) check that the change of approximation scheme makes
sense (note: before calling this routine there is already a
check that we wish to change only one approximation flag at
a time) */
class_test((pa_old[ppw->index_ap_tca] == (int)tca_off) && (ppw->approx[ppw->index_ap_tca] == (int)tca_on),
ppt->error_message,
"at tau=%g: the tight-coupling approximation can be switched off, not on",tau);
/** - ---> (c.2.) some variables (gw, gwdot, ...) are not affected by
any approximation. They need to be reconducted whatever
the approximation switching is. We treat them here. Below
we will treat other variables case by case. */
ppv->y[ppv->index_pt_gw] =
ppw->pv->y[ppw->pv->index_pt_gw];
ppv->y[ppv->index_pt_gwdot] =
ppw->pv->y[ppw->pv->index_pt_gwdot];
if (ppt->evolve_tensor_ur == _TRUE_) {
/* For now, neutrinos go here. */
ppv->y[ppv->index_pt_delta_ur] =
ppw->pv->y[ppw->pv->index_pt_delta_ur];
ppv->y[ppv->index_pt_theta_ur] =
ppw->pv->y[ppw->pv->index_pt_theta_ur];
ppv->y[ppv->index_pt_shear_ur] =
ppw->pv->y[ppw->pv->index_pt_shear_ur];
ppv->y[ppv->index_pt_l3_ur] =
ppw->pv->y[ppw->pv->index_pt_l3_ur];
for (l=4; l <= ppv->l_max_ur; l++)
ppv->y[ppv->index_pt_delta_ur+l] =
ppw->pv->y[ppw->pv->index_pt_delta_ur+l];
}
if (ppt->evolve_tensor_ncdm == _TRUE_) {
index_pt = 0;
for(n_ncdm = 0; n_ncdm < ppv->N_ncdm; n_ncdm++) {
for(index_q=0; index_q < ppv->q_size_ncdm[n_ncdm]; index_q++) {
for(l=0; l<=ppv->l_max_ncdm[n_ncdm]; l++) {
// This is correct with or without ncdmfa, since ppv->lmax_ncdm is set accordingly.
ppv->y[ppv->index_pt_psi0_ncdm1+index_pt] =
ppw->pv->y[ppw->pv->index_pt_psi0_ncdm1+index_pt];
index_pt++;
}
}
}
}
/* -- case of switching off tight coupling
approximation. Provide correct initial conditions to new set
of variables */
if ((pa_old[ppw->index_ap_tca] == (int)tca_on) && (ppw->approx[ppw->index_ap_tca] == (int)tca_off)) {
if (ppt->perturbations_verbose>2)
fprintf(stdout,"Mode k=%e: switch off tight-coupling approximation at tau=%e\n",k,tau);
ppv->y[ppv->index_pt_delta_g] = -4./3.*ppw->pv->y[ppw->pv->index_pt_gwdot]/ppw->pvecthermo[pth->index_th_dkappa];
ppv->y[ppv->index_pt_pol0_g] = 1./3.*ppw->pv->y[ppw->pv->index_pt_gwdot]/ppw->pvecthermo[pth->index_th_dkappa];
}
/* -- case of switching on radiation streaming
approximation. Provide correct initial conditions to new set
of variables */
if ((pa_old[ppw->index_ap_rsa] == (int)rsa_off) && (ppw->approx[ppw->index_ap_rsa] == (int)rsa_on)) {
if (ppt->perturbations_verbose>2)
fprintf(stdout,"Mode k=%e: switch on radiation streaming approximation at tau=%e with Omega_r=%g\n",k,tau,ppw->pvecback[pba->index_bg_Omega_r]);
}
}
/** - --> (d) free the previous vector of perturbations */
class_call(perturb_vector_free(ppw->pv),
ppt->error_message,
ppt->error_message);
/** - --> (e) let ppw-->pv points towards the perturb_vector structure
that we just created */
ppw->pv = ppv;
}
return _SUCCESS_;
}
/**
* Free the perturb_vector structure.
*
* @param pv Input: pointer to perturb_vector structure to be freed
* @return the error status
*/
int perturb_vector_free(
struct perturb_vector * pv
) {
if (pv->l_max_ncdm != NULL) free(pv->l_max_ncdm);
if (pv->q_size_ncdm != NULL) free(pv->q_size_ncdm);
free(pv->y);
free(pv->dy);
free(pv->used_in_sources);
free(pv);
return _SUCCESS_;
}
/**
* For each mode, wavenumber and initial condition, this function
* initializes in the vector all values of perturbed variables (in a
* given gauge). It is assumed here that all values have previously been
* set to zero, only non-zero values are set here.
*
* @param ppr Input: pointer to precision structure
* @param pba Input: pointer to background structure
* @param ppt Input: pointer to the perturbation structure
* @param index_md Input: index of mode under consideration (scalar/.../tensor)
* @param index_ic Input: index of initial condition under consideration (ad, iso...)
* @param k Input: wavenumber
* @param tau Input: conformal time
* @param ppw Input/Output: workspace containing in input the approximation scheme, the background/thermodynamics/metric quantities, and eventually the previous vector y; and in output the new vector y.
* @return the error status
*/
int perturb_initial_conditions(struct precision * ppr,
struct background * pba,
struct perturbs * ppt,
int index_md,
int index_ic,
double k,
double tau,
struct perturb_workspace * ppw
) {
/** Summary: */
/** --> Declare local variables */
double a,a_prime_over_a;
double delta_ur=0.,theta_ur=0.,shear_ur=0.,l3_ur=0.,eta=0.,delta_cdm=0.,alpha, alpha_prime;
double delta_dr=0;
double q,epsilon,k2;
int index_q,n_ncdm,idx;
double rho_r,rho_m,rho_nu,rho_m_over_rho_r;
double fracnu,fracg,fracb,fraccdm,om;
double ktau_two,ktau_three;
double f_dr;
double delta_tot;
double velocity_tot;
double s2_squared;
/** --> For scalars */
if (_scalars_) {
/** - (a) compute relevant background quantities: compute rho_r,
rho_m, rho_nu (= all relativistic except photons), and their
ratio. */
class_call(background_at_tau(pba,
tau,
pba->normal_info,
pba->inter_normal,
&(ppw->last_index_back),
ppw->pvecback),
pba->error_message,
ppt->error_message);
a = ppw->pvecback[pba->index_bg_a];
a_prime_over_a = ppw->pvecback[pba->index_bg_H]*a;
/* 8piG/3 rho_r(t_i) */
rho_r = ppw->pvecback[pba->index_bg_rho_g];
/* 8piG/3 rho_m(t_i) */
rho_m = ppw->pvecback[pba->index_bg_rho_b];
/* 8piG/3 rho_nu(t_i) (all neutrinos and collisionless relics being relativistic at that time) */
rho_nu = 0.;
if (pba->has_cdm == _TRUE_) {
rho_m += ppw->pvecback[pba->index_bg_rho_cdm];
}
if (pba->has_dcdm == _TRUE_) {
rho_m += ppw->pvecback[pba->index_bg_rho_dcdm];
}
if (pba->has_dr == _TRUE_) {
rho_r += ppw->pvecback[pba->index_bg_rho_dr];
rho_nu += ppw->pvecback[pba->index_bg_rho_dr];
}
if (pba->has_ur == _TRUE_) {
rho_r += ppw->pvecback[pba->index_bg_rho_ur];
rho_nu += ppw->pvecback[pba->index_bg_rho_ur];
}
if (pba->has_ncdm == _TRUE_) {
for(n_ncdm=0; n_ncdm<pba->N_ncdm; n_ncdm++) {
rho_r += ppw->pvecback[pba->index_bg_rho_ncdm1 + n_ncdm];
rho_nu += ppw->pvecback[pba->index_bg_rho_ncdm1 + n_ncdm];
}
}
class_test(rho_r == 0.,
ppt->error_message,
"stop to avoid division by zero");
/* f_nu = Omega_nu(t_i) / Omega_r(t_i) */
fracnu = rho_nu/rho_r;
/* f_g = Omega_g(t_i) / Omega_r(t_i) */
fracg = ppw->pvecback[pba->index_bg_rho_g]/rho_r;
/* f_b = Omega_b(t_i) / Omega_m(t_i) */
fracb = ppw->pvecback[pba->index_bg_rho_b]/rho_m;
/* f_cdm = Omega_cdm(t_i) / Omega_m(t_i) */
fraccdm = 1.-fracb;
/* Omega_m(t_i) / Omega_r(t_i) */
rho_m_over_rho_r = rho_m/rho_r;
/* omega = Omega_m(t_i) a(t_i) H(t_i) / sqrt(Omega_r(t_i))
= Omega_m(t_0) a(t_0) H(t_0) / sqrt(Omega_r(t_0)) assuming rho_m in a-3 and rho_r in a^-4
= (8piG/3 rho_m(t_i)) a(t_i) / sqrt(8piG/3 rho_r(t_i)) in Mpc-1
This (a priori strange) parameter is the relevant one for expressing a
as a function of tau during radiation and matter domination (but not DE domination).
Indeed the exact solution of Friedmann when there is only radiation and matter in
the universe is
a = [H(t_0)^2 Omega_m(t_0) a(t_0)^3 / 4] x [tau^2 + 4 tau / omega]
*/
om = a*rho_m/sqrt(rho_r);
/* (k tau)^2, (k tau)^3 */
ktau_two=k*k*tau*tau;
ktau_three=k*tau*ktau_two;
/* curvature-dependent factors */
s2_squared = 1.-3.*pba->K/k/k;
/** - (b) starts by setting everything in synchronous gauge. If
another gauge is needed, we will perform a gauge
transformation below. */
/** - --> (b.1.) adiabatic */
if ((ppt->has_ad == _TRUE_) && (index_ic == ppt->index_ic_ad)) {
/* The following formulas are valid at leading order in
(k*tau) and (om*tau), and order zero in
tight-coupling. Identical to first order terms in CRS,
except for normalization (when ppr->curvature_ini=1, tau=1:
leads to factor 1/2 difference between CRS formulas with
beta1=0). Identical to CAMB when om set to zero in theta_g,
theta_ur, shear_ur, tau
In the non-flat case the relation R=eta is still valid
outside the horizon for adiabatic IC. Hence eta is still
set to ppr->curvature_ini at leading order. Factors s2
appear through the solution of Einstein equations and
equations of motion. */
/* photon density */
ppw->pv->y[ppw->pv->index_pt_delta_g] = - ktau_two/3. * (1.-om*tau/5.)
* ppr->curvature_ini * s2_squared;
/* photon velocity */
ppw->pv->y[ppw->pv->index_pt_theta_g] = - k*ktau_three/36. * (1.-3.*(1.+5.*fracb-fracnu)/20./(1.-fracnu)*om*tau)
* ppr->curvature_ini * s2_squared;
/* tighly-coupled baryons */
ppw->pv->y[ppw->pv->index_pt_delta_b] = 3./4.*ppw->pv->y[ppw->pv->index_pt_delta_g]; /* baryon density */
ppw->pv->y[ppw->pv->index_pt_theta_b] = ppw->pv->y[ppw->pv->index_pt_theta_g]; /* baryon velocity */
if (pba->has_cdm == _TRUE_) {
ppw->pv->y[ppw->pv->index_pt_delta_cdm] = 3./4.*ppw->pv->y[ppw->pv->index_pt_delta_g]; /* cdm density */
/* cdm velocity vanishes in the synchronous gauge */
}
if (pba->has_dcdm == _TRUE_) {
ppw->pv->y[ppw->pv->index_pt_delta_dcdm] = 3./4.*ppw->pv->y[ppw->pv->index_pt_delta_g]; /* dcdm density */
/* dcdm velocity velocity vanishes initially in the synchronous gauge */
}
/* fluid (assumes wa=0, if this is not the case the
fluid will catch anyway the attractor solution) */
/* if (pba->has_fld == _TRUE_) {*/
if ( 0 ) { // commented out so that no dark energy perturbations are included
ppw->pv->y[ppw->pv->index_pt_delta_fld] = - ktau_two/4.*(1.+pba->w0_fld+pba->wa_fld)*(4.-3.*pba->cs2_fld)/(4.-6.*(pba->w0_fld+pba->wa_fld)+3.*pba->cs2_fld) * ppr->curvature_ini * s2_squared; /* from 1004.5509 //TBC: curvature*/
ppw->pv->y[ppw->pv->index_pt_theta_fld] = - k*ktau_three/4.*pba->cs2_fld/(4.-6.*(pba->w0_fld+pba->wa_fld)+3.*pba->cs2_fld) * ppr->curvature_ini * s2_squared; /* from 1004.5509 //TBC:curvature*/
}
if (pba->has_scf == _TRUE_) {
/** - ---> Canonical field (solving for the perturbations):
* initial perturbations set to zero, they should reach the attractor soon enough.
* - ---> TODO: Incorporate the attractor IC from 1004.5509.
* delta_phi \f$ = -(a/k)^2/\phi'(\rho + p)\theta \f$,
* delta_phi_prime \f$ = a^2/\phi' \f$ (delta_rho_phi + V'delta_phi),
* and assume theta, delta_rho as for perfect fluid
* with \f$ c_s^2 = 1 \f$ and w = 1/3 (ASSUMES radiation TRACKING)
*/
ppw->pv->y[ppw->pv->index_pt_phi_scf] = 0.;
/* a*a/k/k/ppw->pvecback[pba->index_bg_phi_prime_scf]*k*ktau_three/4.*1./(4.-6.*(1./3.)+3.*1.) * (ppw->pvecback[pba->index_bg_rho_scf] + ppw->pvecback[pba->index_bg_p_scf])* ppr->curvature_ini * s2_squared; */
ppw->pv->y[ppw->pv->index_pt_phi_prime_scf] = 0.;
/* delta_fld expression * rho_scf with the w = 1/3, c_s = 1
a*a/ppw->pvecback[pba->index_bg_phi_prime_scf]*( - ktau_two/4.*(1.+1./3.)*(4.-3.*1.)/(4.-6.*(1/3.)+3.*1.)*ppw->pvecback[pba->index_bg_rho_scf] - ppw->pvecback[pba->index_bg_dV_scf]*ppw->pv->y[ppw->pv->index_pt_phi_scf])* ppr->curvature_ini * s2_squared; */
}
/* all relativistic relics: ur, early ncdm, dr */
if ((pba->has_ur == _TRUE_) || (pba->has_ncdm == _TRUE_) || (pba->has_dr == _TRUE_)) {
delta_ur = ppw->pv->y[ppw->pv->index_pt_delta_g]; /* density of ultra-relativistic neutrinos/relics */
theta_ur = - k*ktau_three/36./(4.*fracnu+15.) * (4.*fracnu+11.+12.*s2_squared-3.*(8.*fracnu*fracnu+50.*fracnu+275.)/20./(2.*fracnu+15.)*tau*om) * ppr->curvature_ini * s2_squared; /* velocity of ultra-relativistic neutrinos/relics */ //TBC
shear_ur = ktau_two/(45.+12.*fracnu) * (3.*s2_squared-1.) * (1.+(4.*fracnu-5.)/4./(2.*fracnu+15.)*tau*om) * ppr->curvature_ini;//TBC /s2_squared; /* shear of ultra-relativistic neutrinos/relics */ //TBC:0
l3_ur = ktau_three*2./7./(12.*fracnu+45.)* ppr->curvature_ini;//TBC
if (pba->has_dr == _TRUE_) delta_dr = delta_ur;
}
/* synchronous metric perturbation eta */
//eta = ppr->curvature_ini * (1.-ktau_two/12./(15.+4.*fracnu)*(5.+4.*fracnu - (16.*fracnu*fracnu+280.*fracnu+325)/10./(2.*fracnu+15.)*tau*om)) / s2_squared;
//eta = ppr->curvature_ini * s2_squared * (1.-ktau_two/12./(15.+4.*fracnu)*(15.*s2_squared-10.+4.*s2_squared*fracnu - (16.*fracnu*fracnu+280.*fracnu+325)/10./(2.*fracnu+15.)*tau*om));
eta = ppr->curvature_ini * (1.-ktau_two/12./(15.+4.*fracnu)*(5.+4.*s2_squared*fracnu - (16.*fracnu*fracnu+280.*fracnu+325)/10./(2.*fracnu+15.)*tau*om));
}
/* isocurvature initial conditions taken from Bucher, Moodely,
Turok 99, with just a different normalization convention for
tau and the scale factor. [k tau] from BMT99 is left invariant
because it is the ratio [k/aH]. But [Omega_i,0 tau] from BMT99
must be replaced by [frac_i*om*tau/4]. Some doubts remain about
the niv formulas, that should be recheked at some point. We
also checked that for bi,cdi,nid, everything coincides exactly
with the CAMB formulas. */
/** - --> (b.2.) Cold dark matter Isocurvature */
if ((ppt->has_cdi == _TRUE_) && (index_ic == ppt->index_ic_cdi)) {
class_test(pba->has_cdm == _FALSE_,
ppt->error_message,
"not consistent to ask for CDI in absence of CDM!");
ppw->pv->y[ppw->pv->index_pt_delta_g] = ppr->entropy_ini*fraccdm*om*tau*(-2./3.+om*tau/4.);
ppw->pv->y[ppw->pv->index_pt_theta_g] = -ppr->entropy_ini*fraccdm*om*ktau_two/12.;
ppw->pv->y[ppw->pv->index_pt_delta_b] = 3./4.*ppw->pv->y[ppw->pv->index_pt_delta_g];
ppw->pv->y[ppw->pv->index_pt_theta_b] = ppw->pv->y[ppw->pv->index_pt_theta_g];
ppw->pv->y[ppw->pv->index_pt_delta_cdm] = ppr->entropy_ini+3./4.*ppw->pv->y[ppw->pv->index_pt_delta_g];
if ((pba->has_ur == _TRUE_) || (pba->has_ncdm == _TRUE_)) {
delta_ur = ppw->pv->y[ppw->pv->index_pt_delta_g];
theta_ur = ppw->pv->y[ppw->pv->index_pt_theta_g];
shear_ur = -ppr->entropy_ini*fraccdm*ktau_two*tau*om/6./(2.*fracnu+15.);
}
eta = -ppr->entropy_ini*fraccdm*om*tau*(1./6.-om*tau/16.);
}
/** - --> (b.3.) Baryon Isocurvature */
if ((ppt->has_bi == _TRUE_) && (index_ic == ppt->index_ic_bi)) {
ppw->pv->y[ppw->pv->index_pt_delta_g] = ppr->entropy_ini*fracb*om*tau*(-2./3.+om*tau/4.);
ppw->pv->y[ppw->pv->index_pt_theta_g] = -ppr->entropy_ini*fracb*om*ktau_two/12.;
ppw->pv->y[ppw->pv->index_pt_delta_b] = ppr->entropy_ini+3./4.*ppw->pv->y[ppw->pv->index_pt_delta_g];
ppw->pv->y[ppw->pv->index_pt_theta_b] = ppw->pv->y[ppw->pv->index_pt_theta_g];
if (pba->has_cdm == _TRUE_) {
ppw->pv->y[ppw->pv->index_pt_delta_cdm] = 3./4.*ppw->pv->y[ppw->pv->index_pt_delta_g];
}
if ((pba->has_ur == _TRUE_) || (pba->has_ncdm == _TRUE_)) {
delta_ur = ppw->pv->y[ppw->pv->index_pt_delta_g];
theta_ur = ppw->pv->y[ppw->pv->index_pt_theta_g];
shear_ur = -ppr->entropy_ini*fracb*ktau_two*tau*om/6./(2.*fracnu+15.);
}
eta = -ppr->entropy_ini*fracb*om*tau*(1./6.-om*tau/16.);
}
/** - --> (b.4.) Neutrino density Isocurvature */
if ((ppt->has_nid == _TRUE_) && (index_ic == ppt->index_ic_nid)) {
class_test((pba->has_ur == _FALSE_) && (pba->has_ncdm == _FALSE_),
ppt->error_message,
"not consistent to ask for NID in absence of ur or ncdm species!");
ppw->pv->y[ppw->pv->index_pt_delta_g] = ppr->entropy_ini*fracnu/fracg*(-1.+ktau_two/6.);
ppw->pv->y[ppw->pv->index_pt_theta_g] = -ppr->entropy_ini*fracnu/fracg*k*k*tau*(1./4.-fracb/fracg*3./16.*om*tau);
ppw->pv->y[ppw->pv->index_pt_delta_b] = ppr->entropy_ini*fracnu/fracg/8.*ktau_two;
ppw->pv->y[ppw->pv->index_pt_theta_b] = ppw->pv->y[ppw->pv->index_pt_theta_g];
if (pba->has_cdm == _TRUE_) {
ppw->pv->y[ppw->pv->index_pt_delta_cdm] = -ppr->entropy_ini*fracnu*fracb/fracg/80.*ktau_two*om*tau;
}
delta_ur = ppr->entropy_ini*(1.-ktau_two/6.);
theta_ur = ppr->entropy_ini*k*k*tau/4.;
shear_ur = ppr->entropy_ini*ktau_two/(4.*fracnu+15.)/2.;
eta = -ppr->entropy_ini*fracnu/(4.*fracnu+15.)/6.*ktau_two;
}
/** - --> (b.5.) Neutrino velocity Isocurvature */
if ((ppt->has_niv == _TRUE_) && (index_ic == ppt->index_ic_niv)) {
class_test((pba->has_ur == _FALSE_) && (pba->has_ncdm == _FALSE_),
ppt->error_message,
"not consistent to ask for NIV in absence of ur or ncdm species!");
ppw->pv->y[ppw->pv->index_pt_delta_g] = ppr->entropy_ini*k*tau*fracnu/fracg*
(1. - 3./16.*fracb*(2.+fracg)/fracg*om*tau); /* small diff wrt camb */
ppw->pv->y[ppw->pv->index_pt_theta_g] = ppr->entropy_ini*fracnu/fracg*3./4.*k*
(-1.+3./4.*fracb/fracg*om*tau+3./16.*om*om*tau*tau*fracb/fracg/fracg*(fracg-3.*fracb)+ktau_two/6.);
ppw->pv->y[ppw->pv->index_pt_delta_b] = 3./4.*ppw->pv->y[ppw->pv->index_pt_delta_g]; /* small diff wrt camb */
ppw->pv->y[ppw->pv->index_pt_theta_b] = ppw->pv->y[ppw->pv->index_pt_theta_g];
if (pba->has_cdm == _TRUE_) {
ppw->pv->y[ppw->pv->index_pt_delta_cdm] = -ppr->entropy_ini*9./64.*fracnu*fracb/fracg*k*tau*om*tau;
}
delta_ur = -ppr->entropy_ini*k*tau*(1.+3./16.*fracb*fracnu/fracg*om*tau); /* small diff wrt camb */
theta_ur = ppr->entropy_ini*3./4.*k*(1. - 1./6.*ktau_two*(4.*fracnu+9.)/(4.*fracnu+5.));
shear_ur = ppr->entropy_ini/(4.*fracnu+15.)*k*tau*(1. + 3.*om*tau*fracnu/(4.*fracnu+15.)); /* small diff wrt camb */
eta = ppr->entropy_ini*fracnu*k*tau*(-1./(4.*fracnu+5.) + (-3./64.*fracb/fracg+15./4./(4.*fracnu+15.)/(4.*fracnu+5.)*om*tau)); /* small diff wrt camb */
}
/** - (c) If the needed gauge is really the synchronous gauge, we need to affect the previously computed value of eta to the actual variable eta */
if (ppt->gauge == synchronous) {
ppw->pv->y[ppw->pv->index_pt_eta] = eta;
}
/** - (d) If the needed gauge is the newtonian gauge, we must compute alpha and then perform a gauge transformation for each variable */
if (ppt->gauge == newtonian) {
/* alpha is like in Ma & Bertschinger: (h'+6 eta')/(2k^2). We obtain it from the first two Einstein equations:
alpha = [eta + 3/2 (a'/a)^2 (delta_rho/rho_c) / k^2 /s_2^2 + 3/2 (a'/a)^3 3 ((rho+p)theta/rho_c) / k^4 / s_2^2] / (a'/a)
= [eta + 3/2 (a'/a)^2 / k^2 /s_2^2 {delta_tot + 3 (a'/a) /k^2 velocity_tot}] / (a'/a)
with
delta_tot = (delta_rho/rho_c)
= [rho_r delta_r + rho_m delta_m] / (rho_r + rho_m)
= [delta_r + (rho_m/rho_r) delta_m] / (1 + rho_m/rho_r)
= [(f_g delta_g + f_nu delta_nu) + (rho_m/rho_r) (f_b delta_b + f_cdm delta_cdm)] / (1 + rho_m/rho_r)
velocity_tot = ((rho+p)theta/rho_c)
= [(4/3) rho_r theta_r + rho_m theta_m] / (rho_r + rho_m)
= [(4/3) theta_r + (rho_m/rho_r) theta_m] / (1 + rho_m/rho_r)
= [(4/3) (f_g theta_g + f_nu theta_nu) + (rho_m/rho_r) (f_b delta_b + f_cdm 0)] / (1 + rho_m/rho_r)
*/
if (pba->has_cdm == _TRUE_)
delta_cdm = ppw->pv->y[ppw->pv->index_pt_delta_cdm];
else if (pba->has_dcdm == _TRUE_)
delta_cdm = ppw->pv->y[ppw->pv->index_pt_delta_dcdm];
else
delta_cdm=0.;
// note: if there are no neutrinos, fracnu, delta_ur and theta_ur below will consistently be zero.
delta_tot = (fracg*ppw->pv->y[ppw->pv->index_pt_delta_g]+fracnu*delta_ur+rho_m_over_rho_r*(fracb*ppw->pv->y[ppw->pv->index_pt_delta_b]+fraccdm*delta_cdm))/(1.+rho_m_over_rho_r);
velocity_tot = ((4./3.)*(fracg*ppw->pv->y[ppw->pv->index_pt_theta_g]+fracnu*theta_ur) + rho_m_over_rho_r*fracb*ppw->pv->y[ppw->pv->index_pt_theta_b])/(1.+rho_m_over_rho_r);
alpha = (eta + 3./2.*a_prime_over_a*a_prime_over_a/k/k/s2_squared*(delta_tot + 3.*a_prime_over_a/k/k*velocity_tot))/a_prime_over_a;
ppw->pv->y[ppw->pv->index_pt_phi] = eta - a_prime_over_a*alpha;
ppw->pv->y[ppw->pv->index_pt_delta_g] -= 4.*a_prime_over_a*alpha;
ppw->pv->y[ppw->pv->index_pt_theta_g] += k*k*alpha;
ppw->pv->y[ppw->pv->index_pt_delta_b] -= 3.*a_prime_over_a*alpha;
ppw->pv->y[ppw->pv->index_pt_theta_b] += k*k*alpha;
if (pba->has_cdm == _TRUE_) {
ppw->pv->y[ppw->pv->index_pt_delta_cdm] -= 3.*a_prime_over_a*alpha;
ppw->pv->y[ppw->pv->index_pt_theta_cdm] = k*k*alpha;
}
if (pba->has_dcdm == _TRUE_) {
ppw->pv->y[ppw->pv->index_pt_delta_dcdm] += (-3.*a_prime_over_a - a*pba->Gamma_dcdm)*alpha;
ppw->pv->y[ppw->pv->index_pt_theta_dcdm] = k*k*alpha;
}
/* fluid */
/* if (pba->has_fld == _TRUE_) {*/
if ( 0 ) { // commented out so that no dark energy perturbations are included
ppw->pv->y[ppw->pv->index_pt_delta_fld] += 3*(1.+pba->w0_fld+pba->wa_fld)*a_prime_over_a*alpha;
ppw->pv->y[ppw->pv->index_pt_theta_fld] += k*k*alpha;
}
/* scalar field: check */
if (pba->has_scf == _TRUE_) {
alpha_prime = 0.0;
/* - 2. * a_prime_over_a * alpha + eta
- 4.5 * (a2/k2) * ppw->rho_plus_p_shear; */
ppw->pv->y[ppw->pv->index_pt_phi_scf] += alpha*ppw->pvecback[pba->index_bg_phi_prime_scf];
ppw->pv->y[ppw->pv->index_pt_phi_prime_scf] +=
(-2.*a_prime_over_a*alpha*ppw->pvecback[pba->index_bg_phi_prime_scf]
-a*a* dV_scf(pba,ppw->pvecback[pba->index_bg_phi_scf])*alpha
+ppw->pvecback[pba->index_bg_phi_prime_scf]*alpha_prime);
}
if ((pba->has_ur == _TRUE_) || (pba->has_ncdm == _TRUE_) || (pba->has_dr == _TRUE_)) {
delta_ur -= 4.*a_prime_over_a*alpha;
theta_ur += k*k*alpha;
/* shear and l3 are gauge invariant */
if (pba->has_dr == _TRUE_)
delta_dr += (-4.*a_prime_over_a + a*pba->Gamma_dcdm*ppw->pvecback[pba->index_bg_rho_dcdm]/ppw->pvecback[pba->index_bg_rho_dr])*alpha;
}
} /* end of gauge transformation to newtonian gauge */
/** - (e) In any gauge, we should now implement the relativistic initial conditions in ur and ncdm variables */
if (pba->has_ur == _TRUE_) {
ppw->pv->y[ppw->pv->index_pt_delta_ur] = delta_ur;
ppw->pv->y[ppw->pv->index_pt_theta_ur] = theta_ur;
ppw->pv->y[ppw->pv->index_pt_shear_ur] = shear_ur;
ppw->pv->y[ppw->pv->index_pt_l3_ur] = l3_ur;
}
if (pba->has_ncdm == _TRUE_) {
idx = ppw->pv->index_pt_psi0_ncdm1;
for (n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
for (index_q=0; index_q < ppw->pv->q_size_ncdm[n_ncdm]; index_q++) {
q = pba->q_ncdm[n_ncdm][index_q];
epsilon = sqrt(q*q+a*a*pba->M_ncdm[n_ncdm]*pba->M_ncdm[n_ncdm]);
ppw->pv->y[idx] = -0.25 * delta_ur * pba->dlnf0_dlnq_ncdm[n_ncdm][index_q];
ppw->pv->y[idx+1] = -epsilon/3./q/k*theta_ur* pba->dlnf0_dlnq_ncdm[n_ncdm][index_q];
ppw->pv->y[idx+2] = -0.5 * shear_ur * pba->dlnf0_dlnq_ncdm[n_ncdm][index_q];
ppw->pv->y[idx+3] = -0.25 * l3_ur * pba->dlnf0_dlnq_ncdm[n_ncdm][index_q];
//Jump to next momentum bin:
idx += (ppw->pv->l_max_ncdm[n_ncdm]+1);
}
}
}
if (pba->has_dr == _TRUE_) {
f_dr = pow(pow(a/pba->a_today,2)/pba->H0,2)*ppw->pvecback[pba->index_bg_rho_dr];
ppw->pv->y[ppw->pv->index_pt_F0_dr] = delta_dr*f_dr;
ppw->pv->y[ppw->pv->index_pt_F0_dr+1] = 4./(3.*k)*theta_ur*f_dr;
ppw->pv->y[ppw->pv->index_pt_F0_dr+2] = 2.*shear_ur*f_dr;
ppw->pv->y[ppw->pv->index_pt_F0_dr+3] = l3_ur*f_dr;
}
}
/** --> For tensors */
if (_tensors_) {
/** tensor initial conditions take into account the fact that
scalar (resp. tensor) \f$ C_l\f$'s are related to the real space
power spectrum of curvature (resp. of the tensor part of
metric perturbations)
\f[ <R(x) R(x)> \ \ \sum_{ij} <h_{ij}(x) h^{ij}(x)> \f]
In momentum space it is conventional to use the modes R(k)
and h(k) where the quantity h obeying to the equation of
propagation:
\f[ h'' + \frac{2a'}{a} h + [k2+2K] h = 12\pi Ga2 (\rho+p) \sigma = 8\pi Ga2 p \pi \f]
and the power spectra in real space and momentum space are related through:
\f[ <R(x) R(x)> = \int \frac{dk}{k} \left[ \frac{k^3}{2\pi^2} <R(k)R(k)^*>\right] = \int \frac{dk}{k} \mathcal{P}_R(k) \f]
\f[\sum_{ij} <h_{ij}(x) h^{ij}(x)> = \frac{dk}{k} \left[ \frac{k^3}{2\pi^2} F\left(\frac{k^2}{K}\right) <h(k)h(k)^*>\right] = \int \frac{dk}{k} F\left(\frac{k^2}{K}\right) \mathcal{P}_h(k) \f]
where \f$ \mathcal{P}_R\f$ and \f$ \mathcal{P}_h\f$ are the dimensionless spectrum of
curvature R, and F is a function of k2/K, where K is the curvature
parameter. F is equal to one in flat space (K=0), and coming
from the contraction of the laplacian eigentensor \f$ Q_{ij}\f$ with
itself. We will give F explicitly below.
Similarly the scalar (S) and tensor (T) \f$ C_l\f$'s are given by
\f[ C_l^S = 4\pi \int \frac{dk}{k} [\Delta_l^S(q)]^2 \mathcal{P}_R(k) \f]
\f[ C_l^T = 4\pi \int \frac{dk}{k} [\Delta_l^T(q)]^2 F\left(\frac{k^2}{K}\right) \mathcal{P}_h(k) \f]
The usual convention for the tensor-to-scalar ratio
\f$ r = A_t / A_s \f$ at pivot scale
= 16 epsilon in single-field inflation
is such that for constant \f$ \mathcal{P}_R(k)\f$ and \f$ \mathcal{P}_h(k)\f$,
\f[ r = 6 \frac{\mathcal{P}_h(k)}{\mathcal{P}_R(k)} \f]
so
\f[ \mathcal{P}_h(k) = \frac{\mathcal{P}_R(k) r}{6} = \frac{A_s r}{6} = \frac{A_t}{6} \f]
A priori it would make sense to say that for a power-law
primordial spectrum there is an extra factor \f$ (k/k_{pivot})^{n_t} \f$
(and eventually running and so on and so forth...)
However it has been shown that the minimal models of
inflation in a negatively curved bubble lead to
\f$ \mathcal{P}_h(k)=\tanh(\pi*\nu/2)\f$. In open models it is customary to
define the tensor tilt in a non-flat universe as a deviation
from this behavior rather than from true scale-invariance in
the above sense.
Hence we should have
\f[ \mathcal{P}_h(k) = \frac{A_t}{6} [ \tanh(\pi*\frac{\nu}{2})] (k/k_{pivot})^{(n_t+...)}\f]
where the brackets \f[ [...] \f] mean "if K<0"
Then
\f[ C_l^T = 4\pi \int \frac{dk}{k} [\Delta_l^T(q)]^2 F\left(\frac{k^2}{K}\right) \frac{A_t}{6} [\tanh(\pi*\frac{\nu}{2})] (k/k_{pivot})^{(n_t+...)} \f]
In the code, it is then a matter of choice to write:
- In the primordial module: \f$ \mathcal{P}_h(k) = \frac{A_t}{6} \tanh{(\pi*\frac{\nu}{2})} (k/k^*)^{n_T}\f$
- In the perturbation initial conditions: \f$ h = 1\f$
- In the spectra module: \f$ C_l^T = \frac{4}{\pi} \int \frac{dk}{k} [\Delta_l^T(q)]^2 F\left(\frac{k^2}{K}\right) \mathcal{P}_h(k) \f$
or:
- In the primordial module: \f$ \mathcal{P}_h(k) = A_t (k/k^*)^{n_T} \f$
- In the perturbation initial conditions: \f$ h = \sqrt{[F\left(\frac{k^2}{K}\right) / 6] \tanh{(\pi*\frac{\nu}{2})}} \f$
- In the spectra module: \f$ C_l^T = \frac{4}{\pi} \int \frac{dk}{k} [\Delta_l^T(q)]^2 \mathcal{P}_h(k) \f$
We choose this last option, such that the primordial and
spectra module differ minimally in flat and non-flat space. Then we must impose
\f[ h = \sqrt{\left(\frac{F}{6}\right) \tanh{(\pi*\frac{\nu}{2})}} \f]
The factor F is found to be given by:
\f[ \sum_{ij}<h_{ij}(x) h^{ij}(x)> = \int \frac{dk}{k} \frac{k2(k2-K)}{(k2+3K)(k2+2K)} \mathcal{P}_h(k) \f]
Introducing as usual \f$ q2 = k2 - 3K \f$ and using qdq = kdk this gives
\f[ \sum_{ij}<h_{ij}(x) h^{ij}(x)> = \int \frac{dk}{k} \frac{(q2-3K)(q2-4K)}{q2(q2-K)} \mathcal{P}_h(k) \f]
Using qdq = kdk this is equivalent to
\f[ \sum_{ij}<h_{ij}(x) h^{ij}(x)> = \int \frac{dq}{q} \frac{q2-4K}{q2-K} \mathcal{P}_h(k(q)) \f]
Finally, introducing \f$ \nu=q/\sqrt{|K|}\f$ and sgnK=SIGN(k)\f$=\pm 1\f$, this could also be written
\f[ \sum_{ij}<h_{ij}(x) h^{ij}(x)> = \int \frac{d\nu}{\nu} \frac{(\nu2-4sgnK)}{(\nu2-sgnK)} \mathcal{P}_h(k(\nu)) \f]
Equation (43,44) of Hu, Seljak, White, Zaldarriaga is
equivalent to absorbing the above factor
\f$ (\nu2-4sgnK)/(\nu2-sgnK)\f$ in the definition of the primordial
spectrum. Since the initial condition should be written in terms of k rather than nu, they should read
\f[ h = \sqrt{ [k2(k2-K)]/[(k2+3K)(k2+2K)] / 6 * \tanh{(\pi*\frac{\nu}{2})} } \f]
We leave the freedom to multiply by an arbitrary number
ppr->gw_ini. The standard convention corresponding to
standard definitions of r, \f$ A_T\f$, \f$ n_T\f$ is however ppr->gw_ini=1.
*
*/
if (index_ic == ppt->index_ic_ten) {
ppw->pv->y[ppw->pv->index_pt_gw] = ppr->gw_ini/_SQRT6_;
}
k2 = k*k;
if (pba->sgnK != 0) {
ppw->pv->y[ppw->pv->index_pt_gw] *= sqrt(k2*(k2-pba->K)/(k2+3.*pba->K)/(k2+2.*pba->K));
}
if (pba->sgnK == -1) {
if (k*k+3*pba->K >= 0.) {
ppw->pv->y[ppw->pv->index_pt_gw] *= sqrt(tanh(_PI_/2.*sqrt(k2+3*pba->K)/sqrt(-pba->K)));
}
else {
ppw->pv->y[ppw->pv->index_pt_gw] = 0.;
}
}
}
return _SUCCESS_;
}
/**
* Evaluate background/thermodynamics at \f$ \tau \f$, infer useful flags / time scales for integrating perturbations.
*
* Evaluate background quantities at \f$ \tau \f$, as well as thermodynamics for scalar mode; infer useful flags and time scales for integrating the perturbations:
* - check whether tight-coupling approximation is needed.
* - check whether radiation (photons, massless neutrinos...) perturbations are needed.
* - choose step of integration: step = ppr->perturb_integration_stepsize * min_time_scale, where min_time_scale = smallest time scale involved in the equations. There are three time scales to compare:
* -# that of recombination, \f$ \tau_c = 1/\kappa' \f$
* -# Hubble time scale, \f$ \tau_h = a/a' \f$
* -# Fourier mode, \f$ \tau_k = 1/k \f$
*
* So, in general, min_time_scale = \f$ \min(\tau_c, \tau_b, \tau_h, \tau_k) \f$.
*
* However, if \f$ \tau_c \ll \tau_h \f$ and \f$ \tau_c
* \ll \tau_k \f$, we can use the tight-coupling regime for photons
* and write equations in such way that the time scale \f$
* \tau_c \f$ becomes irrelevant (no effective mass term in \f$
* 1/\tau_c \f$). Then, the smallest
* scale in the equations is only \f$ \min(\tau_h, \tau_k) \f$.
* In practise, it is sufficient to use only the condition \f$ \tau_c \ll \tau_h \f$.
*
* Also, if \f$ \rho_{matter} \gg \rho_{radiation} \f$ and \f$ k \gg
* aH \f$, we can switch off radiation perturbations (i.e. switch on
* the free-streaming approximation) and then the smallest scale is
* simply \f$ \tau_h \f$.
*
* @param ppr Input: pointer to precision structure
* @param pba Input: pointer to background structure
* @param pth Input: pointer to thermodynamics structure
* @param ppt Input: pointer to the perturbation structure
* @param index_md Input: index of mode under consideration (scalar/.../tensor)
* @param k Input: wavenumber
* @param tau Input: conformal time
* @param ppw Input/Output: in output contains the approximation to be used at this time
* @return the error status
*/
int perturb_approximations(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt,
int index_md,
double k,
double tau,
struct perturb_workspace * ppw
) {
/** Summary: */
/** - define local variables */
/* (a) time scale of Fourier mode, \f$ \tau_k = 1/k \f$ */
double tau_k;
/* (b) time scale of expansion, \f$ \tau_h = a/a' \f$ */
double tau_h;
/* (c) time scale of recombination, \f$ \tau_{\gamma} = 1/\kappa' \f$ */
double tau_c;
/** - compute Fourier mode time scale = \f$ \tau_k = 1/k \f$ */
class_test(k == 0.,
ppt->error_message,
"stop to avoid division by zero");
tau_k = 1./k;
/** - evaluate background quantities with background_at_tau() and
Hubble time scale \f$ \tau_h = a/a' \f$ */
class_call(background_at_tau(pba,tau, pba->normal_info, ppw->inter_mode, &(ppw->last_index_back), ppw->pvecback),
pba->error_message,
ppt->error_message);
class_test(ppw->pvecback[pba->index_bg_H]*ppw->pvecback[pba->index_bg_a] == 0.,
ppt->error_message,
"aH=0, stop to avoid division by zero");
tau_h = 1./(ppw->pvecback[pba->index_bg_H]*ppw->pvecback[pba->index_bg_a]);
/** - for scalar modes: */
if (_scalars_) {
/** - --> (a) evaluate thermodynamical quantities with thermodynamics_at_z() */
class_call(thermodynamics_at_z(pba,
pth,
1./ppw->pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
ppw->inter_mode,
&(ppw->last_index_thermo),
ppw->pvecback,
ppw->pvecthermo),
pth->error_message,
ppt->error_message);
/** - ---> (b.1.) if \f$ \kappa'=0 \f$, recombination is finished; tight-coupling approximation must be off */
if (ppw->pvecthermo[pth->index_th_dkappa] == 0.) {
ppw->approx[ppw->index_ap_tca] = (int)tca_off;
}
/** - ---> (b.2.) if \f$ \kappa' \neq 0 \f$, recombination is not finished: check tight-coupling approximation */
else {
/** - ----> (b.2.a) compute recombination time scale for photons, \f$ \tau_{\gamma} = 1/ \kappa' \f$ */
tau_c = 1./ppw->pvecthermo[pth->index_th_dkappa];
class_test(tau_c < 0.,
ppt->error_message,
"tau_c = 1/kappa' should always be positive unless there is something wrong in the thermodynamics module. However you have here tau_c=%e at z=%e, conformal time=%e x_e=%e. (This could come from the interpolation of a too poorly sampled reionisation history?).\n",
tau_c,
1./ppw->pvecback[pba->index_bg_a]-1.,
tau,
ppw->pvecthermo[pth->index_th_xe]);
/** - ----> (b.2.b) check whether tight-coupling approximation should be on */
if ((tau_c/tau_h < ppr->tight_coupling_trigger_tau_c_over_tau_h) &&
(tau_c/tau_k < ppr->tight_coupling_trigger_tau_c_over_tau_k)) {
ppw->approx[ppw->index_ap_tca] = (int)tca_on;
}
else {
ppw->approx[ppw->index_ap_tca] = (int)tca_off;
}
}
/** - --> (c) free-streaming approximations */
if ((tau/tau_k > ppr->radiation_streaming_trigger_tau_over_tau_k) &&
(tau > pth->tau_free_streaming) &&
(ppr->radiation_streaming_approximation != rsa_none)) {
ppw->approx[ppw->index_ap_rsa] = (int)rsa_on;
}
else {
ppw->approx[ppw->index_ap_rsa] = (int)rsa_off;
}
if (pba->has_ur == _TRUE_) {
if ((tau/tau_k > ppr->ur_fluid_trigger_tau_over_tau_k) &&
(ppr->ur_fluid_approximation != ufa_none)) {
ppw->approx[ppw->index_ap_ufa] = (int)ufa_on;
}
else {
ppw->approx[ppw->index_ap_ufa] = (int)ufa_off;
}
}
if (pba->has_ncdm == _TRUE_) {
if ((tau/tau_k > ppr->ncdm_fluid_trigger_tau_over_tau_k) &&
(ppr->ncdm_fluid_approximation != ncdmfa_none)) {
ppw->approx[ppw->index_ap_ncdmfa] = (int)ncdmfa_on;
}
else {
ppw->approx[ppw->index_ap_ncdmfa] = (int)ncdmfa_off;
}
}
}
/** - for tensor modes: */
if (_tensors_) {
/** - --> (a) evaluate thermodynamical quantities with thermodynamics_at_z() */
class_call(thermodynamics_at_z(pba,
pth,
1./ppw->pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
ppw->inter_mode,
&(ppw->last_index_thermo),
ppw->pvecback,
ppw->pvecthermo),
pth->error_message,
ppt->error_message);
/** - ---> (b.1.) if \f$ \kappa'=0 \f$, recombination is finished; tight-coupling approximation must be off */
if (ppw->pvecthermo[pth->index_th_dkappa] == 0.) {
ppw->approx[ppw->index_ap_tca] = (int)tca_off;
}
/** - ---> (b.2.) if \f$ \kappa' \neq 0 \f$, recombination is not finished: check tight-coupling approximation */
else {
/** - ----> (b.2.a) compute recombination time scale for photons, \f$ \tau_{\gamma} = 1/ \kappa' \f$ */
tau_c = 1./ppw->pvecthermo[pth->index_th_dkappa];
/** - ----> (b.2.b) check whether tight-coupling approximation should be on */
if ((tau_c/tau_h < ppr->tight_coupling_trigger_tau_c_over_tau_h) &&
(tau_c/tau_k < ppr->tight_coupling_trigger_tau_c_over_tau_k)) {
ppw->approx[ppw->index_ap_tca] = (int)tca_on;
}
else {
ppw->approx[ppw->index_ap_tca] = (int)tca_off;
}
}
if ((tau/tau_k > ppr->radiation_streaming_trigger_tau_over_tau_k) &&
(tau > pth->tau_free_streaming) &&
(ppr->radiation_streaming_approximation != rsa_none)) {
ppw->approx[ppw->index_ap_rsa] = (int)rsa_on;
}
else {
ppw->approx[ppw->index_ap_rsa] = (int)rsa_off;
}
}
return _SUCCESS_;
}
/**
* Compute typical timescale over which the perturbation equations
* vary. Some integrators (e.g. Runge-Kunta) benefit from calling this
* routine at each step in order to adapt the next step.
*
* This is one of the few functions in the code which is passed to the generic_integrator() routine.
* Since generic_integrator() should work with functions passed from various modules, the format of the arguments
* is a bit special:
* - fixed parameters and workspaces are passed through a generic pointer.
* generic_integrator() doesn't know the content of this pointer.
* - the error management is a bit special: errors are not written as usual to pth->error_message, but to a generic
* error_message passed in the list of arguments.
*
* @param tau Input: conformal time
* @param parameters_and_workspace Input: fixed parameters (e.g. indices), workspace, approximation used, etc.
* @param timescale Output: perturbation variation timescale (given the approximation used)
* @param error_message Output: error message
*/
int perturb_timescale(
double tau,
void * parameters_and_workspace,
double * timescale,
ErrorMsg error_message
) {
/** Summary: */
/** - define local variables */
/* (a) time scale of Fourier mode, \f$ \tau_k = 1/k \f$ */
double tau_k;
/* (b) time scale of expansion, \f$ \tau_h = a/a' \f$ */
double tau_h;
/* (c) time scale of recombination, \f$ \tau_{\gamma} = 1/\kappa' \f$ */
double tau_c;
/* various pointers allowing to extract the fields of the
parameter_and_workspace input structure */
struct perturb_parameters_and_workspace * pppaw;
struct background * pba;
struct thermo * pth;
struct perturbs * ppt;
struct perturb_workspace * ppw;
double * pvecback;
double * pvecthermo;
/** - extract the fields of the parameter_and_workspace input structure */
pppaw = parameters_and_workspace;
pba = pppaw->pba;
pth = pppaw->pth;
ppt = pppaw->ppt;
ppw = pppaw->ppw;
pvecback = ppw->pvecback;
pvecthermo = ppw->pvecthermo;
/** - compute Fourier mode time scale = \f$ \tau_k = 1/k \f$ */
class_test(pppaw->k == 0.,
ppt->error_message,
"stop to avoid division by zero");
tau_k = 1./pppaw->k;
/** - evaluate background quantities with background_at_tau() and
Hubble time scale \f$ \tau_h = a/a' \f$ */
class_call(background_at_tau(pba,tau, pba->normal_info, ppw->inter_mode, &(ppw->last_index_back), pvecback),
pba->error_message,
error_message);
class_test(pvecback[pba->index_bg_H]*pvecback[pba->index_bg_a] == 0.,
error_message,
"aH=0, stop to avoid division by zero");
tau_h = 1./(pvecback[pba->index_bg_H]*pvecback[pba->index_bg_a]);
/** - for scalars modes: */
if ((ppt->has_scalars == _TRUE_) && (pppaw->index_md == ppt->index_md_scalars)) {
*timescale = tau_h;
if ((ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) || (pba->has_ncdm == _TRUE_))
*timescale = MIN(tau_k,*timescale);
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) {
class_call(thermodynamics_at_z(pba,
pth,
1./pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
ppw->inter_mode,
&(ppw->last_index_thermo),
pvecback,
pvecthermo),
pth->error_message,
error_message);
if (pvecthermo[pth->index_th_dkappa] != 0.) {
/** - --> compute recombination time scale for photons, \f$ \tau_{\gamma} = 1/ \kappa' \f$ */
tau_c = 1./pvecthermo[pth->index_th_dkappa];
*timescale = MIN(tau_c,*timescale);
}
}
}
/** - for vector modes: */
if ((ppt->has_vectors == _TRUE_) && (pppaw->index_md == ppt->index_md_vectors)) {
*timescale = MIN(tau_h,tau_k);
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) {
class_call(thermodynamics_at_z(pba,
pth,
1./pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
ppw->inter_mode,
&(ppw->last_index_thermo),
pvecback,
pvecthermo),
pth->error_message,
error_message);
if (pvecthermo[pth->index_th_dkappa] != 0.) {
/** - --> compute recombination time scale for photons, \f$ \tau_{\gamma} = 1/ \kappa' \f$ */
tau_c = 1./pvecthermo[pth->index_th_dkappa];
*timescale = MIN(tau_c,*timescale);
}
}
}
/** - for tensor modes: */
if ((ppt->has_tensors == _TRUE_) && (pppaw->index_md == ppt->index_md_tensors)) {
*timescale = MIN(tau_h,tau_k);
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) {
class_call(thermodynamics_at_z(pba,
pth,
1./pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
ppw->inter_mode,
&(ppw->last_index_thermo),
pvecback,
pvecthermo),
pth->error_message,
error_message);
if (pvecthermo[pth->index_th_dkappa] != 0.) {
/** - --> compute recombination time scale for photons, \f$ \tau_{\gamma} = 1/ \kappa' \f$ */
tau_c = 1./pvecthermo[pth->index_th_dkappa];
*timescale = MIN(tau_c,*timescale);
}
}
}
return _SUCCESS_;
}
/**
* Compute metric perturbations (those not integrated over time) using Einstein equations
*
* @param ppr Input: pointer to precision structure
* @param pba Input: pointer to background structure
* @param pth Input: pointer to thermodynamics structure
* @param ppt Input: pointer to the perturbation structure
* @param index_md Input: index of mode under consideration (scalar/.../tensor)
* @param k Input: wavenumber
* @param tau Input: conformal time
* @param y Input: vector of perturbations (those integrated over time) (already allocated)
* @param ppw Input/Output: in output contains the updated metric perturbations
* @return the error status
*/
int perturb_einstein(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt,
int index_md,
double k,
double tau,
double * y,
struct perturb_workspace * ppw
) {
/** Summary: */
/** - define local variables */
double k2,a,a2,a_prime_over_a;
double s2_squared;
double shear_g = 0.;
/** - define wavenumber and scale factor related quantities */
k2 = k*k;
a = ppw->pvecback[pba->index_bg_a];
a2 = a * a;
a_prime_over_a = ppw->pvecback[pba->index_bg_H]*a;
s2_squared = 1.-3.*pba->K/k2;
/** - sum up perturbations from all species */
class_call(perturb_total_stress_energy(ppr,pba,pth,ppt,index_md,k,y,ppw),
ppt->error_message,
ppt->error_message);
/** - for scalar modes: */
if (_scalars_) {
/** - --> infer metric perturbations from Einstein equations */
/* newtonian gauge */
if (ppt->gauge == newtonian) {
/* in principle we could get phi from the constrain equation:
ppw->pvecmetric[ppw->index_mt_phi] = -1.5 * (a2/k2/k2/s2/s2) * (k2 * delta_rho + 3.*a_prime_over_a * rho_plus_p_theta);
with s2_squared = sqrt(1-3K/k2) = ppw->s_l[2]*ppw->s_l[2]
This was the case in class v1.3. However the integration is
more stable is we treat phi as a dynamical variable
y[ppw->pv->index_pt_phi], which derivative is given by the
second equation below (credits to Guido Walter Pettinari). */
/* equation for psi */
ppw->pvecmetric[ppw->index_mt_psi] = y[ppw->pv->index_pt_phi] - 4.5 * (a2/k2) * ppw->rho_plus_p_shear;
/* equation for phi' */
ppw->pvecmetric[ppw->index_mt_phi_prime] = -a_prime_over_a * ppw->pvecmetric[ppw->index_mt_psi] + 1.5 * (a2/k2) * ppw->rho_plus_p_theta;
/* eventually, infer radiation streaming approximation for
gamma and ur (this is exactly the right place to do it
because the result depends on h_prime) */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_on) {
class_call(perturb_rsa_delta_and_theta(ppr,pba,pth,ppt,k,y,a_prime_over_a,ppw->pvecthermo,ppw),
ppt->error_message,
ppt->error_message);
}
}
/* synchronous gauge */
if (ppt->gauge == synchronous) {
/* first equation involving total density fluctuation */
ppw->pvecmetric[ppw->index_mt_h_prime] =
( k2 * s2_squared * y[ppw->pv->index_pt_eta] + 1.5 * a2 * ppw->delta_rho)/(0.5*a_prime_over_a); /* h' */
/* eventually, infer radiation streaming approximation for
gamma and ur (this is exactly the right place to do it
because the result depends on h_prime) */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_on) {
class_call(perturb_rsa_delta_and_theta(ppr,pba,pth,ppt,k,y,a_prime_over_a,ppw->pvecthermo,ppw),
ppt->error_message,
ppt->error_message);
/* update total theta given rsa approximation results */
ppw->rho_plus_p_theta += 4./3.*ppw->pvecback[pba->index_bg_rho_g]*ppw->rsa_theta_g;
if (pba->has_ur == _TRUE_) {
ppw->rho_plus_p_theta += 4./3.*ppw->pvecback[pba->index_bg_rho_ur]*ppw->rsa_theta_ur;
}
}
/* second equation involving total velocity */
ppw->pvecmetric[ppw->index_mt_eta_prime] = (1.5 * a2 * ppw->rho_plus_p_theta + 0.5 * pba->K * ppw->pvecmetric[ppw->index_mt_h_prime])/k2/s2_squared; /* eta' */
/* third equation involving total pressure */
ppw->pvecmetric[ppw->index_mt_h_prime_prime] =
- 2. * a_prime_over_a * ppw->pvecmetric[ppw->index_mt_h_prime]
+ 2. * k2 * s2_squared * y[ppw->pv->index_pt_eta]
- 9. * a2 * ppw->delta_p;
/* alpha = (h'+6eta')/2k^2 */
ppw->pvecmetric[ppw->index_mt_alpha] = (ppw->pvecmetric[ppw->index_mt_h_prime] + 6.*ppw->pvecmetric[ppw->index_mt_eta_prime])/2./k2;
/* eventually, infer first-order tight-coupling approximation for photon
shear, then correct the total shear */
if (ppw->approx[ppw->index_ap_tca] == (int)tca_on) {
shear_g = 16./45./ppw->pvecthermo[pth->index_th_dkappa]*(y[ppw->pv->index_pt_theta_g]+k2*ppw->pvecmetric[ppw->index_mt_alpha]);
ppw->rho_plus_p_shear += 4./3.*ppw->pvecback[pba->index_bg_rho_g]*shear_g;
}
/* fourth equation involving total shear */
ppw->pvecmetric[ppw->index_mt_alpha_prime] = //TBC
- 2. * a_prime_over_a * ppw->pvecmetric[ppw->index_mt_alpha]
+ y[ppw->pv->index_pt_eta]
- 4.5 * (a2/k2) * ppw->rho_plus_p_shear;
}
/* transform (delta_m, theta_m) of the current gauge into
gauge-independent variables (you could comment this out if you
really want gauge-dependent results) */
if (ppt->has_source_delta_m == _TRUE_) {
ppw->delta_m += 3. *ppw->pvecback[pba->index_bg_a]*ppw->pvecback[pba->index_bg_H] * ppw->theta_m/k2;
// note: until 2.4.3 there was a typo, the factor was (-2 H'/H) instead
// of (3 aH). There is the same typo in the CLASSgal paper
// 1307.1459v1,v2,v3. It came from a confusion between (1+w_total)
// and (1+w_matter)=1 [the latter is the relevant one here].
//
// note2: at this point this gauge-invariant variable is only
// valid if all matter components are pressureless and
// stable. This relation will be generalized soon to the case
// of decaying dark matter.
}
if (ppt->has_source_theta_m == _TRUE_) {
if (ppt->gauge == synchronous) {
ppw->theta_m += ppw->pvecmetric[ppw->index_mt_alpha]*k2;
}
}
}
/** - for vector modes */
if (_vectors_) {
if (ppt->gauge == newtonian) {
ppw->pvecmetric[ppw->index_mt_V_prime] = -2.*a_prime_over_a*y[ppw->pv->index_pt_V] - 3.*ppw->vector_source_pi/k;
}
if (ppt->gauge == synchronous) {
// assuming vector_source_pi = p_class a^2 pi_T^{(1)} and vector_source_v = (rho_class+p_class)a^2 v^{(1)}
// from Hu and White:
ppw->pvecmetric[ppw->index_mt_hv_prime_prime] = -2.*a_prime_over_a*y[ppw->pv->index_pt_hv_prime] - 3.*ppw->vector_source_pi/k2;
// what we suspect:
//ppw->pvecmetric[ppw->index_mt_hv_prime_prime] = -2.*a_prime_over_a*y[ppw->pv->index_pt_hv_prime] - 3.*ppw->vector_source_pi;
// if we use the other equation:
//ppw->pvecmetric[ppw->index_mt_hv_prime] = -2./k/ (1.-2.*pba->K/k2) * 3. * ppw->vector_source_v;
}
}
/** - for tensor modes */
if (_tensors_) {
/* single einstein equation for tensor perturbations */
ppw->pvecmetric[ppw->index_mt_gw_prime_prime] = -2.*a_prime_over_a*y[ppw->pv->index_pt_gwdot]-(k2+2.*pba->K)*y[ppw->pv->index_pt_gw]+ppw->gw_source;
}
return _SUCCESS_;
}
int perturb_total_stress_energy(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt,
int index_md,
double k,
double * y,
struct perturb_workspace * ppw
) {
/** Summary: */
/** - define local variables */
double a,a2;
double delta_g=0.;
double theta_g=0.;
double shear_g=0.;
double delta_ur=0.;
double theta_ur=0.;
double shear_ur=0.;
double rho_delta_ncdm=0.;
double rho_plus_p_theta_ncdm=0.;
double rho_plus_p_shear_ncdm=0.;
double delta_p_ncdm=0.;
double factor;
double rho_plus_p_ncdm;
int index_q,n_ncdm,idx;
double epsilon,q,q2,cg2_ncdm,w_ncdm,rho_ncdm_bg,p_ncdm_bg,pseudo_p_ncdm;
double rho_m,delta_rho_m,rho_plus_p_m,rho_plus_p_theta_m;
double w;
double gwncdm;
double rho_relativistic;
double rho_dr_over_f;
double delta_rho_scf, delta_p_scf, psi;
/** - wavenumber and scale factor related quantities */
a = ppw->pvecback[pba->index_bg_a];
a2 = a * a;
/** - for scalar modes */
if (_scalars_) {
/** - --> (a) deal with approximation schemes */
/** - ---> (a.1.) photons */
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) {
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
/** - ----> (a.1.1.) no approximation */
delta_g = y[ppw->pv->index_pt_delta_g];
theta_g = y[ppw->pv->index_pt_theta_g];
shear_g = y[ppw->pv->index_pt_shear_g];
}
else {
/** - ----> (a.1.2.) radiation streaming approximation */
delta_g = 0.; /* actual free streaming approximation imposed after evaluation of einstein equations */
theta_g = 0.; /* actual free streaming approximation imposed after evaluation of einstein equations */
shear_g = 0.; /* shear always neglected in radiation streaming approximation */
}
}
else {
/** - ----> (a.1.3.) tight coupling approximation */
delta_g = y[ppw->pv->index_pt_delta_g];
theta_g = y[ppw->pv->index_pt_theta_g];
/* first-order tight-coupling approximation for photon shear */
if (ppt->gauge == newtonian) {
shear_g = 16./45./ppw->pvecthermo[pth->index_th_dkappa]*y[ppw->pv->index_pt_theta_g];
}
else {
shear_g = 0.; /* in the synchronous gauge, the expression of
shear_g (at first-order in a tight-coupling
expansion) is a function of h' and eta'; but h'
and eta' are calculated in perturb_einstein()
as a function of delta_g and theta_g. Hence,
we set shear_g temporarily to zero, and set it
to the right first-order value in
perturb_einstein(), just before using the
Einstein equation for the shear. */
}
}
/** - ---> (a.2.) ur */
if (pba->has_ur == _TRUE_) {
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
delta_ur = y[ppw->pv->index_pt_delta_ur];
theta_ur = y[ppw->pv->index_pt_theta_ur];
shear_ur = y[ppw->pv->index_pt_shear_ur];
}
else {
delta_ur = 0.; /* actual free streaming approximation imposed after evaluation of 1st einstein equation */
theta_ur = 0.; /* actual free streaming approximation imposed after evaluation of 1st einstein equation */
shear_ur = 0.; /* shear always neglected in free streaming approximation */
}
}
/** - --> (b) compute the total density, velocity and shear perturbations */
/* photon and baryon contribution */
ppw->delta_rho = ppw->pvecback[pba->index_bg_rho_g]*delta_g
+ ppw->pvecback[pba->index_bg_rho_b]*y[ppw->pv->index_pt_delta_b];
ppw->rho_plus_p_theta = 4./3.*ppw->pvecback[pba->index_bg_rho_g]*theta_g
+ ppw->pvecback[pba->index_bg_rho_b]*y[ppw->pv->index_pt_theta_b];
ppw->rho_plus_p_shear = 4./3.*ppw->pvecback[pba->index_bg_rho_g]*shear_g;
ppw->delta_p = 1./3.*ppw->pvecback[pba->index_bg_rho_g]*delta_g
+ ppw->pvecthermo[pth->index_th_cb2]*ppw->pvecback[pba->index_bg_rho_b]*y[ppw->pv->index_pt_delta_b];
/* cdm contribution */
if (pba->has_cdm == _TRUE_) {
ppw->delta_rho = ppw->delta_rho + ppw->pvecback[pba->index_bg_rho_cdm]*y[ppw->pv->index_pt_delta_cdm];
if (ppt->gauge == newtonian)
ppw->rho_plus_p_theta = ppw->rho_plus_p_theta + ppw->pvecback[pba->index_bg_rho_cdm]*y[ppw->pv->index_pt_theta_cdm];
}
/* dcdm contribution */
if (pba->has_dcdm == _TRUE_) {
ppw->delta_rho += ppw->pvecback[pba->index_bg_rho_dcdm]*y[ppw->pv->index_pt_delta_dcdm];
ppw->rho_plus_p_theta += ppw->pvecback[pba->index_bg_rho_dcdm]*y[ppw->pv->index_pt_theta_dcdm];
}
/* fluid contribution */
/* if (pba->has_fld == _TRUE_) {*/
if ( 0 ) { // commented out so that no dark energy perturbations are included
w = pba->w0_fld + pba->wa_fld * (1. - a / pba->a_today);
ppw->delta_rho += ppw->pvecback[pba->index_bg_rho_fld]*y[ppw->pv->index_pt_delta_fld];
ppw->rho_plus_p_theta += (1.+w)*ppw->pvecback[pba->index_bg_rho_fld]*y[ppw->pv->index_pt_theta_fld];
ppw->delta_p = ppw->delta_p + pba->cs2_fld * ppw->pvecback[pba->index_bg_rho_fld]*y[ppw->pv->index_pt_delta_fld];
}
/* ultra-relativistic decay radiation */
if (pba->has_dr == _TRUE_) {
/* We have delta_rho_dr = rho_dr * F0_dr / f, where F follows the
convention in astro-ph/9907388 and f is defined as
f = rho_dr*a^4/rho_crit_today. In CLASS density units
rho_crit_today = H0^2.
*/
rho_dr_over_f = pow(pba->H0/a2,2);
ppw->delta_rho += rho_dr_over_f*y[ppw->pv->index_pt_F0_dr];
ppw->rho_plus_p_theta += 4./3.*3./4*k*rho_dr_over_f*y[ppw->pv->index_pt_F0_dr+1];
ppw->rho_plus_p_shear += 2./3.*rho_dr_over_f*y[ppw->pv->index_pt_F0_dr+2];
ppw->delta_p += 1./3.*rho_dr_over_f*y[ppw->pv->index_pt_F0_dr];
}
/* ultra-relativistic neutrino/relics contribution */
if (pba->has_ur == _TRUE_) {
ppw->delta_rho = ppw->delta_rho + ppw->pvecback[pba->index_bg_rho_ur]*delta_ur;
ppw->rho_plus_p_theta = ppw->rho_plus_p_theta + 4./3.*ppw->pvecback[pba->index_bg_rho_ur]*theta_ur;
ppw->rho_plus_p_shear = ppw->rho_plus_p_shear + 4./3.*ppw->pvecback[pba->index_bg_rho_ur]*shear_ur;
ppw->delta_p += 1./3.*ppw->pvecback[pba->index_bg_rho_ur]*delta_ur;
}
/* non-cold dark matter contribution */
if (pba->has_ncdm == _TRUE_) {
idx = ppw->pv->index_pt_psi0_ncdm1;
if(ppw->approx[ppw->index_ap_ncdmfa] == (int)ncdmfa_on) {
// The perturbations are evolved integrated:
for(n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
rho_ncdm_bg = ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm];
p_ncdm_bg = ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm];
pseudo_p_ncdm = ppw->pvecback[pba->index_bg_pseudo_p_ncdm1+n_ncdm];
rho_plus_p_ncdm = rho_ncdm_bg + p_ncdm_bg;
w_ncdm = p_ncdm_bg/rho_ncdm_bg;
cg2_ncdm = w_ncdm*(1.0-1.0/(3.0+3.0*w_ncdm)*(3.0*w_ncdm-2.0+pseudo_p_ncdm/p_ncdm_bg));
if ((ppt->has_source_delta_ncdm == _TRUE_) || (ppt->has_source_theta_ncdm == _TRUE_) || (ppt->has_source_delta_m == _TRUE_)) {
ppw->delta_ncdm[n_ncdm] = y[idx];
ppw->theta_ncdm[n_ncdm] = y[idx+1];
ppw->shear_ncdm[n_ncdm] = y[idx+2];
}
ppw->delta_rho += rho_ncdm_bg*y[idx];
ppw->rho_plus_p_theta += rho_plus_p_ncdm*y[idx+1];
ppw->rho_plus_p_shear += rho_plus_p_ncdm*y[idx+2];
ppw->delta_p += cg2_ncdm*rho_ncdm_bg*y[idx];
idx += ppw->pv->l_max_ncdm[n_ncdm]+1;
}
}
else {
// We must integrate to find perturbations:
for(n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
rho_delta_ncdm = 0.0;
rho_plus_p_theta_ncdm = 0.0;
rho_plus_p_shear_ncdm = 0.0;
delta_p_ncdm = 0.0;
factor = pba->factor_ncdm[n_ncdm]*pow(pba->a_today/a,4);
for (index_q=0; index_q < ppw->pv->q_size_ncdm[n_ncdm]; index_q ++) {
q = pba->q_ncdm[n_ncdm][index_q];
q2 = q*q;
epsilon = sqrt(q2+pba->M_ncdm[n_ncdm]*pba->M_ncdm[n_ncdm]*a2);
rho_delta_ncdm += q2*epsilon*pba->w_ncdm[n_ncdm][index_q]*y[idx];
rho_plus_p_theta_ncdm += q2*q*pba->w_ncdm[n_ncdm][index_q]*y[idx+1];
rho_plus_p_shear_ncdm += q2*q2/epsilon*pba->w_ncdm[n_ncdm][index_q]*y[idx+2];
delta_p_ncdm += q2*q2/epsilon*pba->w_ncdm[n_ncdm][index_q]*y[idx];
//Jump to next momentum bin:
idx+=(ppw->pv->l_max_ncdm[n_ncdm]+1);
}
rho_delta_ncdm *= factor;
rho_plus_p_theta_ncdm *= k*factor;
rho_plus_p_shear_ncdm *= 2.0/3.0*factor;
delta_p_ncdm *= factor/3.;
if ((ppt->has_source_delta_ncdm == _TRUE_) || (ppt->has_source_theta_ncdm == _TRUE_) || (ppt->has_source_delta_m == _TRUE_)) {
ppw->delta_ncdm[n_ncdm] = rho_delta_ncdm/ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm];
ppw->theta_ncdm[n_ncdm] = rho_plus_p_theta_ncdm/
(ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]+ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm]);
ppw->shear_ncdm[n_ncdm] = rho_plus_p_shear_ncdm/
(ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]+ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm]);
}
ppw->delta_rho += rho_delta_ncdm;
ppw->rho_plus_p_theta += rho_plus_p_theta_ncdm;
ppw->rho_plus_p_shear += rho_plus_p_shear_ncdm;
ppw->delta_p += delta_p_ncdm;
}
}
}
/* scalar field contribution.
In Newtonian gauge, delta_scf depends on the metric perturbation psi which is inferred
from rho_plus_p_shear. So the contribution from the scalar field must be below all
species with non-zero shear.
*/
if (pba->has_scf == _TRUE_) {
if (ppt->gauge == synchronous) {
delta_rho_scf = 1./3.*
(1./a2*ppw->pvecback[pba->index_bg_phi_prime_scf]*y[ppw->pv->index_pt_phi_prime_scf]
+ ppw->pvecback[pba->index_bg_dV_scf]*y[ppw->pv->index_pt_phi_scf]);
delta_p_scf = 1./3.*
(1./a2*ppw->pvecback[pba->index_bg_phi_prime_scf]*y[ppw->pv->index_pt_phi_prime_scf]
- ppw->pvecback[pba->index_bg_dV_scf]*y[ppw->pv->index_pt_phi_scf]);
}
else {
/* equation for psi */
psi = y[ppw->pv->index_pt_phi] - 4.5 * (a2/k/k) * ppw->rho_plus_p_shear;
delta_rho_scf = 1./3.*
(1./a2*ppw->pvecback[pba->index_bg_phi_prime_scf]*y[ppw->pv->index_pt_phi_prime_scf]
+ ppw->pvecback[pba->index_bg_dV_scf]*y[ppw->pv->index_pt_phi_scf]
- 1./a2*pow(ppw->pvecback[pba->index_bg_phi_prime_scf],2)*psi);
delta_p_scf = 1./3.*
(1./a2*ppw->pvecback[pba->index_bg_phi_prime_scf]*y[ppw->pv->index_pt_phi_prime_scf]
- ppw->pvecback[pba->index_bg_dV_scf]*y[ppw->pv->index_pt_phi_scf]
- 1./a2*pow(ppw->pvecback[pba->index_bg_phi_prime_scf],2)*psi);
}
ppw->delta_rho += delta_rho_scf;
ppw->rho_plus_p_theta += 1./3.*
k*k/a2*ppw->pvecback[pba->index_bg_phi_prime_scf]*y[ppw->pv->index_pt_phi_scf];
ppw->delta_p += delta_p_scf;
}
/* store delta_m in the current gauge. In perturb_einstein, this
will be transformed later on into the gauge-independent variable D
= delta_m - 2H'/H \theta_m/k^2 . */
if (ppt->has_source_delta_m == _TRUE_) {
/* include baryons and cold dark matter */
delta_rho_m = ppw->pvecback[pba->index_bg_rho_b]*y[ppw->pv->index_pt_delta_b];
rho_m = ppw->pvecback[pba->index_bg_rho_b];
if (pba->has_cdm == _TRUE_) {
delta_rho_m += ppw->pvecback[pba->index_bg_rho_cdm]*y[ppw->pv->index_pt_delta_cdm];
rho_m += ppw->pvecback[pba->index_bg_rho_cdm];
}
/* include decaying cold dark matter */
if (pba->has_dcdm == _TRUE_) {
delta_rho_m += ppw->pvecback[pba->index_bg_rho_dcdm]*y[ppw->pv->index_pt_delta_dcdm];
rho_m += ppw->pvecback[pba->index_bg_rho_dcdm];
}
/* include any other species non-relativistic today (like ncdm species) */
if (pba->has_ncdm == _TRUE_) {
for(n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
delta_rho_m += ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]*ppw->delta_ncdm[n_ncdm];
rho_m += ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm];
}
}
/* infer delta_m */
ppw->delta_m = delta_rho_m/rho_m;
}
/* store theta_m in the current gauge. In perturb_einstein, this
will be transformed later on into the gauge-independent variable
Theta . Note that computing theta_m is necessary also if we want
the delta_m source only, because the gauge-invariant delta_m
involves theta_m in the current gauge. */
if ((ppt->has_source_delta_m == _TRUE_) || (ppt->has_source_theta_m == _TRUE_)) {
/* include baryons and cold dark matter */
rho_plus_p_theta_m = ppw->pvecback[pba->index_bg_rho_b]*y[ppw->pv->index_pt_theta_b];
rho_plus_p_m = ppw->pvecback[pba->index_bg_rho_b];
if (pba->has_cdm == _TRUE_) {
if (ppt->gauge == newtonian)
rho_plus_p_theta_m += ppw->pvecback[pba->index_bg_rho_cdm]*y[ppw->pv->index_pt_theta_cdm];
rho_plus_p_m += ppw->pvecback[pba->index_bg_rho_cdm];
}
if (pba->has_dcdm == _TRUE_) {
rho_plus_p_theta_m += ppw->pvecback[pba->index_bg_rho_dcdm]*y[ppw->pv->index_pt_theta_dcdm];
rho_plus_p_m += ppw->pvecback[pba->index_bg_rho_dcdm];
}
/* include any other species non-relativistic today (like ncdm species) */
if (pba->has_ncdm == _TRUE_) {
for(n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
rho_plus_p_theta_m += (ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]+ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm])*ppw->theta_ncdm[n_ncdm];
rho_plus_p_m += (ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]+ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm]);
}
}
/* infer theta_m */
ppw->theta_m = rho_plus_p_theta_m/rho_plus_p_m;
}
}
/** - for vector modes */
if (_vectors_) {
ppw->vector_source_pi = 0.;
ppw->vector_source_v = 0.;
/** - --> photon contribution to vector sources: */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) { /* if radiation streaming approximation is off */
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) { /* if tight-coupling approximation is off */
ppw->vector_source_v += 4./3.*a2*ppw->pvecback[pba->index_bg_rho_g]
* (-1./4.*_SQRT2_)
* (y[ppw->pv->index_pt_delta_g]+2.*y[ppw->pv->index_pt_delta_g]+y[ppw->pv->index_pt_shear_g]);
ppw->vector_source_pi += 1./3.*a2*ppw->pvecback[pba->index_bg_rho_g]
* (6.*_SQRT2_/5./sqrt(1.-2.*pba->K/k/k))
* (4./3./k*y[ppw->pv->index_pt_theta_g]+y[ppw->pv->index_pt_l3_g]);
}
}
/** - --> baryons */
}
/** - for tensor modes */
if (_tensors_) {
ppw->gw_source = 0.0;
/** - --> photon contribution to gravitational wave source: */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) { /* if radiation streaming approximation is off */
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) { /* if tight-coupling approximation is off */
ppw->gw_source += (-_SQRT6_*4*a2*ppw->pvecback[pba->index_bg_rho_g]*
(1./15.*y[ppw->pv->index_pt_delta_g]+
4./21.*y[ppw->pv->index_pt_shear_g]+
1./35.*y[ppw->pv->index_pt_l3_g+1]));
}
}
/** - --> ur contribution to gravitational wave source: */
if (ppt->evolve_tensor_ur == _TRUE_) {
rho_relativistic = 0.;
if (ppt->tensor_method == tm_exact)
rho_relativistic += ppw->pvecback[pba->index_bg_rho_ur];
if (ppt->tensor_method == tm_massless_approximation) {
if (pba->has_ur == _TRUE_)
rho_relativistic += ppw->pvecback[pba->index_bg_rho_ur];
if (pba->has_ncdm == _TRUE_) {
for(n_ncdm = 0; n_ncdm < pba->N_ncdm; n_ncdm++) {
/* (3 p_ncdm1) is the "relativistic" contribution to rho_ncdm1 */
rho_relativistic += 3.*ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm];
}
}
}
ppw->gw_source += (-_SQRT6_*4*a2*rho_relativistic*
(1./15.*y[ppw->pv->index_pt_delta_ur]+
4./21.*y[ppw->pv->index_pt_shear_ur]+
1./35.*y[ppw->pv->index_pt_l3_ur+1]));
}
/** - --> ncdm contribution to gravitational wave source: */
if (ppt->evolve_tensor_ncdm == _TRUE_) {
idx = ppw->pv->index_pt_psi0_ncdm1;
// We must integrate to find perturbations:
for(n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
gwncdm = 0.;
factor = pba->factor_ncdm[n_ncdm]*pow(pba->a_today/a,4);
for (index_q=0; index_q < ppw->pv->q_size_ncdm[n_ncdm]; index_q ++) {
q = pba->q_ncdm[n_ncdm][index_q];
q2 = q*q;
epsilon = sqrt(q2+pba->M_ncdm[n_ncdm]*pba->M_ncdm[n_ncdm]*a2);
gwncdm += q2*q2/epsilon*pba->w_ncdm[n_ncdm][index_q]*(1./15.*y[idx]+2./21.*y[idx+2]+1./35.*y[idx+4]);
//Jump to next momentum bin:
idx+=(ppw->pv->l_max_ncdm[n_ncdm]+1);
}
gwncdm *= -_SQRT6_*4*a2*factor;
ppw->gw_source += gwncdm;
}
}
}
return _SUCCESS_;
}
/**
* Compute the source functions (three terms for temperature, one for
* E or B modes, etc.)
*
* This is one of the few functions in the code which is passed to
* the generic_integrator() routine. Since generic_integrator()
* should work with functions passed from various modules, the format
* of the arguments is a bit special:
*
* - fixed parameters and workspaces are passed through a generic
* pointer. generic_integrator() doesn't know the content of this
* pointer.
*
* - the error management is a bit special: errors are not written as
* usual to pth->error_message, but to a generic error_message passed
* in the list of arguments.
*
* @param tau Input: conformal time
* @param y Input: vector of perturbations
* @param dy Input: vector of time derivative of perturbations
* @param index_tau Input: index in the array tau_sampling
* @param parameters_and_workspace Input/Output: in input, all parameters needed by perturb_derivs, in output, source terms
* @param error_message Output: error message
* @return the error status
*/
int perturb_sources(
double tau,
double * y,
double * dy,
int index_tau,
void * parameters_and_workspace,
ErrorMsg error_message
) {
/** Summary: */
/** - define local variables */
double P;
int index_type;
struct perturb_parameters_and_workspace * pppaw;
struct precision * ppr;
struct background * pba;
struct thermo * pth;
struct perturbs * ppt;
int index_md;
int index_ic;
int index_k;
double k;
double z;
struct perturb_workspace * ppw;
double * pvecback;
double * pvecthermo;
double * pvecmetric;
double delta_g, delta_rho_scf, rho_plus_p_theta_scf;
double a_prime_over_a=0.; /* (a'/a) */
double a_prime_over_a_prime=0.; /* (a'/a)' */
int switch_isw = 1;
double a_rel, a2_rel, f_dr;
/** - rename structure fields (just to avoid heavy notations) */
pppaw = parameters_and_workspace;
ppr = pppaw->ppr;
pba = pppaw->pba;
pth = pppaw->pth;
ppt = pppaw->ppt;
index_md = pppaw->index_md;
index_ic = pppaw->index_ic;
index_k = pppaw->index_k;
k = pppaw->k;
ppw = pppaw->ppw;
pvecback = ppw->pvecback;
pvecthermo = ppw->pvecthermo;
pvecmetric = ppw->pvecmetric;
/** - get background/thermo quantities in this point */
class_call(background_at_tau(pba,
tau,
pba->normal_info,
pba->inter_closeby,
&(ppw->last_index_back),
pvecback),
pba->error_message,
error_message);
z = pba->a_today/pvecback[pba->index_bg_a]-1.;
class_call(thermodynamics_at_z(pba,
pth,
z, /* redshift z=1/a-1 */
pth->inter_closeby,
&(ppw->last_index_thermo),
pvecback,
pvecthermo),
pth->error_message,
error_message);
a_rel = ppw->pvecback[pba->index_bg_a]/pba->a_today;
a2_rel = a_rel * a_rel;
/* derived background quantities, useful only in synchronous gauge */
if (ppt->gauge == synchronous) {
a_prime_over_a = pvecback[pba->index_bg_a] * pvecback[pba->index_bg_H]; /* (a'/a)=aH */
a_prime_over_a_prime = pvecback[pba->index_bg_H_prime] * pvecback[pba->index_bg_a] + pow(pvecback[pba->index_bg_H] * pvecback[pba->index_bg_a],2); /* (a'/a)' = aH'+(aH)^2 */
}
/** - for scalars */
if (_scalars_) {
/** - --> compute metric perturbations */
class_call(perturb_einstein(ppr,
pba,
pth,
ppt,
index_md,
k,
tau,
y,
ppw),
ppt->error_message,
error_message);
/** - --> compute quantities depending on approximation schemes */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_on) {
delta_g = ppw->rsa_delta_g;
P = 0.;
}
else {
delta_g = y[ppw->pv->index_pt_delta_g];
if (ppw->approx[ppw->index_ap_tca] == (int)tca_on)
P = 5.* ppw->s_l[2] * ppw->tca_shear_g/8.; /* (2.5+0.5+2)shear_g/8 */
else
P = (y[ppw->pv->index_pt_pol0_g] + y[ppw->pv->index_pt_pol2_g] + 2.* ppw->s_l[2] *y[ppw->pv->index_pt_shear_g])/8.;
}
/** - --> for each type, compute source terms */
/* scalar temperature */
if (ppt->has_source_t == _TRUE_) {
/* check whether integrated Sachs-Wolf term should be included */
if ((ppt->switch_eisw == 0) && (z >= ppt->eisw_lisw_split_z)) {
switch_isw = 0;
}
if ((ppt->switch_lisw == 0) && (z < ppt->eisw_lisw_split_z)) {
switch_isw=0;
}
/* newtonian gauge: simplest form, not efficient numerically */
/*
if (ppt->gauge == newtonian) {
_set_source_(ppt->index_tp_t0) = pvecthermo[pth->index_th_exp_m_kappa] * pvecmetric[ppw->index_mt_phi_prime] + pvecthermo[pth->index_th_g] * delta_g / 4.;
_set_source_(ppt->index_tp_t1) = pvecthermo[pth->index_th_exp_m_kappa] * k* pvecmetric[ppw->index_mt_psi] + pvecthermo[pth->index_th_g] * y[ppw->pv->index_pt_theta_b]/k;
_set_source_(ppt->index_tp_t2) = pvecthermo[pth->index_th_g] * P;
}
*/
/* newtonian gauge: slightly more complicated form, but more efficient numerically */
if (ppt->gauge == newtonian) {
_set_source_(ppt->index_tp_t0) =
ppt->switch_sw * pvecthermo[pth->index_th_g] * (delta_g / 4. + pvecmetric[ppw->index_mt_psi])
+ switch_isw * (pvecthermo[pth->index_th_g] * (y[ppw->pv->index_pt_phi]-pvecmetric[ppw->index_mt_psi])
+ pvecthermo[pth->index_th_exp_m_kappa] * 2. * pvecmetric[ppw->index_mt_phi_prime])
+ ppt->switch_dop /k/k * (pvecthermo[pth->index_th_g] * dy[ppw->pv->index_pt_theta_b]
+ pvecthermo[pth->index_th_dg] * y[ppw->pv->index_pt_theta_b]);
_set_source_(ppt->index_tp_t1) = switch_isw * pvecthermo[pth->index_th_exp_m_kappa] * k* (pvecmetric[ppw->index_mt_psi]-y[ppw->pv->index_pt_phi]);
_set_source_(ppt->index_tp_t2) = ppt->switch_pol * pvecthermo[pth->index_th_g] * P;
}
/* synchronous gauge: simplest form, not efficient numerically */
/*
if (ppt->gauge == synchronous) {
_set_source_(ppt->index_tp_t0) = - pvecthermo[pth->index_th_exp_m_kappa] * pvecmetric[ppw->index_mt_h_prime] / 6. + pvecthermo[pth->index_th_g] / 4. * delta_g;
_set_source_(ppt->index_tp_t1) = pvecthermo[pth->index_th_g] * y[ppw->pv->index_pt_theta_b] / k;
_set_source_(ppt->index_tp_t2) = pvecthermo[pth->index_th_exp_m_kappa] * k*k* 2./3. * ppw->s_l[2] * pvecmetric[ppw->index_mt_alpha] + pvecthermo[pth->index_th_g] * P;
}
*/
/* synchronous gauge: slightly more complicated form, but more efficient numerically */
if (ppt->gauge == synchronous) {
_set_source_(ppt->index_tp_t0) =
ppt->switch_sw * pvecthermo[pth->index_th_g] * (delta_g/4. + pvecmetric[ppw->index_mt_alpha_prime])
+ switch_isw * (pvecthermo[pth->index_th_g] * (y[ppw->pv->index_pt_eta]
- pvecmetric[ppw->index_mt_alpha_prime]
- 2 * a_prime_over_a * pvecmetric[ppw->index_mt_alpha])
+ pvecthermo[pth->index_th_exp_m_kappa] * 2. * (pvecmetric[ppw->index_mt_eta_prime]
- a_prime_over_a_prime * pvecmetric[ppw->index_mt_alpha]
- a_prime_over_a * pvecmetric[ppw->index_mt_alpha_prime]))
+ ppt->switch_dop * (pvecthermo[pth->index_th_g] * (dy[ppw->pv->index_pt_theta_b]/k/k + pvecmetric[ppw->index_mt_alpha_prime])
+pvecthermo[pth->index_th_dg] * (y[ppw->pv->index_pt_theta_b]/k/k + pvecmetric[ppw->index_mt_alpha]));
_set_source_(ppt->index_tp_t1) =
switch_isw * pvecthermo[pth->index_th_exp_m_kappa] * k * (pvecmetric[ppw->index_mt_alpha_prime]
+ 2. * a_prime_over_a * pvecmetric[ppw->index_mt_alpha]
- y[ppw->pv->index_pt_eta]);
_set_source_(ppt->index_tp_t2) =
ppt->switch_pol * pvecthermo[pth->index_th_g] * P;
}
}
/* scalar polarization */
if (ppt->has_source_p == _TRUE_) {
/* all gauges. Note that the correct formula for the E source
should have a minus sign, as shown in Hu & White. We put a
plus sign to comply with the 'historical convention'
established in CMBFAST and CAMB. */
_set_source_(ppt->index_tp_p) = sqrt(6.) * pvecthermo[pth->index_th_g] * P;
}
/* now, non-CMB sources */
/* Bardeen potential -PHI_H = phi in Newtonian gauge */
if (ppt->has_source_phi == _TRUE_) {
if (ppt->gauge == newtonian)
_set_source_(ppt->index_tp_phi) = y[ppw->pv->index_pt_phi];
if (ppt->gauge == synchronous)
_set_source_(ppt->index_tp_phi) = y[ppw->pv->index_pt_eta] - a_prime_over_a * pvecmetric[ppw->index_mt_alpha];
}
/* its derivative phi' */
if (ppt->has_source_phi_prime == _TRUE_) {
if (ppt->gauge == newtonian)
_set_source_(ppt->index_tp_phi_prime) = dy[ppw->pv->index_pt_phi];
if (ppt->gauge == synchronous)
_set_source_(ppt->index_tp_phi_prime) = dy[ppw->pv->index_pt_eta]
- a_prime_over_a_prime * pvecmetric[ppw->index_mt_alpha]
- a_prime_over_a * pvecmetric[ppw->index_mt_alpha_prime];
}
/* diff of Bardeen potentials PHI_A-PHI_H = psi + phi in newtonian gauge */
if (ppt->has_source_phi_plus_psi == _TRUE_) {
if (ppt->gauge == newtonian)
_set_source_(ppt->index_tp_phi_plus_psi) =
y[ppw->pv->index_pt_phi] + pvecmetric[ppw->index_mt_psi];
if (ppt->gauge == synchronous)
_set_source_(ppt->index_tp_phi_plus_psi) =
y[ppw->pv->index_pt_eta] + pvecmetric[ppw->index_mt_alpha_prime];
}
/* Bardeen potential PHI_A = psi in newtonian gauge */
if (ppt->has_source_psi == _TRUE_) {
if (ppt->gauge == newtonian)
_set_source_(ppt->index_tp_psi) =
pvecmetric[ppw->index_mt_psi];
if (ppt->gauge == synchronous)
_set_source_(ppt->index_tp_psi) =
a_prime_over_a * pvecmetric[ppw->index_mt_alpha] + pvecmetric[ppw->index_mt_alpha_prime];
}
/* total matter over density (gauge-invariant, defined as in arXiv:1307.1459) */
if (ppt->has_source_delta_m == _TRUE_) {
_set_source_(ppt->index_tp_delta_m) = ppw->delta_m;
}
/* delta_g */
if (ppt->has_source_delta_g == _TRUE_) {
_set_source_(ppt->index_tp_delta_g) = delta_g;
}
/* delta_baryon */
if (ppt->has_source_delta_b == _TRUE_) {
_set_source_(ppt->index_tp_delta_b) = y[ppw->pv->index_pt_delta_b];
}
/* delta_cdm */
if (ppt->has_source_delta_cdm == _TRUE_) {
_set_source_(ppt->index_tp_delta_cdm) = y[ppw->pv->index_pt_delta_cdm];
}
/* delta_dcdm */
if (ppt->has_source_delta_dcdm == _TRUE_) {
_set_source_(ppt->index_tp_delta_dcdm) = y[ppw->pv->index_pt_delta_dcdm];
}
/* delta_fld */
if (ppt->has_source_delta_fld == _TRUE_) {
_set_source_(ppt->index_tp_delta_fld) = y[ppw->pv->index_pt_delta_fld];
}
/* delta_scf */
if (ppt->has_source_delta_scf == _TRUE_) {
if (ppt->gauge == synchronous) {
delta_rho_scf = 1./3.*
(1./a2_rel*ppw->pvecback[pba->index_bg_phi_prime_scf]*y[ppw->pv->index_pt_phi_prime_scf]
+ ppw->pvecback[pba->index_bg_dV_scf]*y[ppw->pv->index_pt_phi_scf]);
}
else {
delta_rho_scf = 1./3.*
(1./a2_rel*ppw->pvecback[pba->index_bg_phi_prime_scf]*y[ppw->pv->index_pt_phi_prime_scf]
+ ppw->pvecback[pba->index_bg_dV_scf]*y[ppw->pv->index_pt_phi_scf]
- 1./a2_rel*pow(ppw->pvecback[pba->index_bg_phi_prime_scf],2)*ppw->pvecmetric[ppw->index_mt_psi]);
}
_set_source_(ppt->index_tp_delta_scf) = delta_rho_scf/pvecback[pba->index_bg_rho_scf];
}
/* delta_dr */
if (ppt->has_source_delta_dr == _TRUE_) {
f_dr = pow(a2_rel/pba->H0,2)*pvecback[pba->index_bg_rho_dr];
_set_source_(ppt->index_tp_delta_dr) = y[ppw->pv->index_pt_F0_dr]/f_dr;
}
/* delta_ur */
if (ppt->has_source_delta_ur == _TRUE_) {
if (ppw->approx[ppw->index_ap_rsa]==(int)rsa_off)
_set_source_(ppt->index_tp_delta_ur) = y[ppw->pv->index_pt_delta_ur];
else
_set_source_(ppt->index_tp_delta_ur) = ppw->rsa_delta_ur;
}
/* delta_ncdm1 */
if (ppt->has_source_delta_ncdm == _TRUE_) {
for (index_type = ppt->index_tp_delta_ncdm1; index_type < ppt->index_tp_delta_ncdm1+pba->N_ncdm; index_type++) {
_set_source_(index_type) = ppw->delta_ncdm[index_type - ppt->index_tp_delta_ncdm1];
}
}
/* total velocity (gauge-invariant, defined as in arXiv:1307.1459) */
if (ppt->has_source_theta_m == _TRUE_) {
_set_source_(ppt->index_tp_theta_m) = ppw->theta_m;
}
/* theta_g */
if (ppt->has_source_theta_g == _TRUE_) {
if (ppw->approx[ppw->index_ap_rsa]==(int)rsa_off)
_set_source_(ppt->index_tp_theta_g) = y[ppw->pv->index_pt_theta_g];
else
_set_source_(ppt->index_tp_theta_g) = ppw->rsa_theta_g;
}
/* theta_baryon */
if (ppt->has_source_theta_b == _TRUE_) {
_set_source_(ppt->index_tp_theta_b) = y[ppw->pv->index_pt_theta_b];
}
/* theta_cdm */
if (ppt->has_source_theta_cdm == _TRUE_) {
_set_source_(ppt->index_tp_theta_cdm) = y[ppw->pv->index_pt_theta_cdm];
}
/* theta_dcdm */
if (ppt->has_source_theta_dcdm == _TRUE_) {
_set_source_(ppt->index_tp_theta_dcdm) = y[ppw->pv->index_pt_theta_dcdm];
}
/* theta_fld */
if (ppt->has_source_theta_fld == _TRUE_) {
_set_source_(ppt->index_tp_theta_fld) = y[ppw->pv->index_pt_theta_fld];
}
/* theta_scf */
if (ppt->has_source_theta_scf == _TRUE_) {
rho_plus_p_theta_scf = 1./3.*
k*k/a2_rel*ppw->pvecback[pba->index_bg_phi_prime_scf]*y[ppw->pv->index_pt_phi_scf];
_set_source_(ppt->index_tp_theta_scf) = rho_plus_p_theta_scf/
(pvecback[pba->index_bg_rho_scf]+pvecback[pba->index_bg_p_scf]);
}
/* theta_dr */
if (ppt->has_source_theta_dr == _TRUE_) {
f_dr = pow(a2_rel/pba->H0,2)*pvecback[pba->index_bg_rho_dr];
_set_source_(ppt->index_tp_theta_dr) = 3./4.*k*y[ppw->pv->index_pt_F0_dr+1]/f_dr;
}
/* theta_ur */
if (ppt->has_source_theta_ur == _TRUE_) {
if (ppw->approx[ppw->index_ap_rsa]==(int)rsa_off)
_set_source_(ppt->index_tp_theta_ur) = y[ppw->pv->index_pt_theta_ur];
else
_set_source_(ppt->index_tp_theta_ur) = ppw->rsa_theta_ur;
}
/* theta_ncdm1 */
if (ppt->has_source_theta_ncdm == _TRUE_) {
for (index_type = ppt->index_tp_theta_ncdm1; index_type < ppt->index_tp_theta_ncdm1+pba->N_ncdm; index_type++) {
_set_source_(index_type) = ppw->theta_ncdm[index_type - ppt->index_tp_theta_ncdm1];
}
}
}
/** - for tensors */
if (_tensors_) {
/** - --> compute quantities depending on approximation schemes */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) {
P = -(1./10.*y[ppw->pv->index_pt_delta_g]
+2./7.*y[ppw->pv->index_pt_shear_g]
+3./70.*y[ppw->pv->index_pt_delta_g+4]
-3./5.*y[ppw->pv->index_pt_pol0_g]
+6./7.*y[ppw->pv->index_pt_pol2_g]
-3./70.*y[ppw->pv->index_pt_pol0_g+4])
/sqrt(6.);
}
else {
P = 2./5.*_SQRT6_*y[ppw->pv->index_pt_gwdot]/ppw->pvecthermo[pth->index_th_dkappa]; //TBC
}
}
else {
P = 0.;
}
/* tensor temperature */
if (ppt->has_source_t == _TRUE_) {
_set_source_(ppt->index_tp_t2) = - y[ppw->pv->index_pt_gwdot] * pvecthermo[pth->index_th_exp_m_kappa] + pvecthermo[pth->index_th_g] * P;
}
/* tensor polarization */
if (ppt->has_source_p == _TRUE_) {
/* Note that the correct formula for the polarization source
should have a minus sign, as shown in Hu & White. We put a
plus sign to comply with the 'historical convention'
established in CMBFAST and CAMB. */
_set_source_(ppt->index_tp_p) = sqrt(6.) * pvecthermo[pth->index_th_g] * P;
}
}
return _SUCCESS_;
}
/**
* When testing the code or a cosmological model, it can be useful to
* output perturbations at each step of integration (and not just the
* delta's at each source sampling point, which is achieved simply by
* asking for matter transfer functions). Then this function can be
* passed to the generic_evolver routine.
*
* By default, instead of passing this function to generic_evolver,
* one passes a null pointer. Then this function is just not used.
*
* @param tau Input: conformal time
* @param y Input: vector of perturbations
* @param dy Input: vector of its derivatives (already allocated)
* @param parameters_and_workspace Input: fixed parameters (e.g. indices)
* @param error_message Output: error message
*
*/
int perturb_print_variables(double tau,
double * y,
double * dy,
void * parameters_and_workspace,
ErrorMsg error_message
) {
struct perturb_parameters_and_workspace * pppaw;
/** Summary: */
/** - define local variables */
double k;
int index_md;
//struct precision * ppr;
struct background * pba;
struct thermo * pth;
struct perturbs * ppt;
struct perturb_workspace * ppw;
double * pvecback;
double * pvecmetric;
double delta_g,theta_g,shear_g,l4_g,pol0_g,pol1_g,pol2_g,pol4_g;
double delta_b,theta_b;
double delta_cdm=0.,theta_cdm=0.;
double delta_dcdm=0.,theta_dcdm=0.;
double delta_dr=0.,theta_dr=0.,shear_dr=0., f_dr=1.0;
double delta_ur=0.,theta_ur=0.,shear_ur=0.,l4_ur=0.;
double delta_rho_scf=0., rho_plus_p_theta_scf=0.;
double delta_scf=0., theta_scf=0.;
/** - ncdm sector begins */
int n_ncdm;
double *delta_ncdm=NULL, *theta_ncdm=NULL, *shear_ncdm=NULL, *delta_p_over_delta_rho_ncdm=NULL;
double rho_ncdm_bg, p_ncdm_bg, pseudo_p_ncdm, w_ncdm;
double rho_delta_ncdm = 0.0;
double rho_plus_p_theta_ncdm = 0.0;
double rho_plus_p_shear_ncdm = 0.0;
double delta_p_ncdm = 0.0;
double factor = 0.0;
double q,q2,epsilon;
/** - ncdm sector ends */
double phi=0.,psi=0.,alpha=0.;
double delta_temp=0., delta_chi=0.;
double a,a2,H;
int idx,index_q, storeidx;
double *dataptr;
/** - rename structure fields (just to avoid heavy notations) */
pppaw = parameters_and_workspace;
k = pppaw->k;
index_md = pppaw->index_md;
//ppr = pppaw->ppr;
pba = pppaw->pba;
pth = pppaw->pth;
ppt = pppaw->ppt;
ppw = pppaw->ppw;
pvecback = ppw->pvecback;
pvecmetric = ppw->pvecmetric;
a = pvecback[pba->index_bg_a];
a2 = a*a;
H = pvecback[pba->index_bg_H];
if (pba->has_ncdm == _TRUE_) {
class_alloc(delta_ncdm, sizeof(double)*pba->N_ncdm,error_message);
class_alloc(theta_ncdm, sizeof(double)*pba->N_ncdm,error_message);
class_alloc(shear_ncdm, sizeof(double)*pba->N_ncdm,error_message);
class_alloc(delta_p_over_delta_rho_ncdm, sizeof(double)*pba->N_ncdm,error_message);
}
/** - calculate perturbed recombination */
if ((ppt->has_perturbed_recombination == _TRUE_) && (ppw->approx[ppw->index_ap_tca] == (int)tca_off) ) {
delta_temp = y[ppw->pv->index_pt_perturbed_recombination_delta_temp];
delta_chi =y[ppw->pv->index_pt_perturbed_recombination_delta_chi];
}
/** - for scalar modes */
if (_scalars_) {
if (ppw->approx[ppw->index_ap_rsa]==(int)rsa_off) {
delta_g = y[ppw->pv->index_pt_delta_g];
theta_g = y[ppw->pv->index_pt_theta_g];
}
else {
delta_g = ppw->rsa_delta_g;
theta_g = ppw->rsa_theta_g;
}
if (ppw->approx[ppw->index_ap_rsa]==(int)rsa_off) {
if (ppw->approx[ppw->index_ap_tca]==(int)tca_on) {
shear_g = ppw->tca_shear_g;
//l3_g = 6./7.*k/ppw->pvecthermo[pth->index_th_dkappa]*ppw->tca_shear_g;
pol0_g = 2.5*ppw->tca_shear_g;
pol1_g = 7./12.*6./7.*k/ppw->pvecthermo[pth->index_th_dkappa]*ppw->tca_shear_g;
pol2_g = 0.5*ppw->tca_shear_g;
//pol3_g = 0.25*6./7.*k/ppw->pvecthermo[pth->index_th_dkappa]*ppw->tca_shear_g;
}
else {
shear_g = y[ppw->pv->index_pt_shear_g];
//l3_g = y[ppw->pv->index_pt_l3_g];
pol0_g = y[ppw->pv->index_pt_pol0_g];
pol1_g = y[ppw->pv->index_pt_pol1_g];
pol2_g = y[ppw->pv->index_pt_pol2_g];
//pol3_g = y[ppw->pv->index_pt_pol3_g];
}
}
else {
shear_g = 0;
//l3_g = 0;
pol0_g = 0;
pol1_g = 0;
pol2_g = 0;
//pol3_g = 0.;
}
if (pba->has_ur == _TRUE_) {
if (ppw->approx[ppw->index_ap_rsa]==(int)rsa_off) {
delta_ur = y[ppw->pv->index_pt_delta_ur];
theta_ur = y[ppw->pv->index_pt_theta_ur];
shear_ur = y[ppw->pv->index_pt_shear_ur];
}
else {
delta_ur = ppw->rsa_delta_ur;
theta_ur = ppw->rsa_theta_ur;
shear_ur = 0.;
}
}
delta_b = y[ppw->pv->index_pt_delta_b];
theta_b = y[ppw->pv->index_pt_theta_b];
if (pba->has_cdm == _TRUE_) {
delta_cdm = y[ppw->pv->index_pt_delta_cdm];
if (ppt->gauge == synchronous) {
theta_cdm = 0.;
}
else {
theta_cdm = y[ppw->pv->index_pt_theta_cdm];
}
}
/* gravitational potentials */
if (ppt->gauge == synchronous) {
alpha = pvecmetric[ppw->index_mt_alpha];
psi = pvecback[pba->index_bg_H]*pvecback[pba->index_bg_a] * alpha + pvecmetric[ppw->index_mt_alpha_prime];
phi = y[ppw->pv->index_pt_eta] - pvecback[pba->index_bg_H]*pvecback[pba->index_bg_a]*alpha;
}
else if (ppt->gauge == newtonian) {
psi = pvecmetric[ppw->index_mt_psi];
phi = y[ppw->pv->index_pt_phi];
}
else {
psi = 0.0;
phi = 0.0;
}
if (pba->has_ncdm == _TRUE_) {
/** - --> Get delta, deltaP/rho, theta, shear and store in array */
idx = ppw->pv->index_pt_psi0_ncdm1;
if(ppw->approx[ppw->index_ap_ncdmfa] == (int)ncdmfa_on) {
// The perturbations are evolved integrated:
for(n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
rho_ncdm_bg = pvecback[pba->index_bg_rho_ncdm1+n_ncdm];
p_ncdm_bg = pvecback[pba->index_bg_p_ncdm1+n_ncdm];
pseudo_p_ncdm = pvecback[pba->index_bg_pseudo_p_ncdm1+n_ncdm];
w_ncdm = p_ncdm_bg/rho_ncdm_bg;
delta_ncdm[n_ncdm] = y[idx];
theta_ncdm[n_ncdm] = y[idx+1];
shear_ncdm[n_ncdm] = y[idx+2];
//This is the adiabatic sound speed:
delta_p_over_delta_rho_ncdm[n_ncdm] = w_ncdm*(1.0-1.0/(3.0+3.0*w_ncdm)*(3.0*w_ncdm-2.0+pseudo_p_ncdm/p_ncdm_bg));
idx += ppw->pv->l_max_ncdm[n_ncdm]+1;
}
}
else {
// We must integrate to find perturbations:
for(n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
rho_delta_ncdm = 0.0;
rho_plus_p_theta_ncdm = 0.0;
rho_plus_p_shear_ncdm = 0.0;
delta_p_ncdm = 0.0;
factor = pba->factor_ncdm[n_ncdm]*pow(pba->a_today/a,4);
for (index_q=0; index_q < ppw->pv->q_size_ncdm[n_ncdm]; index_q ++) {
q = pba->q_ncdm[n_ncdm][index_q];
q2 = q*q;
epsilon = sqrt(q2+pba->M_ncdm[n_ncdm]*pba->M_ncdm[n_ncdm]*a2);
rho_delta_ncdm += q2*epsilon*pba->w_ncdm[n_ncdm][index_q]*y[idx];
rho_plus_p_theta_ncdm += q2*q*pba->w_ncdm[n_ncdm][index_q]*y[idx+1];
rho_plus_p_shear_ncdm += q2*q2/epsilon*pba->w_ncdm[n_ncdm][index_q]*y[idx+2];
delta_p_ncdm += q2*q2/epsilon*pba->w_ncdm[n_ncdm][index_q]*y[idx];
//Jump to next momentum bin:
idx+=(ppw->pv->l_max_ncdm[n_ncdm]+1);
}
rho_delta_ncdm *= factor;
rho_plus_p_theta_ncdm *= k*factor;
rho_plus_p_shear_ncdm *= 2.0/3.0*factor;
delta_p_ncdm *= factor/3.;
delta_ncdm[n_ncdm] = rho_delta_ncdm/ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm];
theta_ncdm[n_ncdm] = rho_plus_p_theta_ncdm/
(ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]+ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm]);
shear_ncdm[n_ncdm] = rho_plus_p_shear_ncdm/
(ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]+ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm]);
delta_p_over_delta_rho_ncdm[n_ncdm] = delta_p_ncdm/rho_delta_ncdm;
if (delta_p_over_delta_rho_ncdm[n_ncdm] < -0.5) {
FILE * fid = fopen("integrand.dat","w");
fclose(fid);
}
}
}
}
if (pba->has_dcdm == _TRUE_) {
delta_dcdm = y[ppw->pv->index_pt_delta_dcdm];
theta_dcdm = y[ppw->pv->index_pt_theta_dcdm];
}
if (pba->has_dr == _TRUE_) {
f_dr = pow(pvecback[pba->index_bg_a]*pvecback[pba->index_bg_a]/pba->H0,2)*pvecback[pba->index_bg_rho_dr];
delta_dr = y[ppw->pv->index_pt_F0_dr]/f_dr;
theta_dr = y[ppw->pv->index_pt_F0_dr+1]*3./4.*k/f_dr;
shear_dr = y[ppw->pv->index_pt_F0_dr+2]*0.5/f_dr;
}
if (pba->has_scf == _TRUE_) {
if (ppt->gauge == synchronous) {
delta_rho_scf = 1./3.*
(1./a2*ppw->pvecback[pba->index_bg_phi_prime_scf]*y[ppw->pv->index_pt_phi_prime_scf]
+ ppw->pvecback[pba->index_bg_dV_scf]*y[ppw->pv->index_pt_phi_scf]);
}
else {
delta_rho_scf = 1./3.*
(1./a2*ppw->pvecback[pba->index_bg_phi_prime_scf]*y[ppw->pv->index_pt_phi_prime_scf]
+ ppw->pvecback[pba->index_bg_dV_scf]*y[ppw->pv->index_pt_phi_scf]
- 1./a2*pow(ppw->pvecback[pba->index_bg_phi_prime_scf],2)*ppw->pvecmetric[ppw->index_mt_psi]);
}
rho_plus_p_theta_scf = 1./3.*
k*k/a2*ppw->pvecback[pba->index_bg_phi_prime_scf]*y[ppw->pv->index_pt_phi_scf];
delta_scf = delta_rho_scf/pvecback[pba->index_bg_rho_scf];
theta_scf = rho_plus_p_theta_scf/(pvecback[pba->index_bg_rho_scf]+pvecback[pba->index_bg_p_scf]);
}
/* converting synchronous variables to newtonian ones */
if (ppt->gauge == synchronous) {
/* density and velocity perturbations (comment out if you wish to keep synchronous variables) */
delta_g -= 4. * pvecback[pba->index_bg_H]*pvecback[pba->index_bg_a]*alpha;
theta_g += k*k*alpha;
delta_b -= 3. * pvecback[pba->index_bg_H]*pvecback[pba->index_bg_a]*alpha;
theta_b += k*k*alpha;
if (pba->has_ur == _TRUE_) {
delta_ur -= 4. * pvecback[pba->index_bg_H]*pvecback[pba->index_bg_a]*alpha;
theta_ur += k*k*alpha;
}
if (pba->has_dr == _TRUE_) {
delta_dr += (-4.*a*H+a*pba->Gamma_dcdm*pvecback[pba->index_bg_rho_dcdm]/pvecback[pba->index_bg_rho_dr])*alpha;
theta_dr += k*k*alpha;
}
if (pba->has_cdm == _TRUE_) {
delta_cdm -= 3. * pvecback[pba->index_bg_H]*pvecback[pba->index_bg_a]*alpha;
theta_cdm += k*k*alpha;
}
if (pba->has_ncdm == _TRUE_) {
for(n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
/** - --> Do gauge transformation of delta, deltaP/rho (?) and theta using -= 3aH(1+w_ncdm) alpha for delta. */
}
}
if (pba->has_dcdm == _TRUE_) {
delta_dcdm += alpha*(-a*pba->Gamma_dcdm-3.*a*H);
theta_dcdm += k*k*alpha;
}
if (pba->has_scf == _TRUE_) {
delta_scf += alpha*(-3.0*H*(1.0+pvecback[pba->index_bg_p_scf]/pvecback[pba->index_bg_rho_scf]));
theta_scf += k*k*alpha;
}
}
// fprintf(ppw->perturb_output_file," ");
/** - --> Handle (re-)allocation */
if (ppt->scalar_perturbations_data[ppw->index_ikout] == NULL) {
class_alloc(ppt->scalar_perturbations_data[ppw->index_ikout],
sizeof(double)*ppt->number_of_scalar_titles,
error_message);
ppt->size_scalar_perturbation_data[ppw->index_ikout] = 0;
}
else {
ppt->scalar_perturbations_data[ppw->index_ikout] =
realloc(ppt->scalar_perturbations_data[ppw->index_ikout],
sizeof(double)*(ppt->size_scalar_perturbation_data[ppw->index_ikout]+ppt->number_of_scalar_titles));
}
storeidx = 0;
dataptr = ppt->scalar_perturbations_data[ppw->index_ikout]+
ppt->size_scalar_perturbation_data[ppw->index_ikout];
ppt->size_scalar_perturbation_data[ppw->index_ikout] += ppt->number_of_scalar_titles;
class_store_double(dataptr, tau, _TRUE_, storeidx);
class_store_double(dataptr, pvecback[pba->index_bg_a], _TRUE_, storeidx);
class_store_double(dataptr, delta_g, _TRUE_, storeidx);
class_store_double(dataptr, theta_g, _TRUE_, storeidx);
class_store_double(dataptr, shear_g, _TRUE_, storeidx);
class_store_double(dataptr, pol0_g, _TRUE_, storeidx);
class_store_double(dataptr, pol1_g, _TRUE_, storeidx);
class_store_double(dataptr, pol2_g, _TRUE_, storeidx);
class_store_double(dataptr, delta_b, _TRUE_, storeidx);
class_store_double(dataptr, theta_b, _TRUE_, storeidx);
class_store_double(dataptr, psi, _TRUE_, storeidx);
class_store_double(dataptr, phi, _TRUE_, storeidx);
/* perturbed recombination */
class_store_double(dataptr, delta_temp, ppt->has_perturbed_recombination, storeidx);
class_store_double(dataptr, delta_chi, ppt->has_perturbed_recombination, storeidx);
/* Ultra relativistic species */
class_store_double(dataptr, delta_ur, pba->has_ur, storeidx);
class_store_double(dataptr, theta_ur, pba->has_ur, storeidx);
class_store_double(dataptr, shear_ur, pba->has_ur, storeidx);
/* Cold dark matter */
class_store_double(dataptr, delta_cdm, pba->has_cdm, storeidx);
class_store_double(dataptr, theta_cdm, pba->has_cdm, storeidx);
/* Non-cold Dark Matter */
if ((pba->has_ncdm == _TRUE_) && ((ppt->has_density_transfers == _TRUE_) || (ppt->has_velocity_transfers == _TRUE_) || (ppt->has_source_delta_m == _TRUE_))) {
for(n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
class_store_double(dataptr, delta_ncdm[n_ncdm], _TRUE_, storeidx);
class_store_double(dataptr, theta_ncdm[n_ncdm], _TRUE_, storeidx);
class_store_double(dataptr, shear_ncdm[n_ncdm], _TRUE_, storeidx);
class_store_double(dataptr, delta_p_over_delta_rho_ncdm[n_ncdm], _TRUE_, storeidx);
}
}
/* Decaying cold dark matter */
class_store_double(dataptr, delta_dcdm, pba->has_dcdm, storeidx);
class_store_double(dataptr, theta_dcdm, pba->has_dcdm, storeidx);
/* Decay radiation */
class_store_double(dataptr, delta_dr, pba->has_dr, storeidx);
class_store_double(dataptr, theta_dr, pba->has_dr, storeidx);
class_store_double(dataptr, shear_dr, pba->has_dr, storeidx);
/* Scalar field scf*/
class_store_double(dataptr, delta_scf, pba->has_scf, storeidx);
class_store_double(dataptr, theta_scf, pba->has_scf, storeidx);
//fprintf(ppw->perturb_output_file,"\n");
}
/** - for tensor modes: */
if (_tensors_) {
if (ppw->approx[ppw->index_ap_rsa]==(int)rsa_off) {
if (ppw->approx[ppw->index_ap_tca]==(int)tca_off) {
delta_g = y[ppw->pv->index_pt_delta_g];
shear_g = y[ppw->pv->index_pt_shear_g];
l4_g = y[ppw->pv->index_pt_delta_g+4];
pol0_g = y[ppw->pv->index_pt_pol0_g];
pol2_g = y[ppw->pv->index_pt_pol2_g];
pol4_g = y[ppw->pv->index_pt_pol0_g+4];
}
else {
delta_g = -4./3.*ppw->pv->y[ppw->pv->index_pt_gwdot]/ppw->pvecthermo[pth->index_th_dkappa]; //TBC
shear_g = 0.;
l4_g = 0.;
pol0_g = 1./3.*ppw->pv->y[ppw->pv->index_pt_gwdot]/ppw->pvecthermo[pth->index_th_dkappa]; //TBC
pol2_g = 0.;
pol4_g = 0.;
}
}
else {
delta_g = 0.;
shear_g = 0.;
l4_g = 0.;
pol0_g = 0.;
pol2_g = 0.;
pol4_g = 0.;
}
if (ppt->evolve_tensor_ur == _TRUE_) {
delta_ur = y[ppw->pv->index_pt_delta_ur];
shear_ur = y[ppw->pv->index_pt_shear_ur];
l4_ur = y[ppw->pv->index_pt_delta_ur+4];
}
/** - --> Handle (re-)allocation */
if (ppt->tensor_perturbations_data[ppw->index_ikout] == NULL) {
class_alloc(ppt->tensor_perturbations_data[ppw->index_ikout],
sizeof(double)*ppt->number_of_tensor_titles,
error_message);
ppt->size_tensor_perturbation_data[ppw->index_ikout] = 0;
}
else {
ppt->tensor_perturbations_data[ppw->index_ikout] =
realloc(ppt->tensor_perturbations_data[ppw->index_ikout],
sizeof(double)*(ppt->size_tensor_perturbation_data[ppw->index_ikout]+ppt->number_of_tensor_titles));
}
storeidx = 0;
dataptr = ppt->tensor_perturbations_data[ppw->index_ikout]+
ppt->size_tensor_perturbation_data[ppw->index_ikout];
ppt->size_tensor_perturbation_data[ppw->index_ikout] += ppt->number_of_tensor_titles;
//fprintf(ppw->perturb_output_file," ");
class_store_double(dataptr, tau, _TRUE_, storeidx);
class_store_double(dataptr, pvecback[pba->index_bg_a], _TRUE_, storeidx);
class_store_double(dataptr, delta_g, _TRUE_, storeidx);
class_store_double(dataptr, shear_g, _TRUE_, storeidx);
class_store_double(dataptr, l4_g, _TRUE_, storeidx);
class_store_double(dataptr, pol0_g, _TRUE_, storeidx);
class_store_double(dataptr, pol2_g, _TRUE_, storeidx);
class_store_double(dataptr, pol4_g, _TRUE_, storeidx);
class_store_double(dataptr, y[ppw->pv->index_pt_gw], _TRUE_, storeidx);
class_store_double(dataptr, y[ppw->pv->index_pt_gwdot], _TRUE_, storeidx);
class_store_double(dataptr, delta_ur, ppt->evolve_tensor_ur, storeidx);
class_store_double(dataptr, shear_ur, ppt->evolve_tensor_ur, storeidx);
class_store_double(dataptr, l4_ur, ppt->evolve_tensor_ur, storeidx);
//printf("index_pt_delta+ur = %d\n",ppw->pv->index_pt_delta_ur);
/* Non-cold Dark Matter */
if (ppt->evolve_tensor_ncdm == _TRUE_) {
idx = ppw->pv->index_pt_psi0_ncdm1;
for(n_ncdm=0; n_ncdm < pba->N_ncdm; n_ncdm++) {
rho_delta_ncdm = 0.0;
rho_plus_p_theta_ncdm = 0.0;
rho_plus_p_shear_ncdm = 0.0;
delta_p_ncdm = 0.0;
factor = pba->factor_ncdm[n_ncdm]*pow(pba->a_today/a,4);
for (index_q=0; index_q < ppw->pv->q_size_ncdm[n_ncdm]; index_q ++) {
q = pba->q_ncdm[n_ncdm][index_q];
q2 = q*q;
epsilon = sqrt(q2+pba->M_ncdm[n_ncdm]*pba->M_ncdm[n_ncdm]*a2);
rho_delta_ncdm += q2*epsilon*pba->w_ncdm[n_ncdm][index_q]*y[idx];
rho_plus_p_theta_ncdm += q2*q*pba->w_ncdm[n_ncdm][index_q]*y[idx+1];
rho_plus_p_shear_ncdm += q2*q2/epsilon*pba->w_ncdm[n_ncdm][index_q]*y[idx+2];
delta_p_ncdm += q2*q2/epsilon*pba->w_ncdm[n_ncdm][index_q]*y[idx];
//Jump to next momentum bin:
idx+=(ppw->pv->l_max_ncdm[n_ncdm]+1);
}
rho_delta_ncdm *= factor;
rho_plus_p_theta_ncdm *= k*factor;
rho_plus_p_shear_ncdm *= 2.0/3.0*factor;
delta_p_ncdm *= factor/3.;
delta_ncdm[n_ncdm] = rho_delta_ncdm/ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm];
theta_ncdm[n_ncdm] = rho_plus_p_theta_ncdm/
(ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]+ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm]);
shear_ncdm[n_ncdm] = rho_plus_p_shear_ncdm/
(ppw->pvecback[pba->index_bg_rho_ncdm1+n_ncdm]+ppw->pvecback[pba->index_bg_p_ncdm1+n_ncdm]);
class_store_double(dataptr, delta_ncdm[n_ncdm], _TRUE_, storeidx);
class_store_double(dataptr, theta_ncdm[n_ncdm], _TRUE_, storeidx);
class_store_double(dataptr, shear_ncdm[n_ncdm], _TRUE_, storeidx);
}
}
// fprintf(ppw->perturb_output_file,"\n");
}
if (pba->has_ncdm == _TRUE_) {
free(delta_ncdm);
free(theta_ncdm);
free(shear_ncdm);
free(delta_p_over_delta_rho_ncdm);
}
return _SUCCESS_;
}
/**
* Compute derivative of all perturbations to be integrated
*
* For each mode (scalar/vector/tensor) and each wavenumber k, this
* function computes the derivative of all values in the vector of
* perturbed variables to be integrated.
*
* This is one of the few functions in the code which is passed to the generic_integrator() routine.
* Since generic_integrator() should work with functions passed from various modules, the format of the arguments
* is a bit special:
* - fixed parameters and workspaces are passed through a generic pointer.
* generic_integrator() doesn't know what the content of this pointer is.
* - errors are not written as usual in pth->error_message, but in a generic
* error_message passed in the list of arguments.
*
* @param tau Input: conformal time
* @param y Input: vector of perturbations
* @param dy Output: vector of its derivatives (already allocated)
* @param parameters_and_workspace Input/Output: in input, fixed parameters (e.g. indices); in output, background and thermo quantities evaluated at tau.
* @param error_message Output: error message
*/
int perturb_derivs(double tau,
double * y,
double * dy,
void * parameters_and_workspace,
ErrorMsg error_message
) {
/** Summary: */
/** - define local variables */
/* multipole */
int l;
/* scale factor and other background quantities */
double a,a2,a_prime_over_a,R;
/* short-cut names for the fields of the input structure */
struct perturb_parameters_and_workspace * pppaw;
double k,k2;
int index_md;
struct precision * ppr;
struct background * pba;
struct thermo * pth;
struct perturbs * ppt;
struct perturb_workspace * ppw;
double * pvecback;
double * pvecthermo;
double * pvecmetric;
double * s_l;
struct perturb_vector * pv;
/* short-cut notations for the perturbations */
double delta_g=0.,theta_g=0.,shear_g=0.;
double delta_b,theta_b;
double cb2,cs2,ca2;
double metric_continuity=0.,metric_euler=0.,metric_shear=0.,metric_ufa_class=0.;
/* perturbed recombination (just to simplify the notation) */
double H0=0.,Nnow=0.,n_H=0.,fHe=0.;
double delta_temp=0.,delta_chi=0., chi=0.;
double alpha_rec=0.,delta_alpha_rec=0.;
double a_rad=0., Compton_CR =0.;
double Tb_in_K=0.;
/* Non-metric source terms for photons, i.e. \mathcal{P}^{(m)} from arXiv:1305.3261 */
double P0,P1,P2;
/* for use with fluid (fld): */
double w,w_prime;
/* for use with non-cold dark matter (ncdm): */
int index_q,n_ncdm,idx;
double q,epsilon,dlnf0_dlnq,qk_div_epsilon;
double rho_ncdm_bg,p_ncdm_bg,pseudo_p_ncdm,w_ncdm,ca2_ncdm,ceff2_ncdm=0.,cvis2_ncdm=0.;
/* for use with curvature */
double cotKgen, sqrt_absK;
double s2_squared, ssqrt3;
/* for use with dcdm and dr */
double f_dr, fprime_dr;
/** - rename the fields of the input structure (just to avoid heavy notations) */
pppaw = parameters_and_workspace;
k = pppaw->k;
k2=k*k;
index_md = pppaw->index_md;
ppr = pppaw->ppr;
pba = pppaw->pba;
pth = pppaw->pth;
ppt = pppaw->ppt;
ppw = pppaw->ppw;
s_l = ppw->s_l;
pvecback = ppw->pvecback;
pvecthermo = ppw->pvecthermo;
pvecmetric = ppw->pvecmetric;
pv = ppw->pv;
/** - get background/thermo quantities in this point */
class_call(background_at_tau(pba,
tau,
pba->normal_info,
pba->inter_closeby,
&(ppw->last_index_back),
pvecback),
pba->error_message,
error_message);
class_call(thermodynamics_at_z(pba,
pth,
1./pvecback[pba->index_bg_a]-1., /* redshift z=1/a-1 */
pth->inter_closeby,
&(ppw->last_index_thermo),
pvecback,
pvecthermo),
pth->error_message,
error_message);
/** - get metric perturbations with perturb_einstein() */
class_call(perturb_einstein(ppr,
pba,
pth,
ppt,
index_md,
k,
tau,
y,
ppw),
ppt->error_message,
error_message);
/** - compute related background quantities */
a = pvecback[pba->index_bg_a];
a2 = a*a;
a_prime_over_a = pvecback[pba->index_bg_H] * a;
R = 4./3. * pvecback[pba->index_bg_rho_g]/pvecback[pba->index_bg_rho_b];
/** - Compute 'generalised cotK function of argument \f$ \sqrt{|K|}*\tau \f$, for closing hierarchy.
(see equation 2.34 in arXiv:1305.3261): */
if (pba->has_curvature == _FALSE_) {
cotKgen = 1.0/(k*tau);
}
else {
sqrt_absK = sqrt(fabs(pba->K));
if (pba->K < 0)
cotKgen = sqrt_absK/k/tanh(sqrt_absK*tau);
else
cotKgen = sqrt_absK/k/tan(sqrt_absK*tau);
}
s2_squared = 1.-3.*pba->K/k2;
/** - for scalar modes: */
if (_scalars_) {
/** - --> (a) define short-cut notations for the scalar perturbations */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
delta_g = y[pv->index_pt_delta_g];
theta_g = y[pv->index_pt_theta_g];
}
delta_b = y[pv->index_pt_delta_b];
theta_b = y[pv->index_pt_theta_b];
cb2 = pvecthermo[pth->index_th_cb2];
/** - --> (b) perturbed recombination **/
if ((ppt->has_perturbed_recombination == _TRUE_)&&(ppw->approx[ppw->index_ap_tca]==(int)tca_off)) {
delta_temp= y[ppw->pv->index_pt_perturbed_recombination_delta_temp];
delta_chi= y[ppw->pv->index_pt_perturbed_recombination_delta_chi];
chi=pvecthermo[pth->index_th_xe];
// Conversion of H0 in inverse seconds (pba->H0 is [H0/c] in inverse Mpcs)
H0 = pba->H0 * _c_ / _Mpc_over_m_;
//Computation of Nnow in SI units
Nnow = 3.*H0*H0*pba->Omega0_b*(1.-pth->YHe)/(8.*_PI_*_G_*_m_H_);
// total amount of hydrogen today
n_H = (pba->a_today/a)*(pba->a_today/a)*(pba->a_today/a)* Nnow;
// Helium-to-hydrogen ratio
fHe = pth->YHe / (_not4_*(1-pth->YHe));
// The constant such that rho_gamma = a_rad * T^4
a_rad = 8./15.*pow(_PI_,5)*pow(_k_B_,4)/pow(_c_*_h_P_,3);
// Compton cooling rate in Mpc^(-1)
Compton_CR = 8./3. *_sigma_ * a_rad /(_m_e_ * _c_ *_c_) *_Mpc_over_m_ ;
// Temperature is already in Kelvin
Tb_in_K = pvecthermo[pth->index_th_Tb];
// Alpha in m^3/s, cf. Recfast paper
alpha_rec = 1.14 * 4.309e-19*pow((Tb_in_K * 1e-4),-0.6166)/(1+0.6703*pow((Tb_in_K * 1e-4),0.53)) ;
// delta alpha, dimensionless
delta_alpha_rec= (-0.6166 + 0.6703 * pow((Tb_in_K * 1e-4),0.53)*(-0.6166-0.53))/(1+0.6703*pow((Tb_in_K * 1e-4),0.53)) * delta_temp;
} // end of perturbed recombination related quantities
/** - --> (c) compute metric-related quantities (depending on gauge; additional gauges can be coded below)
- Each continuity equation contains a term in (theta+metric_continuity) with
metric_continuity = (h_prime/2) in synchronous gauge, (-3 phi_prime) in newtonian gauge
- Each Euler equation contains a source term metric_euler with
metric_euler = 0 in synchronous gauge, (k2 psi) in newtonian gauge
- Each shear derivative equation contains a source term metric_shear equal to
metric_shear = (h_prime+6eta_prime)/2 in synchronous gauge, 0 in newtonian gauge
- metric_shear_prime is the derivative of metric_shear
- In the ufa_class approximation, the leading-order source term is (h_prime/2) in synchronous gauge,
(-3 (phi_prime+psi_prime)) in newtonian gauge: we approximate the later by (-6 phi_prime) */
if (ppt->gauge == synchronous) {
metric_continuity = pvecmetric[ppw->index_mt_h_prime]/2.;
metric_euler = 0.;
metric_shear = k2 * pvecmetric[ppw->index_mt_alpha];
//metric_shear_prime = k2 * pvecmetric[ppw->index_mt_alpha_prime];
metric_ufa_class = pvecmetric[ppw->index_mt_h_prime]/2.;
}
if (ppt->gauge == newtonian) {
metric_continuity = -3.*pvecmetric[ppw->index_mt_phi_prime];
metric_euler = k2*pvecmetric[ppw->index_mt_psi];
metric_shear = 0.;
//metric_shear_prime = 0.;
metric_ufa_class = -6.*pvecmetric[ppw->index_mt_phi_prime];
}
/** - --> (d) if some approximation schemes are turned on, enforce a few y[] values computed in perturb_einstein */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_on) {
delta_g = ppw->rsa_delta_g;
theta_g = ppw->rsa_theta_g;
}
/** - --> (e) BEGINNING OF ACTUAL SYSTEM OF EQUATIONS OF EVOLUTION */
/* Note concerning perturbed recombination: $cb2*delta_b$ must be replaced everywhere by $cb2*(delta_b+delta_temp)$. If perturbed recombination is not required, delta_temp is equal to zero. */
/** - ---> photon temperature density */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
dy[pv->index_pt_delta_g] = -4./3.*(theta_g+metric_continuity);
}
/** - ---> baryon density */
dy[pv->index_pt_delta_b] = -(theta_b+metric_continuity);
/** - ---> baryon velocity (depends on tight-coupling approximation=tca) */
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) {
/* without tca */
/** - ----> perturbed recombination has an impact **/
dy[pv->index_pt_theta_b] =
- a_prime_over_a*theta_b
+ metric_euler
+ k2*cb2*(delta_b+delta_temp)
+ R*pvecthermo[pth->index_th_dkappa]*(theta_g-theta_b);
}
else {
/* with tca */
class_call(perturb_tca_slip_and_shear(y,pppaw,error_message),
error_message,
error_message);
/* perturbed recombination has an impact **/
dy[pv->index_pt_theta_b] =
(-a_prime_over_a*theta_b
+k2*(cb2*(delta_b+delta_temp)+R*(delta_g/4.-s2_squared*ppw->tca_shear_g))
+R*ppw->tca_slip)/(1.+R)
+metric_euler;
}
/** - ---> photon temperature higher momenta and photon polarization (depend on tight-coupling approximation) */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
/** - ----> if photon tight-coupling is off */
if (ppw->approx[ppw->index_ap_tca] == (int)tca_off) {
/** - -----> define \f$ \Pi = G_{\gamma 0} + G_{\gamma 2} + F_{\gamma 2} \f$ */
P0 = (y[pv->index_pt_pol0_g] + y[pv->index_pt_pol2_g] + 2.*s_l[2]*y[pv->index_pt_shear_g])/8.;
/** - -----> photon temperature velocity */
dy[pv->index_pt_theta_g] =
k2*(delta_g/4.-s2_squared*y[pv->index_pt_shear_g])
+ metric_euler
+ pvecthermo[pth->index_th_dkappa]*(theta_b-theta_g);
/** - -----> photon temperature shear */
dy[pv->index_pt_shear_g] =
0.5*(8./15.*(theta_g+metric_shear)
-3./5.*k*s_l[3]/s_l[2]*y[pv->index_pt_l3_g]
-pvecthermo[pth->index_th_dkappa]*(2.*y[pv->index_pt_shear_g]-4./5./s_l[2]*P0));
/** - -----> photon temperature l=3 */
l = 3;
dy[pv->index_pt_l3_g] = k/(2.0*l+1.0)*
(l*s_l[l]*2.*s_l[2]*y[pv->index_pt_shear_g]-(l+1.)*s_l[l+1]*y[pv->index_pt_l3_g+1])
- pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_l3_g];
/** - -----> photon temperature l>3 */
for (l = 4; l < pv->l_max_g; l++) {
dy[pv->index_pt_delta_g+l] = k/(2.0*l+1.0)*
(l*s_l[l]*y[pv->index_pt_delta_g+l-1]-(l+1)*s_l[l+1]*y[pv->index_pt_delta_g+l+1])
- pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_delta_g+l];
}
/** - -----> photon temperature lmax */
l = pv->l_max_g; /* l=lmax */
dy[pv->index_pt_delta_g+l] =
k*(s_l[l]*y[pv->index_pt_delta_g+l-1]-(1.+l)*cotKgen*y[pv->index_pt_delta_g+l])
- pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_delta_g+l];
/** - -----> photon polarization l=0 */
dy[pv->index_pt_pol0_g] =
-k*y[pv->index_pt_pol0_g+1]
-pvecthermo[pth->index_th_dkappa]*(y[pv->index_pt_pol0_g]-4.*P0);
/** - -----> photon polarization l=1 */
dy[pv->index_pt_pol1_g] =
k/3.*(y[pv->index_pt_pol1_g-1]-2.*s_l[2]*y[pv->index_pt_pol1_g+1])
-pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_pol1_g];
/** - -----> photon polarization l=2 */
dy[pv->index_pt_pol2_g] =
k/5.*(2.*s_l[2]*y[pv->index_pt_pol2_g-1]-3.*s_l[3]*y[pv->index_pt_pol2_g+1])
-pvecthermo[pth->index_th_dkappa]*(y[pv->index_pt_pol2_g]-4./5.*P0);
/** - -----> photon polarization l>2 */
for (l=3; l < pv->l_max_pol_g; l++)
dy[pv->index_pt_pol0_g+l] = k/(2.*l+1)*
(l*s_l[l]*y[pv->index_pt_pol0_g+l-1]-(l+1.)*s_l[l+1]*y[pv->index_pt_pol0_g+l+1])
-pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_pol0_g+l];
/** - -----> photon polarization lmax_pol */
l = pv->l_max_pol_g;
dy[pv->index_pt_pol0_g+l] =
k*(s_l[l]*y[pv->index_pt_pol0_g+l-1]-(l+1)*cotKgen*y[pv->index_pt_pol0_g+l])
-pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_pol0_g+l];
}
/** - ----> if photon tight-coupling is on: */
else {
/** - -----> in that case, only need photon velocity */
/* perturbed recombination has an impact **/
dy[pv->index_pt_theta_g] =
-(dy[pv->index_pt_theta_b]+a_prime_over_a*theta_b-cb2*k2*(delta_b+delta_temp))/R
+k2*(0.25*delta_g-s2_squared*ppw->tca_shear_g)+(1.+R)/R*metric_euler;
}
}
/** - ---> cdm */
if (pba->has_cdm == _TRUE_) {
/** - ----> newtonian gauge: cdm density and velocity */
if (ppt->gauge == newtonian) {
dy[pv->index_pt_delta_cdm] = -(y[pv->index_pt_theta_cdm]+metric_continuity); /* cdm density */
dy[pv->index_pt_theta_cdm] = - a_prime_over_a*y[pv->index_pt_theta_cdm] + metric_euler; /* cdm velocity */
}
/** - ----> synchronous gauge: cdm density only (velocity set to zero by definition of the gauge) */
if (ppt->gauge == synchronous) {
dy[pv->index_pt_delta_cdm] = -metric_continuity; /* cdm density */
}
}
/* perturbed recombination */
/* computes the derivatives of delta x_e and delta T_b */
if((ppt->has_perturbed_recombination == _TRUE_)&&(ppw->approx[ppw->index_ap_tca] == (int)tca_off)) {
// alpha * n_H is in inverse seconds, so we have to multiply it by Mpc_in_sec
dy[ppw->pv->index_pt_perturbed_recombination_delta_chi] = - alpha_rec* a * chi*n_H *(delta_alpha_rec + delta_chi + delta_b) * _Mpc_over_m_ / _c_ ;
// see the documentation for this formula
dy[ppw->pv->index_pt_perturbed_recombination_delta_temp] = 2./3. * dy[ppw->pv->index_pt_delta_b] - a * Compton_CR * pow(pba->T_cmb/a, 4) * chi / (1.+chi+fHe) * ( (1.-pba->T_cmb*pba->a_today/a/pvecthermo[pth->index_th_Tb])*(delta_g + delta_chi*(1.+fHe)/(1.+chi+fHe)) + pba->T_cmb*pba->a_today/a/pvecthermo[pth->index_th_Tb] *(delta_temp - 1./4. * delta_g) );
}
/** - ---> dcdm and dr */
if (pba->has_dcdm == _TRUE_) {
/** - ----> dcdm */
dy[pv->index_pt_delta_dcdm] = -(y[pv->index_pt_theta_dcdm]+metric_continuity)
- a * pba->Gamma_dcdm / k2 * metric_euler; /* dcdm density */
dy[pv->index_pt_theta_dcdm] = - a_prime_over_a*y[pv->index_pt_theta_dcdm] + metric_euler; /* dcdm velocity */
}
/** - ---> dr */
if ((pba->has_dcdm == _TRUE_)&&(pba->has_dr == _TRUE_)) {
/* f = rho_dr*a^4/rho_crit_today. In CLASS density units
rho_crit_today = H0^2.
*/
f_dr = pow(pow(a/pba->a_today,2)/pba->H0,2)*pvecback[pba->index_bg_rho_dr];
fprime_dr = pba->Gamma_dcdm*pvecback[pba->index_bg_rho_dcdm]*pow(a,5)/pow(pba->H0,2);
/** - ----> dr F0 */
dy[pv->index_pt_F0_dr] = -k*y[pv->index_pt_F0_dr+1]-4./3.*metric_continuity*f_dr+
fprime_dr*(y[pv->index_pt_delta_dcdm]+metric_euler/k2);
/** - ----> dr F1 */
dy[pv->index_pt_F0_dr+1] = k/3.*y[pv->index_pt_F0_dr]-2./3.*k*y[pv->index_pt_F0_dr+2]*s2_squared +
4*metric_euler/(3.*k)*f_dr + fprime_dr/k*y[pv->index_pt_theta_dcdm];
/** - ----> exact dr F2 */
dy[pv->index_pt_F0_dr+2] = 8./15.*(3./4.*k*y[pv->index_pt_F0_dr+1]+metric_shear*f_dr) -3./5.*k*s_l[3]/s_l[2]*y[pv->index_pt_F0_dr+3];
/** - ----> exact dr l=3 */
l = 3;
dy[pv->index_pt_F0_dr+3] = k/(2.*l+1.)*
(l*s_l[l]*s_l[2]*y[pv->index_pt_F0_dr+2]-(l+1.)*s_l[l+1]*y[pv->index_pt_F0_dr+4]);
/** - ----> exact dr l>3 */
for (l = 4; l < pv->l_max_dr; l++) {
dy[pv->index_pt_F0_dr+l] = k/(2.*l+1)*
(l*s_l[l]*y[pv->index_pt_F0_dr+l-1]-(l+1.)*s_l[l+1]*y[pv->index_pt_F0_dr+l+1]);
}
/** - ----> exact dr lmax_dr */
l = pv->l_max_dr;
dy[pv->index_pt_F0_dr+l] =
k*(s_l[l]*y[pv->index_pt_F0_dr+l-1]-(1.+l)*cotKgen*y[pv->index_pt_F0_dr+l]);
}
/** - ---> fluid (fld) */
/* if (pba->has_fld == _TRUE_) {*/
if ( 0 ) { // commented out so that no dark energy perturbations are included
/** - ----> factors w, w_prime, adiabatic sound speed ca2 (all three background-related),
plus actual sound speed in the fluid rest frame cs2 */
w = pba->w0_fld + pba->wa_fld * (1. - a / pba->a_today);
w_prime = - pba->wa_fld * a / pba->a_today * a_prime_over_a;
ca2 = w - w_prime / 3. / (1.+w) / a_prime_over_a;
cs2 = pba->cs2_fld;
/** - ----> fluid density */
dy[pv->index_pt_delta_fld] =
-(1+w)*(y[pv->index_pt_theta_fld]+metric_continuity)
-3.*(cs2-w)*a_prime_over_a*y[pv->index_pt_delta_fld]
-9.*(1+w)*(cs2-ca2)*a_prime_over_a*a_prime_over_a*y[pv->index_pt_theta_fld]/k2;
/** - ----> fluid velocity */
dy[pv->index_pt_theta_fld] = /* fluid velocity */
-(1.-3.*cs2)*a_prime_over_a*y[pv->index_pt_theta_fld]
+cs2*k2/(1.+w)*y[pv->index_pt_delta_fld]
+metric_euler;
}
/** - ---> scalar field (scf) */
if (pba->has_scf == _TRUE_) {
/** - ----> field value */
dy[pv->index_pt_phi_scf] = y[pv->index_pt_phi_prime_scf];
/** - ----> Klein Gordon equation */
dy[pv->index_pt_phi_prime_scf] = - 2.*a_prime_over_a*y[pv->index_pt_phi_prime_scf]
- metric_continuity*pvecback[pba->index_bg_phi_prime_scf] // metric_continuity = h'/2
- (k2 + a2*pvecback[pba->index_bg_ddV_scf])*y[pv->index_pt_phi_scf]; //checked
}
/** - ---> ultra-relativistic neutrino/relics (ur) */
if (pba->has_ur == _TRUE_) {
/** - ----> if radiation streaming approximation is off */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
/** - -----> ur density */
dy[pv->index_pt_delta_ur] =
// standard term
-4./3.*(y[pv->index_pt_theta_ur] + metric_continuity)
// non-standard term, non-zero if if ceff2_ur not 1/3
+(1.-ppt->three_ceff2_ur)*a_prime_over_a*(y[pv->index_pt_delta_ur] + 4.*a_prime_over_a*y[pv->index_pt_theta_ur]/k/k);
/** - -----> ur velocity */
dy[pv->index_pt_theta_ur] =
// standard term with extra coefficient (3 ceff2_ur), normally equal to one
k2*(ppt->three_ceff2_ur*y[pv->index_pt_delta_ur]/4.-s2_squared*y[pv->index_pt_shear_ur]) + metric_euler
// non-standard term, non-zero if ceff2_ur not 1/3
-(1.-ppt->three_ceff2_ur)*a_prime_over_a*y[pv->index_pt_theta_ur];
if(ppw->approx[ppw->index_ap_ufa] == (int)ufa_off) {
/** - -----> exact ur shear */
dy[pv->index_pt_shear_ur] =
0.5*(
// standard term
8./15.*(y[pv->index_pt_theta_ur]+metric_shear)-3./5.*k*s_l[3]/s_l[2]*y[pv->index_pt_shear_ur+1]
// non-standard term, non-zero if cvis2_ur not 1/3
-(1.-ppt->three_cvis2_ur)*(8./15.*(y[pv->index_pt_theta_ur]+metric_shear)));
/** - -----> exact ur l=3 */
l = 3;
dy[pv->index_pt_l3_ur] = k/(2.*l+1.)*
(l*2.*s_l[l]*s_l[2]*y[pv->index_pt_shear_ur]-(l+1.)*s_l[l+1]*y[pv->index_pt_l3_ur+1]);
/** - -----> exact ur l>3 */
for (l = 4; l < pv->l_max_ur; l++) {
dy[pv->index_pt_delta_ur+l] = k/(2.*l+1)*
(l*s_l[l]*y[pv->index_pt_delta_ur+l-1]-(l+1.)*s_l[l+1]*y[pv->index_pt_delta_ur+l+1]);
}
/** - -----> exact ur lmax_ur */
l = pv->l_max_ur;
dy[pv->index_pt_delta_ur+l] =
k*(s_l[l]*y[pv->index_pt_delta_ur+l-1]-(1.+l)*cotKgen*y[pv->index_pt_delta_ur+l]);
}
else {
/** - -----> in fluid approximation (ufa): only ur shear needed */
//TBC: curvature?
/* a la Ma & Bertschinger */
if (ppr->ur_fluid_approximation == ufa_mb) {
dy[pv->index_pt_shear_ur] =
-3./tau*y[pv->index_pt_shear_ur]
+2./3.*(y[pv->index_pt_theta_ur]+metric_shear);
}
/* a la Hu */
if (ppr->ur_fluid_approximation == ufa_hu) {
dy[pv->index_pt_shear_ur] =
-3.*a_prime_over_a*y[pv->index_pt_shear_ur]
+2./3.*(y[pv->index_pt_theta_ur]+metric_shear);
}
/* a la CLASS */
if (ppr->ur_fluid_approximation == ufa_CLASS) {
dy[pv->index_pt_shear_ur] =
-3./tau*y[pv->index_pt_shear_ur]
+2./3.*(y[pv->index_pt_theta_ur]+metric_ufa_class);
}
}
}
}
/** - ---> non-cold dark matter (ncdm): massive neutrinos, WDM, etc. */
//TBC: curvature in all ncdm
if (pba->has_ncdm == _TRUE_) {
idx = pv->index_pt_psi0_ncdm1;
/** - ----> first case: use a fluid approximation (ncdmfa) */
//TBC: curvature
if(ppw->approx[ppw->index_ap_ncdmfa] == (int)ncdmfa_on) {
/** - -----> loop over species */
for (n_ncdm=0; n_ncdm<pv->N_ncdm; n_ncdm++) {
/** - -----> define intermediate quantitites */
rho_ncdm_bg = pvecback[pba->index_bg_rho_ncdm1+n_ncdm]; /* background density */
p_ncdm_bg = pvecback[pba->index_bg_p_ncdm1+n_ncdm]; /* background pressure */
pseudo_p_ncdm = pvecback[pba->index_bg_pseudo_p_ncdm1+n_ncdm]; /* pseudo-pressure (see CLASS IV paper) */
w_ncdm = p_ncdm_bg/rho_ncdm_bg; /* equation of state parameter */
ca2_ncdm = w_ncdm/3.0/(1.0+w_ncdm)*(5.0-pseudo_p_ncdm/p_ncdm_bg); /* adiabatic sound speed */
/* c_eff is (delta p / delta rho) in the gauge under
consideration (not in the gauge comoving with the
fluid) */
/* c_vis is introduced in order to close the system */
/* different ansatz for sound speed c_eff and viscosity speed c_vis */
if (ppr->ncdm_fluid_approximation == ncdmfa_mb) {
ceff2_ncdm = ca2_ncdm;
cvis2_ncdm = 3.*w_ncdm*ca2_ncdm;
}
if (ppr->ncdm_fluid_approximation == ncdmfa_hu) {
ceff2_ncdm = ca2_ncdm;
cvis2_ncdm = w_ncdm;
}
if (ppr->ncdm_fluid_approximation == ncdmfa_CLASS) {
ceff2_ncdm = ca2_ncdm;
cvis2_ncdm = 3.*w_ncdm*ca2_ncdm;
}
/** - -----> exact continuity equation */
dy[idx] = -(1.0+w_ncdm)*(y[idx+1]+metric_continuity)-
3.0*a_prime_over_a*(ceff2_ncdm-w_ncdm)*y[idx];
/** - -----> exact euler equation */
dy[idx+1] = -a_prime_over_a*(1.0-3.0*ca2_ncdm)*y[idx+1]+
ceff2_ncdm/(1.0+w_ncdm)*k2*y[idx]-k2*y[idx+2]
+ metric_euler;
/** - -----> different ansatz for approximate shear derivative */
if (ppr->ncdm_fluid_approximation == ncdmfa_mb) {
dy[idx+2] = -3.0*(a_prime_over_a*(2./3.-ca2_ncdm-pseudo_p_ncdm/p_ncdm_bg/3.)+1./tau)*y[idx+2]
+8.0/3.0*cvis2_ncdm/(1.0+w_ncdm)*s_l[2]*(y[idx+1]+metric_shear);
}
if (ppr->ncdm_fluid_approximation == ncdmfa_hu) {
dy[idx+2] = -3.0*a_prime_over_a*ca2_ncdm/w_ncdm*y[idx+2]
+8.0/3.0*cvis2_ncdm/(1.0+w_ncdm)*s_l[2]*(y[idx+1]+metric_shear);
}
if (ppr->ncdm_fluid_approximation == ncdmfa_CLASS) {
dy[idx+2] = -3.0*(a_prime_over_a*(2./3.-ca2_ncdm-pseudo_p_ncdm/p_ncdm_bg/3.)+1./tau)*y[idx+2]
+8.0/3.0*cvis2_ncdm/(1.0+w_ncdm)*s_l[2]*(y[idx+1]+metric_ufa_class);
}
/** - -----> jump to next species */
idx += pv->l_max_ncdm[n_ncdm]+1;
}
}
/** - ----> second case: use exact equation (Boltzmann hierarchy on momentum grid) */
else {
/** - -----> loop over species */
for (n_ncdm=0; n_ncdm<pv->N_ncdm; n_ncdm++) {
/** - -----> loop over momentum */
for (index_q=0; index_q < pv->q_size_ncdm[n_ncdm]; index_q++) {
/** - -----> define intermediate quantities */
dlnf0_dlnq = pba->dlnf0_dlnq_ncdm[n_ncdm][index_q];
q = pba->q_ncdm[n_ncdm][index_q];
epsilon = sqrt(q*q+a2*pba->M_ncdm[n_ncdm]*pba->M_ncdm[n_ncdm]);
qk_div_epsilon = k*q/epsilon;
/** - -----> ncdm density for given momentum bin */
dy[idx] = -qk_div_epsilon*y[idx+1]+metric_continuity*dlnf0_dlnq/3.;
/** - -----> ncdm velocity for given momentum bin */
dy[idx+1] = qk_div_epsilon/3.0*(y[idx] - 2*s_l[2]*y[idx+2])
-epsilon*metric_euler/(3*q*k)*dlnf0_dlnq;
/** - -----> ncdm shear for given momentum bin */
dy[idx+2] = qk_div_epsilon/5.0*(2*s_l[2]*y[idx+1]-3.*s_l[3]*y[idx+3])
-s_l[2]*metric_shear*2./15.*dlnf0_dlnq;
/** - -----> ncdm l>3 for given momentum bin */
for(l=3; l<pv->l_max_ncdm[n_ncdm]; l++) {
dy[idx+l] = qk_div_epsilon/(2.*l+1.0)*(l*s_l[l]*y[idx+(l-1)]-(l+1.)*s_l[l+1]*y[idx+(l+1)]);
}
/** - -----> ncdm lmax for given momentum bin (truncation as in Ma and Bertschinger)
but with curvature taken into account a la arXiv:1305.3261 */
dy[idx+l] = qk_div_epsilon*y[idx+l-1]-(1.+l)*k*cotKgen*y[idx+l];
/** - -----> jump to next momentum bin or species */
idx += (pv->l_max_ncdm[n_ncdm]+1);
}
}
}
}
/** - ---> metric */
/** - ---> eta of synchronous gauge */
if (ppt->gauge == synchronous) {
dy[pv->index_pt_eta] = pvecmetric[ppw->index_mt_eta_prime];
}
if (ppt->gauge == newtonian) {
dy[pv->index_pt_phi] = pvecmetric[ppw->index_mt_phi_prime];
}
}
/** - vector mode */
if (_vectors_) {
fprintf(stderr,"we are in vectors\n");
ssqrt3 = sqrt(1.-2.*pba->K/k2);
cb2 = pvecthermo[pth->index_th_cb2];
/** - --> baryon velocity */
if (ppt->gauge == synchronous) {
dy[pv->index_pt_theta_b] = -(1-3.*cb2)*a_prime_over_a*y[pv->index_pt_theta_b]
- pvecthermo[pth->index_th_dkappa]*(_SQRT2_/4.*delta_g + y[pv->index_pt_theta_b]);
}
else if (ppt->gauge == newtonian) {
dy[pv->index_pt_theta_b] = -(1-3.*cb2)*a_prime_over_a*y[pv->index_pt_theta_b]
- _SQRT2_/4.*pvecthermo[pth->index_th_dkappa]*(delta_g+2.*_SQRT2_*y[pv->index_pt_theta_b])
+ pvecmetric[ppw->index_mt_V_prime]+(1.-3.*cb2)*a_prime_over_a*y[pv->index_pt_V];
}
/*
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
if (ppw->approx[ppw->index_ap_tca]==(int)tca_off) {
*/
/* short-cut notations for the tensor perturbations */
delta_g = y[pv->index_pt_delta_g];
theta_g = y[pv->index_pt_theta_g];
shear_g = y[pv->index_pt_shear_g];
/* (P^{(1)}) (see Eq. B.23 in 1305.3261)*/
P1 = -_SQRT6_/40.*(
4./(3.*k)*theta_g //F1
+y[pv->index_pt_delta_g+3]
+2.*y[pv->index_pt_pol0_g]
+10./7.*y[pv->index_pt_pol2_g]
-4./7.*y[pv->index_pt_pol0_g+4]);
if (ppt->gauge == synchronous) {
/* photon density (delta_g = F_0) */
dy[pv->index_pt_delta_g] =
-4./3.*theta_g
-pvecthermo[pth->index_th_dkappa]*(delta_g+2.*_SQRT2_*y[pv->index_pt_theta_b]);
/* photon velocity (theta_g = (3k/4)*F_1) */
dy[pv->index_pt_theta_g] =
k2*(delta_g/4.-s_l[2]*shear_g)
-pvecthermo[pth->index_th_dkappa]*(theta_g+4.0/_SQRT6_*P1)
+4.0/(3.0*_SQRT2_)*ssqrt3*y[pv->index_pt_hv_prime];
}
else if (ppt->gauge == newtonian) {
/* photon density (delta_g = F_0) */
dy[pv->index_pt_delta_g] =
-4./3.*theta_g
-pvecthermo[pth->index_th_dkappa]*(delta_g+2.*_SQRT2_*y[pv->index_pt_theta_b])
-2.*_SQRT2_*pvecmetric[ppw->index_mt_V_prime];
/* photon velocity (theta_g = (3k/4)*F_1) */
dy[pv->index_pt_theta_g] =
k2*(delta_g/4.-s_l[2]*shear_g)
-pvecthermo[pth->index_th_dkappa]*(theta_g+4.0/_SQRT6_*P1);
}
/* photon shear (shear_g = F_2/2) */
dy[pv->index_pt_shear_g] =
4./15.*s_l[2]*theta_g-3./10.*k*s_l[3]*y[pv->index_pt_shear_g+1]
-pvecthermo[pth->index_th_dkappa]*shear_g;
/* photon l=3 */
dy[pv->index_pt_l3_g] =
k/7.*(6.*s_l[3]*shear_g-4.*s_l[4]*y[pv->index_pt_l3_g+1])
-pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_l3_g];
/* additional momenta in Boltzmann hierarchy (beyond l=0,1,2,3,4) */
for (l=4; l < pv->l_max_g; l++)
dy[pv->index_pt_delta_g+l] =
k/(2.*l+1.)*(l*s_l[l]*y[pv->index_pt_delta_g+l-1]
-(l+1.)*s_l[l+1]*y[pv->index_pt_delta_g+l+1])
-pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_delta_g+l];
/* l=lmax */
l = pv->l_max_g;
dy[pv->index_pt_delta_g+l] =
k*(s_l[l]*y[pv->index_pt_delta_g+l-1]
-(1.+l)*cotKgen*y[pv->index_pt_delta_g+l])
- pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_delta_g+l];
/* photon polarization, l=0 (pol0_g = G_0)*/
dy[pv->index_pt_pol0_g] =
-k*y[pv->index_pt_pol0_g+1]
-pvecthermo[pth->index_th_dkappa]*(y[pv->index_pt_pol0_g]-_SQRT6_*P1);
/* additional momenta in Boltzmann hierarchy (beyond l=0,1,2,3,4) */
for (l=1; l < pv->l_max_pol_g; l++)
dy[pv->index_pt_pol0_g+l] =
k/(2.*l+1.)*(l*s_l[l]*y[pv->index_pt_pol0_g+l-1]
-(l+1.)*s_l[l+1]*y[pv->index_pt_pol0_g+l+1])
-pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_pol0_g+l];
/* l=lmax */
l = pv->l_max_pol_g;
dy[pv->index_pt_pol0_g+l] =
k*(s_l[l]*y[pv->index_pt_pol0_g+l-1]
-(l+1.)*cotKgen*y[pv->index_pt_pol0_g+l])
-pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_pol0_g+l];
/*
}
}
*/
if (ppt->gauge == synchronous) {
/* Vector metric perturbation in synchronous gauge: */
dy[pv->index_pt_hv_prime] = pvecmetric[ppw->index_mt_hv_prime_prime];
}
else if (ppt->gauge == newtonian) {
/* Vector metric perturbation in Newtonian gauge: */
dy[pv->index_pt_V] = pvecmetric[ppw->index_mt_V_prime];
}
}
/** - tensor modes: */
if (_tensors_) {
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
if (ppw->approx[ppw->index_ap_tca]==(int)tca_off) {
/* short-cut notations for the tensor perturbations */
delta_g = y[pv->index_pt_delta_g];
theta_g = y[pv->index_pt_theta_g];
shear_g = y[pv->index_pt_shear_g];
/* (P^{(2)}) */
P2 =-1.0/_SQRT6_*(
1./10.*delta_g
+2./7.*shear_g
+3./70.*y[pv->index_pt_delta_g+4]
-3./5.*y[pv->index_pt_pol0_g]
+6./7.*y[pv->index_pt_pol2_g]
-3./70.*y[pv->index_pt_pol0_g+4]);
/* above expression from paper, expression below matches old class but is not correct
P2 = -1.0/_SQRT6_*(
1./10.*delta_g
+2./35.*shear_g
+1./210.*y[pv->index_pt_delta_g+4]
-3./5.*y[pv->index_pt_pol0_g]
+6./35.*y[pv->index_pt_pol2_g]
-1./210.*y[pv->index_pt_pol0_g+4]
);
*/
/* photon density (delta_g = F_0) */
dy[pv->index_pt_delta_g] =
-4./3.*theta_g
-pvecthermo[pth->index_th_dkappa]*(delta_g+_SQRT6_*P2)
//+y[pv->index_pt_gwdot];
+_SQRT6_*y[pv->index_pt_gwdot]; //TBC
/* photon velocity (theta_g = (3k/4)*F_1) */
dy[pv->index_pt_theta_g] =
k2*(delta_g/4.-s_l[2]*shear_g)
-pvecthermo[pth->index_th_dkappa]*theta_g;
/* photon shear (shear_g = F_2/2) */
dy[pv->index_pt_shear_g] =
4./15.*s_l[2]*theta_g-3./10.*k*s_l[3]*y[pv->index_pt_shear_g+1]
-pvecthermo[pth->index_th_dkappa]*shear_g;
/* photon l=3 */
dy[pv->index_pt_l3_g] =
k/7.*(6.*s_l[3]*shear_g-4.*s_l[4]*y[pv->index_pt_l3_g+1])
-pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_l3_g];
/* additional momenta in Boltzmann hierarchy (beyond l=0,1,2,3,4) */
for (l=4; l < pv->l_max_g; l++)
dy[pv->index_pt_delta_g+l] =
k/(2.*l+1.)*(l*s_l[l]*y[pv->index_pt_delta_g+l-1]
-(l+1.)*s_l[l+1]*y[pv->index_pt_delta_g+l+1])
-pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_delta_g+l];
/* l=lmax */
l = pv->l_max_g;
dy[pv->index_pt_delta_g+l] =
k*(s_l[l]*y[pv->index_pt_delta_g+l-1]
-(1.+l)*cotKgen*y[pv->index_pt_delta_g+l])
- pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_delta_g+l];
/* photon polarization, l=0 (pol0_g = G_0)*/
dy[pv->index_pt_pol0_g] =
-k*y[pv->index_pt_pol0_g+1]
-pvecthermo[pth->index_th_dkappa]*(y[pv->index_pt_pol0_g]-_SQRT6_*P2);
/* additional momenta in Boltzmann hierarchy (beyond l=0,1,2,3,4) */
for (l=1; l < pv->l_max_pol_g; l++)
dy[pv->index_pt_pol0_g+l] =
k/(2.*l+1.)*(l*s_l[l]*y[pv->index_pt_pol0_g+l-1]
-(l+1.)*s_l[l+1]*y[pv->index_pt_pol0_g+l+1])
-pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_pol0_g+l];
/* l=lmax */
l = pv->l_max_pol_g;
dy[pv->index_pt_pol0_g+l] =
k*(s_l[l]*y[pv->index_pt_pol0_g+l-1]
-(l+1.)*cotKgen*y[pv->index_pt_pol0_g+l])
-pvecthermo[pth->index_th_dkappa]*y[pv->index_pt_pol0_g+l];
}
}
if (ppt->evolve_tensor_ur == _TRUE_) {
dy[pv->index_pt_delta_ur] = -4./3.*y[pv->index_pt_theta_ur]+_SQRT6_*y[pv->index_pt_gwdot];
dy[pv->index_pt_theta_ur] = k2*(y[pv->index_pt_delta_ur]/4.-s2_squared*y[pv->index_pt_shear_ur]);
dy[pv->index_pt_shear_ur] = (4./15.*y[pv->index_pt_theta_ur]
-3./10.*k*s_l[3]/s_l[2]*y[pv->index_pt_shear_ur+1]);
l = 3;
dy[pv->index_pt_l3_ur] = k/(2.*l+1.)*
(l*2.*s_l[l]*s_l[2]*y[pv->index_pt_shear_ur]-(l+1.)*s_l[l+1]*y[pv->index_pt_l3_ur+1]);
for (l = 4; l < pv->l_max_ur; l++) {
dy[pv->index_pt_delta_ur+l] = k/(2.*l+1)*
(l*s_l[l]*y[pv->index_pt_delta_ur+l-1]-(l+1.)*s_l[l+1]*y[pv->index_pt_delta_ur+l+1]);
}
l = pv->l_max_ur;
dy[pv->index_pt_delta_ur+l] =
k*(s_l[l]*y[pv->index_pt_delta_ur+l-1]-(1.+l)*cotKgen*y[pv->index_pt_delta_ur+l]);
}
/** - --> non-cold dark matter (ncdm): massive neutrinos, WDM, etc. */
//TBC: curvature in all ncdm
if (ppt->evolve_tensor_ncdm == _TRUE_) {
idx = pv->index_pt_psi0_ncdm1;
/** - ---> loop over species */
for (n_ncdm=0; n_ncdm<pv->N_ncdm; n_ncdm++) {
/** - ----> loop over momentum */
for (index_q=0; index_q < pv->q_size_ncdm[n_ncdm]; index_q++) {
/** - ----> define intermediate quantities */
dlnf0_dlnq = pba->dlnf0_dlnq_ncdm[n_ncdm][index_q];
q = pba->q_ncdm[n_ncdm][index_q];
epsilon = sqrt(q*q+a2*pba->M_ncdm[n_ncdm]*pba->M_ncdm[n_ncdm]);
qk_div_epsilon = k*q/epsilon;
/** - ----> ncdm density for given momentum bin */
dy[idx] = -qk_div_epsilon*y[idx+1]-0.25*_SQRT6_*y[pv->index_pt_gwdot]*dlnf0_dlnq;
/** - ----> ncdm l>0 for given momentum bin */
for(l=1; l<pv->l_max_ncdm[n_ncdm]; l++) {
dy[idx+l] = qk_div_epsilon/(2.*l+1.0)*(l*s_l[l]*y[idx+(l-1)]-(l+1.)*s_l[l+1]*y[idx+(l+1)]);
}
/** - ----> ncdm lmax for given momentum bin (truncation as in Ma and Bertschinger)
but with curvature taken into account a la arXiv:1305.3261 */
dy[idx+l] = qk_div_epsilon*y[idx+l-1]-(1.+l)*k*cotKgen*y[idx+l];
/** - ----> jump to next momentum bin or species */
idx += (pv->l_max_ncdm[n_ncdm]+1);
}
}
}
/** - --> tensor metric perturbation h (gravitational waves) */
dy[pv->index_pt_gw] = y[pv->index_pt_gwdot];
/** - --> its time-derivative */
dy[pv->index_pt_gwdot] = pvecmetric[ppw->index_mt_gw_prime_prime];
}
return _SUCCESS_;
}
int perturb_tca_slip_and_shear(double * y,
void * parameters_and_workspace,
ErrorMsg error_message
) {
/** Summary: */
/** - define local variables */
/* scale factor and other background quantities */
double a,a_prime_over_a,a_primeprime_over_a,R;
/* useful terms for tight-coupling approximation */
double slip=0.;
double tau_c=0.,dtau_c=0.;
double theta_prime,shear_g_prime=0.,theta_prime_prime;
double g0,g0_prime,g0_prime_prime;
double F=0.,F_prime=0.,F_prime_prime=0.;
/* short-cut names for the fields of the input structure */
struct perturb_parameters_and_workspace * pppaw;
double k,k2;
struct precision * ppr;
struct background * pba;
struct thermo * pth;
struct perturbs * ppt;
struct perturb_workspace * ppw;
double * pvecback;
double * pvecthermo;
double * pvecmetric;
struct perturb_vector * pv;
/* short-cut notations for the perturbations */
double delta_g=0.,theta_g=0.,shear_g=0.;
double delta_b,theta_b;
double Delta;
double cb2;
double metric_continuity=0.,metric_euler=0.,metric_shear=0.,metric_shear_prime=0.;
/* perturbed recombination */
double delta_temp=0.;
/* for use with curvature */
double s2_squared;
/** - rename the fields of the input structure (just to avoid heavy notations) */
pppaw = parameters_and_workspace;
k = pppaw->k;
k2=k*k;
ppr = pppaw->ppr;
pba = pppaw->pba;
pth = pppaw->pth;
ppt = pppaw->ppt;
ppw = pppaw->ppw;
pvecback = ppw->pvecback;
pvecthermo = ppw->pvecthermo;
pvecmetric = ppw->pvecmetric;
pv = ppw->pv;
/** - compute related background quantities */
a = pvecback[pba->index_bg_a];
a_prime_over_a = pvecback[pba->index_bg_H] * a;
a_primeprime_over_a = pvecback[pba->index_bg_H_prime] * a + 2. * a_prime_over_a * a_prime_over_a;
//z = pba->a_today-1.;
R = 4./3. * pvecback[pba->index_bg_rho_g]/pvecback[pba->index_bg_rho_b];
s2_squared = 1.-3.*pba->K/k2;
/** - --> (a) define short-cut notations for the scalar perturbations */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_off) {
delta_g = y[pv->index_pt_delta_g];
theta_g = y[pv->index_pt_theta_g];
}
delta_b = y[pv->index_pt_delta_b];
theta_b = y[pv->index_pt_theta_b];
cb2 = pvecthermo[pth->index_th_cb2];
/* perturbed recombination */
if ((ppt->has_perturbed_recombination == _TRUE_) && (ppw->approx[ppw->index_ap_tca] == (int)tca_off) ) {
delta_temp = y[pv->index_pt_perturbed_recombination_delta_temp];
}
/** - --> (b) define short-cut notations used only in tight-coupling approximation */
tau_c = 1./pvecthermo[pth->index_th_dkappa]; /* inverse of opacity */
dtau_c = -pvecthermo[pth->index_th_ddkappa]*tau_c*tau_c; /* its first derivative wrt conformal time */
F = tau_c/(1+R); /* F = tau_c/(1+R) */
if (ppr->tight_coupling_approximation >= (int)second_order_CLASS) {
F_prime = dtau_c/(1+R)+tau_c*a_prime_over_a*R/(1+R)/(1+R); /*F' needed by second_order_CLASS and compromise_CLASS */
if (ppr->tight_coupling_approximation == (int)second_order_CLASS) {
F_prime_prime =(- pvecthermo[pth->index_th_dddkappa]*tau_c*tau_c /* F'' needed by second_order_CLASS only */
+ 2.*pvecthermo[pth->index_th_ddkappa]*pvecthermo[pth->index_th_ddkappa]*tau_c*tau_c*tau_c)/(1+R)
+2.*dtau_c*a_prime_over_a*R/(1+R)/(1+R)
+tau_c*((a_primeprime_over_a-2.*a_prime_over_a*a_prime_over_a)+2.*a_prime_over_a*a_prime_over_a*R/(1+R))*R/(1+R)/(1+R);
}
}
/** - --> (c) compute metric-related quantities (depending on gauge; additional gauges can be coded below)
- Each continuity equation contains a term in (theta+metric_continuity) with
metric_continuity = (h_prime/2) in synchronous gauge, (-3 phi_prime) in newtonian gauge
- Each Euler equation contains a source term metric_euler with
metric_euler = 0 in synchronous gauge, (k2 psi) in newtonian gauge
- Each shear derivative equation contains a source term metric_shear equal to
metric_shear = (h_prime+6eta_prime)/2 in synchronous gauge, 0 in newtonian gauge
- metric_shear_prime is the derivative of metric_shear
- In the ufa_class approximation, the leading-order source term is (h_prime/2) in synchronous gauge,
(-3 (phi_prime+psi_prime)) in newtonian gauge: we approximate the later by (-6 phi_prime) */
if (ppt->gauge == synchronous) {
metric_continuity = pvecmetric[ppw->index_mt_h_prime]/2.;
metric_euler = 0.;
metric_shear = k2 * pvecmetric[ppw->index_mt_alpha];
metric_shear_prime = k2 * pvecmetric[ppw->index_mt_alpha_prime];
}
if (ppt->gauge == newtonian) {
metric_continuity = -3.*pvecmetric[ppw->index_mt_phi_prime];
metric_euler = k2*pvecmetric[ppw->index_mt_psi];
metric_shear = 0.;
metric_shear_prime = 0.;
}
/** - --> (d) if some approximation schemes are turned on, enforce a few y[ ] values computed in perturb_einstein */
/* free-streaming photon velocity */
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_on)
theta_g = ppw->rsa_theta_g;
/** - ---> like Ma & Bertschinger */
if (ppr->tight_coupling_approximation == (int)first_order_MB) {
slip=2.*R/(1.+R)*a_prime_over_a*(theta_b-theta_g)
+F*(-a_primeprime_over_a*theta_b
+k2*(-a_prime_over_a*delta_g/2.
+cb2*(-theta_b-metric_continuity)
-4./3.*(-theta_g-metric_continuity)/4.)
-a_prime_over_a*metric_euler);
}
/** - ---> relax assumption dkappa~a\f$^{-2}\f$ (like in CAMB) */
if ((ppr->tight_coupling_approximation == (int)first_order_CAMB) || (ppr->tight_coupling_approximation == (int)compromise_CLASS)) {
slip=(dtau_c/tau_c-2.*a_prime_over_a/(1.+R))*(theta_b-theta_g)
+F*(-a_primeprime_over_a*theta_b
+k2*(-a_prime_over_a*delta_g/2.
+cb2*(-theta_b-metric_continuity)
-4./3.*(-theta_g-metric_continuity)/4.)
-a_prime_over_a*metric_euler);
}
/** - ---> also relax assumption cb2~a\f$^{-1}\f$ */
if ((ppr->tight_coupling_approximation == (int)first_order_CLASS) || (ppr->tight_coupling_approximation == (int)second_order_CLASS)) {
slip=(dtau_c/tau_c-2.*a_prime_over_a/(1.+R))*(theta_b-theta_g)
+F*(-a_primeprime_over_a*theta_b
+k2*(-a_prime_over_a*delta_g/2.
+pvecthermo[pth->index_th_dcb2]*delta_b
+cb2*(-theta_b-metric_continuity)
-4./3.*(-theta_g-metric_continuity)/4.)
-a_prime_over_a*metric_euler);
}
/** - ---> intermediate quantities for 2nd order tca: shear_g at first order in tight-coupling */
shear_g=16./45.*tau_c*(theta_g+metric_shear);
/* (Ma & Bertschinger give (1/9)*(4/3) instead of (2/15)*(4/3)
because they didn't include the contribution of G_gamma0
and G_gamma2, which are of the same order as sigma_g. This
was already consistently included in CAMB) */
/** - ---> intermediate quantities for 2nd order tca: zero order for theta_b' = theta_g' */
/** - ----> perturbed recombination has an impact **/
theta_prime = (-a_prime_over_a*theta_b+k2*(cb2*(delta_b+delta_temp)+R/4.*delta_g))/(1.+R) + metric_euler;
/** - ---> intermediate quantities for 2nd order tca: shear_g_prime at first order in tight-coupling */
shear_g_prime=16./45.*(tau_c*(theta_prime+metric_shear_prime)+dtau_c*(theta_g+metric_shear));
/** - ---> 2nd order as in CRS*/
if (ppr->tight_coupling_approximation == (int)second_order_CRS) {
if (ppt->gauge == newtonian) {
class_stop(error_message,
"the second_order_CRS approach to tight-coupling is coded in synchronous gauge, not newtonian: change gauge or try another tight-coupling scheme");
}
if (ppt->gauge == synchronous) {
class_test(pba->sgnK != 0,
ppt->error_message,
"the second_order_CRS approach to tight-coupling is coded in the flat case only: for non-flat try another tight-coupling scheme");
/* infer Delta from h'' using Einstein equation */
Delta = 2*k2*y[pv->index_pt_eta]
-2*a_prime_over_a*pvecmetric[ppw->index_mt_h_prime]
-pvecmetric[ppw->index_mt_h_prime_prime];
/* monster expression for slip at second-order in tight-coupling */
slip=(-2./(1.+R)*a_prime_over_a-pvecthermo[pth->index_th_ddkappa]/pvecthermo[pth->index_th_dkappa])*(theta_b-theta_g)
+(-a_primeprime_over_a*theta_b
-k2*a_prime_over_a*(delta_g/2.-2.*shear_g)
+k2*(cb2*(-theta_b-metric_continuity)
-4./3.*(-theta_g-metric_continuity)/4.
+shear_g_prime)
)/pvecthermo[pth->index_th_dkappa]/(1.+R)
-2.*R*(3.*a_prime_over_a*a_prime_over_a*cb2+(1.+R)*(a_primeprime_over_a-a_prime_over_a*a_prime_over_a)-3.*a_prime_over_a*a_prime_over_a)
/(1.+R)/(1.+R)/(1.+R)*(theta_b-theta_g)/pvecthermo[pth->index_th_dkappa]
+(
a_primeprime_over_a*a_prime_over_a*((2.-3.*cb2)*R-2.)*theta_b/(1.+R)
+a_prime_over_a*k2*(1.-3.*cb2)*theta_b/3./(1.+R)
/* perturbed recombination has an impact (next two lines) */
+a_primeprime_over_a*k2*cb2*(delta_b+delta_temp)/(1.+R)
+k2*k2*(3.*cb2-1.)*cb2*(delta_b+delta_temp)/3./(1.+R)
+k2*k2*R*(3.*cb2-1.)*delta_g/12./(1.+R)
+a_primeprime_over_a*k2*(2.+3.*R)*delta_g/4./(1.+R)
+a_prime_over_a*a_prime_over_a*k2*((2.-3.*cb2)*R-1.)*delta_g/2./(1.+R)
+a_prime_over_a*k2*cb2*(1.+(3.*cb2-2.)*R)*(-theta_b-metric_continuity)/(1.+R)
+a_prime_over_a*k2*(2.+(5.-3.*cb2)*R)*4./3.*(-theta_g-metric_continuity)/4./(1.+R)
+a_prime_over_a*(1.-3.*cb2)*k2*2.*metric_shear/3.
+k2*k2*(3.*cb2-1.)*y[pv->index_pt_eta]/3.
+2.*a_prime_over_a*k2*(3.*cb2-1.)*pvecmetric[ppw->index_mt_eta_prime]
+k2*(1.-3.*cb2)*Delta/6.
)/pvecthermo[pth->index_th_dkappa]/pvecthermo[pth->index_th_dkappa]/(1.+R)/(1.+R)
-(4.*a_primeprime_over_a*theta_b-4.*k2*cb2*(-theta_b-metric_continuity)+2.*a_prime_over_a*k2*delta_g+k2*4./3.*(-theta_g-metric_continuity))/2./(1.+R)/(1.+R)*pvecthermo[pth->index_th_ddkappa]/pvecthermo[pth->index_th_dkappa]/pvecthermo[pth->index_th_dkappa]/pvecthermo[pth->index_th_dkappa]
+4.*a_prime_over_a*R/(1.+R)/(1.+R)*pvecthermo[pth->index_th_ddkappa]/pvecthermo[pth->index_th_dkappa]/pvecthermo[pth->index_th_dkappa]*(theta_b-theta_g);
/* second-order correction to shear */
shear_g = (1.-11./6.*dtau_c)*shear_g-11./6.*tau_c*16./45.*tau_c*(theta_prime+k2*pvecmetric[ppw->index_mt_alpha_prime]);
}
}
/** - ---> 2nd order like in CLASS paper */
if (ppr->tight_coupling_approximation == (int)second_order_CLASS) {
if (ppt->gauge == newtonian) {
class_stop(error_message,
"the second_order_CLASS approach to tight-coupling is coded in synchronous gauge, not newtonian: change gauge or try another tight-coupling scheme");
}
if (ppt->gauge == synchronous) {
/* zero order for theta_b'' = theta_g'' */
theta_prime_prime = ((R-1.)*a_prime_over_a*theta_prime-(a_primeprime_over_a-a_prime_over_a*a_prime_over_a)*theta_b
+k2*(pvecthermo[pth->index_th_dcb2]*delta_b+cb2*(-theta_b-metric_continuity)-a_prime_over_a*R/4.*delta_g+R/4.*4./3.*(-theta_g-metric_continuity)))/(1.+R);
/* zero-order quantities g0, g0', go'' */
g0 = -a_prime_over_a*theta_b + k2*(cb2*delta_b-delta_g/4.);
g0_prime = -a_prime_over_a*theta_prime-(a_primeprime_over_a-a_prime_over_a*a_prime_over_a)*theta_b+k2*(pvecthermo[pth->index_th_dcb2]*delta_b+(1./3.-cb2)*(theta_b+0.5*pvecmetric[ppw->index_mt_h_prime]));
g0_prime_prime = -a_prime_over_a*theta_prime_prime-2.*(a_primeprime_over_a-a_prime_over_a*a_prime_over_a)*theta_prime
-(2.*a_prime_over_a*a_prime_over_a*a_prime_over_a-3.*a_primeprime_over_a*a_prime_over_a)*theta_b
+k2*(pvecthermo[pth->index_th_ddcb2]*delta_b-2.*pvecthermo[pth->index_th_dcb2]*(theta_b+0.5*pvecmetric[ppw->index_mt_h_prime])+(1./3.-cb2)*(theta_prime+0.5*pvecmetric[ppw->index_mt_h_prime_prime]));
/* slip at second order */
slip = (1.-2*a_prime_over_a*F)*slip + F*k2*s2_squared*(2.*a_prime_over_a*shear_g+shear_g_prime)
-F*(F_prime_prime*g0+2.*F_prime*g0_prime+F*g0_prime_prime);
/* second-order correction to shear */
shear_g = (1.-11./6.*dtau_c)*shear_g-11./6.*tau_c*16./45.*tau_c*(theta_prime+metric_shear_prime);
}
}
/** - ---> add only the most important 2nd order terms */
if (ppr->tight_coupling_approximation == (int)compromise_CLASS) {
/* slip at second order (only leading second-order terms) */
slip = (1.-2.*a_prime_over_a*F)*slip + F*k2*(2.*a_prime_over_a*s2_squared*shear_g+s2_squared*shear_g_prime-(1./3.-cb2)*(F*theta_prime+2.*F_prime*theta_b));
/* second-order correction to shear */
shear_g = (1.-11./6.*dtau_c)*shear_g-11./6.*tau_c*16./45.*tau_c*(theta_prime+metric_shear_prime);
}
/** - ---> store tight-coupling values of photon shear and its derivative */
ppw->tca_shear_g = shear_g;
ppw->tca_slip = slip;
return _SUCCESS_;
}
int perturb_rsa_delta_and_theta(
struct precision * ppr,
struct background * pba,
struct thermo * pth,
struct perturbs * ppt,
double k,
double * y,
double a_prime_over_a,
double * pvecthermo,
struct perturb_workspace * ppw
) {
/* - define local variables */
double k2;
k2 = k*k;
// formulas below TBC for curvaturema
/* newtonian gauge */
if (ppt->gauge == newtonian) {
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_on) {
if (ppr->radiation_streaming_approximation == rsa_null) {
ppw->rsa_delta_g = 0.;
ppw->rsa_theta_g = 0.;
}
else {
ppw->rsa_delta_g = -4.*y[ppw->pv->index_pt_phi];
ppw->rsa_theta_g = 6.*ppw->pvecmetric[ppw->index_mt_phi_prime];
}
if (ppr->radiation_streaming_approximation == rsa_MD_with_reio) {
ppw->rsa_delta_g +=
-4./k2*ppw->pvecthermo[pth->index_th_dkappa]*y[ppw->pv->index_pt_theta_b];
ppw->rsa_theta_g +=
3./k2*(ppw->pvecthermo[pth->index_th_ddkappa]*y[ppw->pv->index_pt_theta_b]
+ppw->pvecthermo[pth->index_th_dkappa]*
(-a_prime_over_a*y[ppw->pv->index_pt_theta_b]
+ppw->pvecthermo[pth->index_th_cb2]*k2*y[ppw->pv->index_pt_delta_b]
+k2*y[ppw->pv->index_pt_phi]));
}
if (pba->has_ur == _TRUE_) {
if (ppr->radiation_streaming_approximation == rsa_null) {
ppw->rsa_delta_ur = 0.;
ppw->rsa_theta_ur = 0.;
}
else {
ppw->rsa_delta_ur = -4.*y[ppw->pv->index_pt_phi];
ppw->rsa_theta_ur = 6.*ppw->pvecmetric[ppw->index_mt_phi_prime];
}
}
}
}
/* synchronous gauge */
if (ppt->gauge == synchronous) {
if (ppw->approx[ppw->index_ap_rsa] == (int)rsa_on) {
if (ppr->radiation_streaming_approximation == rsa_null) {
ppw->rsa_delta_g = 0.;
ppw->rsa_theta_g = 0.;
}
else {
ppw->rsa_delta_g = 4./k2*(a_prime_over_a*ppw->pvecmetric[ppw->index_mt_h_prime]
-k2*y[ppw->pv->index_pt_eta]);
ppw->rsa_theta_g = -0.5*ppw->pvecmetric[ppw->index_mt_h_prime];
}
if (ppr->radiation_streaming_approximation == rsa_MD_with_reio) {
ppw->rsa_delta_g +=
-4./k2*ppw->pvecthermo[pth->index_th_dkappa]*(y[ppw->pv->index_pt_theta_b]+0.5*ppw->pvecmetric[ppw->index_mt_h_prime]);
ppw->rsa_theta_g +=
3./k2*(ppw->pvecthermo[pth->index_th_ddkappa]*
(y[ppw->pv->index_pt_theta_b]
+0.5*ppw->pvecmetric[ppw->index_mt_h_prime])
+ppw->pvecthermo[pth->index_th_dkappa]*
(-a_prime_over_a*y[ppw->pv->index_pt_theta_b]
+ ppw->pvecthermo[pth->index_th_cb2]*k2*y[ppw->pv->index_pt_delta_b]
-a_prime_over_a*ppw->pvecmetric[ppw->index_mt_h_prime]
+k2*y[ppw->pv->index_pt_eta]));
}
if (pba->has_ur == _TRUE_) {
if (ppr->radiation_streaming_approximation == rsa_null) {
ppw->rsa_delta_ur = 0.;
ppw->rsa_theta_ur = 0.;
}
else {
ppw->rsa_delta_ur = 4./k2*(a_prime_over_a*ppw->pvecmetric[ppw->index_mt_h_prime]
-k2*y[ppw->pv->index_pt_eta]);
ppw->rsa_theta_ur = -0.5*ppw->pvecmetric[ppw->index_mt_h_prime];
}
}
}
}
return _SUCCESS_;
}
|
coordinate_common.h | /*!
* Copyright 2018 by Contributors
* \author Rory Mitchell
*/
#pragma once
#include <algorithm>
#include <string>
#include <utility>
#include <vector>
#include "../common/random.h"
namespace xgboost {
namespace linear {
/**
* \brief Calculate change in weight for a given feature. Applies l1/l2 penalty normalised by the
* number of training instances.
*
* \param sum_grad The sum gradient.
* \param sum_hess The sum hess.
* \param w The weight.
* \param reg_lambda Unnormalised L2 penalty.
* \param reg_alpha Unnormalised L1 penalty.
* \param sum_instance_weight The sum instance weights, used to normalise l1/l2 penalty.
*
* \return The weight update.
*/
inline double CoordinateDelta(double sum_grad, double sum_hess, double w,
double reg_lambda, double reg_alpha,
double sum_instance_weight) {
reg_alpha *= sum_instance_weight;
reg_lambda *= sum_instance_weight;
if (sum_hess < 1e-5f) return 0.0f;
double tmp = w - (sum_grad + reg_lambda * w) / (sum_hess + reg_lambda);
if (tmp >= 0) {
return std::max(
-(sum_grad + reg_lambda * w + reg_alpha) / (sum_hess + reg_lambda), -w);
} else {
return std::min(
-(sum_grad + reg_lambda * w - reg_alpha) / (sum_hess + reg_lambda), -w);
}
}
/**
* \brief Calculate update to bias.
*
* \param sum_grad The sum gradient.
* \param sum_hess The sum hess.
*
* \return The weight update.
*/
inline double CoordinateDeltaBias(double sum_grad, double sum_hess) {
return -sum_grad / sum_hess;
}
/**
* \brief Get the gradient with respect to a single feature.
*
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param fidx The target feature.
* \param gpair Gradients.
* \param p_fmat The feature matrix.
*
* \return The gradient and diagonal Hessian entry for a given feature.
*/
inline std::pair<double, double> GetGradient(
int group_idx, int num_group, int fidx, const std::vector<bst_gpair> &gpair,
DMatrix *p_fmat) {
double sum_grad = 0.0, sum_hess = 0.0;
dmlc::DataIter<ColBatch> *iter = p_fmat->ColIterator();
while (iter->Next()) {
const ColBatch &batch = iter->Value();
ColBatch::Inst col = batch[fidx];
const bst_omp_uint ndata = static_cast<bst_omp_uint>(col.length);
for (bst_omp_uint j = 0; j < ndata; ++j) {
const bst_float v = col[j].fvalue;
auto &p = gpair[col[j].index * num_group + group_idx];
if (p.GetHess() < 0.0f) continue;
sum_grad += p.GetGrad() * v;
sum_hess += p.GetHess() * v * v;
}
}
return std::make_pair(sum_grad, sum_hess);
}
/**
* \brief Get the gradient with respect to a single feature. Multithreaded.
*
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param fidx The target feature.
* \param gpair Gradients.
* \param p_fmat The feature matrix.
*
* \return The gradient and diagonal Hessian entry for a given feature.
*/
inline std::pair<double, double> GetGradientParallel(
int group_idx, int num_group, int fidx,
const std::vector<bst_gpair> &gpair, DMatrix *p_fmat) {
double sum_grad = 0.0, sum_hess = 0.0;
dmlc::DataIter<ColBatch> *iter = p_fmat->ColIterator();
while (iter->Next()) {
const ColBatch &batch = iter->Value();
ColBatch::Inst col = batch[fidx];
const bst_omp_uint ndata = static_cast<bst_omp_uint>(col.length);
#pragma omp parallel for schedule(static) reduction(+ : sum_grad, sum_hess)
for (bst_omp_uint j = 0; j < ndata; ++j) {
const bst_float v = col[j].fvalue;
auto &p = gpair[col[j].index * num_group + group_idx];
if (p.GetHess() < 0.0f) continue;
sum_grad += p.GetGrad() * v;
sum_hess += p.GetHess() * v * v;
}
}
return std::make_pair(sum_grad, sum_hess);
}
/**
* \brief Get the gradient with respect to the bias. Multithreaded.
*
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param gpair Gradients.
* \param p_fmat The feature matrix.
*
* \return The gradient and diagonal Hessian entry for the bias.
*/
inline std::pair<double, double> GetBiasGradientParallel(
int group_idx, int num_group, const std::vector<bst_gpair> &gpair,
DMatrix *p_fmat) {
const RowSet &rowset = p_fmat->buffered_rowset();
double sum_grad = 0.0, sum_hess = 0.0;
const bst_omp_uint ndata = static_cast<bst_omp_uint>(rowset.size());
#pragma omp parallel for schedule(static) reduction(+ : sum_grad, sum_hess)
for (bst_omp_uint i = 0; i < ndata; ++i) {
auto &p = gpair[rowset[i] * num_group + group_idx];
if (p.GetHess() >= 0.0f) {
sum_grad += p.GetGrad();
sum_hess += p.GetHess();
}
}
return std::make_pair(sum_grad, sum_hess);
}
/**
* \brief Updates the gradient vector with respect to a change in weight.
*
* \param fidx The feature index.
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param dw The change in weight.
* \param in_gpair The gradient vector to be updated.
* \param p_fmat The input feature matrix.
*/
inline void UpdateResidualParallel(int fidx, int group_idx, int num_group,
float dw, std::vector<bst_gpair> *in_gpair,
DMatrix *p_fmat) {
if (dw == 0.0f) return;
dmlc::DataIter<ColBatch> *iter = p_fmat->ColIterator();
while (iter->Next()) {
const ColBatch &batch = iter->Value();
ColBatch::Inst col = batch[fidx];
// update grad value
const bst_omp_uint num_row = static_cast<bst_omp_uint>(col.length);
#pragma omp parallel for schedule(static)
for (bst_omp_uint j = 0; j < num_row; ++j) {
bst_gpair &p = (*in_gpair)[col[j].index * num_group + group_idx];
if (p.GetHess() < 0.0f) continue;
p += bst_gpair(p.GetHess() * col[j].fvalue * dw, 0);
}
}
}
/**
* \brief Updates the gradient vector based on a change in the bias.
*
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param dbias The change in bias.
* \param in_gpair The gradient vector to be updated.
* \param p_fmat The input feature matrix.
*/
inline void UpdateBiasResidualParallel(int group_idx, int num_group,
float dbias,
std::vector<bst_gpair> *in_gpair,
DMatrix *p_fmat) {
if (dbias == 0.0f) return;
const RowSet &rowset = p_fmat->buffered_rowset();
const bst_omp_uint ndata = static_cast<bst_omp_uint>(p_fmat->info().num_row);
#pragma omp parallel for schedule(static)
for (bst_omp_uint i = 0; i < ndata; ++i) {
bst_gpair &g = (*in_gpair)[rowset[i] * num_group + group_idx];
if (g.GetHess() < 0.0f) continue;
g += bst_gpair(g.GetHess() * dbias, 0);
}
}
/**
* \class FeatureSelector
*
* \brief Abstract class for stateful feature selection in coordinate descent
* algorithms.
*/
class FeatureSelector {
public:
static FeatureSelector *Create(std::string name);
/*! \brief virtual destructor */
virtual ~FeatureSelector() {}
/**
* \brief Select next coordinate to update.
*
* \param iteration The iteration.
* \param model The model.
* \param group_idx Zero-based index of the group.
* \param gpair The gpair.
* \param p_fmat The feature matrix.
* \param alpha Regularisation alpha.
* \param lambda Regularisation lambda.
* \param sum_instance_weight The sum instance weight.
*
* \return The index of the selected feature. -1 indicates the bias term.
*/
virtual int SelectNextFeature(int iteration,
const gbm::GBLinearModel &model,
int group_idx,
const std::vector<bst_gpair> &gpair,
DMatrix *p_fmat, float alpha, float lambda,
double sum_instance_weight) = 0;
};
/**
* \class CyclicFeatureSelector
*
* \brief Deterministic selection by cycling through coordinates one at a time.
*/
class CyclicFeatureSelector : public FeatureSelector {
public:
int SelectNextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<bst_gpair> &gpair,
DMatrix *p_fmat, float alpha, float lambda,
double sum_instance_weight) override {
return iteration % model.param.num_feature;
}
};
/**
* \class RandomFeatureSelector
*
* \brief A random coordinate selector.
*/
class RandomFeatureSelector : public FeatureSelector {
public:
int SelectNextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<bst_gpair> &gpair,
DMatrix *p_fmat, float alpha, float lambda,
double sum_instance_weight) override {
return common::GlobalRandom()() % model.param.num_feature;
}
};
/**
* \class GreedyFeatureSelector
*
* \brief Select coordinate with the greatest gradient magnitude.
*/
class GreedyFeatureSelector : public FeatureSelector {
public:
int SelectNextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<bst_gpair> &gpair,
DMatrix *p_fmat, float alpha, float lambda,
double sum_instance_weight) override {
// Find best
int best_fidx = 0;
double best_weight_update = 0.0f;
for (auto fidx = 0U; fidx < model.param.num_feature; fidx++) {
const float w = model[fidx][group_idx];
auto gradient = GetGradientParallel(
group_idx, model.param.num_output_group, fidx, gpair, p_fmat);
float dw = static_cast<float>(
CoordinateDelta(gradient.first, gradient.second, w, lambda, alpha,
sum_instance_weight));
if (std::abs(dw) > std::abs(best_weight_update)) {
best_weight_update = dw;
best_fidx = fidx;
}
}
return best_fidx;
}
};
inline FeatureSelector *FeatureSelector::Create(std::string name) {
if (name == "cyclic") {
return new CyclicFeatureSelector();
} else if (name == "random") {
return new RandomFeatureSelector();
} else if (name == "greedy") {
return new GreedyFeatureSelector();
} else {
LOG(FATAL) << name << ": unknown coordinate selector";
}
return nullptr;
}
} // namespace linear
} // namespace xgboost
|
parallel_invoker.h | // Copyright 2019 The MediaPipe Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Parallel for loop execution.
// For details adapt parallel_using_* flags defined in parallel_invoker.cc.
// Usage example (for 1D):
// Define Functor or lambda function that implements:
// void operator()(const BlockedRange & range) const;
// (in addition functor needs to be copyable).
// Execute a for loop in parallel from 0 to N via:
// ParallelFor(0, // start_index
// num_frames, // end_index, exclusive
// 1 // number of elements processed per iteration
// [](const BlockedRange& range) {
// // Process per-thread sub-range
// for (int i = range.begin(); i < range.end(); ++i) {
// // Process i'th item.
// }
// }
// Specific implementation to copy a vector of images in parallel.
// class CopyInvoker {
// public:
// CopyInvoker(const vector<cv::Mat>& inputs,
// vector<cv::Mat*>* outputs)
// : inputs_(inputs), outputs_(outputs) {
// }
// CopyInvoker(const CopyInvoker& rhs)
// : inputs_(rhs.inputs_), outputs_(rhs.outputs) {
// }
// void operator()(const BlockedRange& range) {
// for (int frame = range.begin(); frame < range.end(); ++frame) {
// inputs_[frame].copyTo(*(*outputs_)[frame]);
// }
// }
// private:
// const vector<cv::Mat>& inputs_;
// vector<cv::Mat*>* outputs_;
// }
// vector<cv::Mat> inputs;
// vector<cv::Mat*> outputs;
// ParallelFor(0, num_frames, 1, CopyInvoker(inputs, &outputs));
//
// OR (with lambdas):
// ParallelFor(0, num_frames, 1,
// [&inputs, &outputs](const BlockedRange& range) {
// for (int frame = range.begin(); frame < range.end(); ++frame) {
// inputs[frame].copyTo(*(outputs)[frame]);
// }
// }
#ifndef MEDIAPIPE_UTIL_TRACKING_PARALLEL_INVOKER_H_
#define MEDIAPIPE_UTIL_TRACKING_PARALLEL_INVOKER_H_
#include <stddef.h>
#include <memory>
#include "absl/synchronization/mutex.h"
#include "mediapipe/framework/port/logging.h"
#ifdef PARALLEL_INVOKER_ACTIVE
#include "mediapipe/framework/port/threadpool.h"
#ifdef __APPLE__
#include <dispatch/dispatch.h>
#include <stdatomic.h>
#endif
#endif // PARALLEL_INVOKER_ACTIVE
// Specifies parallelization implementation to use.
enum PARALLEL_INVOKER_MODE {
PARALLEL_INVOKER_NONE = 0, // Uses single threaded execution
PARALLEL_INVOKER_THREAD_POOL = 1, // Uses //thread/threadpool
PARALLEL_INVOKER_OPENMP = 2, // Uses OpenMP (requires compiler support)
PARALLEL_INVOKER_GCD = 3, // Uses GCD (Apple)
PARALLEL_INVOKER_MAX_VALUE = 4, // Increase when adding more modes
};
extern int flags_parallel_invoker_mode;
extern int flags_parallel_invoker_max_threads;
// Note flag: Parallel processing only activated if
// PARALLEL_INVOKER_ACTIVE is defined.
namespace mediapipe {
// Partitions the range [begin, end) into equal blocks of size grain_size each
// (except last one, might be less than grain_size).
class BlockedRange {
public:
BlockedRange(int begin, int end, int grain_size)
: begin_(begin), end_(end), grain_size_(grain_size) {}
int begin() const { return begin_; }
int end() const { return end_; }
int grain_size() const { return grain_size_; }
private:
int begin_;
int end_;
int grain_size_;
};
// Partitions the range row_range x col_range into equal
// blocks of size row_range.grain_size() x col_range.grain_size() each
// (except last column and row might be of size less than grain_size in one
// or both of their dimensions).
class BlockedRange2D {
public:
BlockedRange2D(const BlockedRange& rows, const BlockedRange& cols)
: rows_(rows), cols_(cols) {}
const BlockedRange& rows() const { return rows_; }
const BlockedRange& cols() const { return cols_; }
private:
BlockedRange rows_;
BlockedRange cols_;
};
#ifdef PARALLEL_INVOKER_ACTIVE
// Singleton ThreadPool for parallel invoker.
ThreadPool* ParallelInvokerThreadPool();
#ifdef __APPLE__
// Enable to allow GCD as an option beside ThreadPool.
#define USE_PARALLEL_INVOKER_GCD 1
#define CHECK_GCD_PARALLEL_WORK_COUNT DEBUG
template <class Invoker>
class ParallelInvokerGCDContext {
public:
ParallelInvokerGCDContext(const Invoker& invoker, const BlockedRange& rows)
: local_invoker_(invoker), rows_(rows) {
#if CHECK_GCD_PARALLEL_WORK_COUNT
count_ = 0;
#endif
}
const Invoker& invoker() {
#if CHECK_GCD_PARALLEL_WORK_COUNT
// Implicitly tracking the # of launched tasks at invoker retrieval.
atomic_fetch_add(&count_, 1);
#endif
return local_invoker_;
}
const BlockedRange& rows() const { return rows_; }
#if CHECK_GCD_PARALLEL_WORK_COUNT
const int count() { return atomic_load(&count_); }
#endif
private:
Invoker local_invoker_;
const BlockedRange& rows_;
#if CHECK_GCD_PARALLEL_WORK_COUNT
_Atomic(int32_t) count_;
#endif
};
template <class Invoker>
class ParallelInvokerGCDContext2D : public ParallelInvokerGCDContext<Invoker> {
public:
ParallelInvokerGCDContext2D(const Invoker& invoker, const BlockedRange& rows,
const BlockedRange& cols)
: ParallelInvokerGCDContext<Invoker>(invoker, rows), cols_(cols) {}
const BlockedRange& cols() const { return cols_; }
private:
BlockedRange cols_;
};
template <class Invoker>
static void ParallelForGCDTask(void* context, size_t index) {
ParallelInvokerGCDContext<Invoker>* invoker_context =
static_cast<ParallelInvokerGCDContext<Invoker>*>(context);
const BlockedRange& all_tasks = invoker_context->rows();
int start = all_tasks.begin() + index * all_tasks.grain_size();
int end = std::min(all_tasks.end(), start + all_tasks.grain_size());
BlockedRange this_task(start, end, all_tasks.grain_size());
const Invoker& invoker = invoker_context->invoker();
invoker(this_task);
}
template <class Invoker>
static void ParallelForGCDTask2D(void* context, size_t index) {
ParallelInvokerGCDContext2D<Invoker>* invoker_context =
static_cast<ParallelInvokerGCDContext2D<Invoker>*>(context);
// Partitioning across rows.
const BlockedRange& all_tasks = invoker_context->rows();
int start = all_tasks.begin() + index * all_tasks.grain_size();
int end = std::min(all_tasks.end(), start + all_tasks.grain_size());
BlockedRange this_task(start, end, all_tasks.grain_size());
const Invoker& invoker = invoker_context->invoker();
invoker(BlockedRange2D(this_task, invoker_context->cols()));
}
#endif // __APPLE__
#endif // PARALLEL_INVOKER_ACTIVE
// Simple wrapper for compatibility with below ParallelFor function.
template <class Invoker>
void SerialFor(size_t start, size_t end, size_t grain_size,
const Invoker& invoker) {
invoker(BlockedRange(start, end, 1));
}
inline void CheckAndSetInvokerOptions() {
#if defined(PARALLEL_INVOKER_ACTIVE)
#if defined(__ANDROID__)
// If unsupported option is selected, force usage of OpenMP if detected, and
// ThreadPool otherwise.
if (flags_parallel_invoker_mode != PARALLEL_INVOKER_NONE &&
flags_parallel_invoker_mode != PARALLEL_INVOKER_THREAD_POOL &&
flags_parallel_invoker_mode != PARALLEL_INVOKER_OPENMP) {
#if defined(_OPENMP)
LOG(WARNING) << "Unsupported invoker mode selected on Android. "
<< "OpenMP linkage detected, so falling back to OpenMP";
flags_parallel_invoker_mode = PARALLEL_INVOKER_OPENMP;
#else // _OPENMP
// Fallback mode for active parallel invoker without OpenMP is ThreadPool.
LOG(WARNING) << "Unsupported invoker mode selected on Android. "
<< "Falling back to ThreadPool";
flags_parallel_invoker_mode = PARALLEL_INVOKER_THREAD_POOL;
#endif // _OPENMP
}
#endif // __ANDROID__
#if defined(__APPLE__) || defined(__EMSCRIPTEN__)
// Force usage of ThreadPool if unsupported option is selected.
// (OpenMP is not supported on iOS, due to missing clang support).
if (flags_parallel_invoker_mode != PARALLEL_INVOKER_NONE &&
#if defined(USE_PARALLEL_INVOKER_GCD)
flags_parallel_invoker_mode != PARALLEL_INVOKER_GCD &&
#endif // USE_PARALLEL_INVOKER_GCD
flags_parallel_invoker_mode != PARALLEL_INVOKER_THREAD_POOL) {
LOG(WARNING) << "Unsupported invoker mode selected on iOS. "
<< "Falling back to ThreadPool mode";
flags_parallel_invoker_mode = PARALLEL_INVOKER_THREAD_POOL;
}
#endif // __APPLE__ || __EMSCRIPTEN__
#if !defined(__APPLE__) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__)
flags_parallel_invoker_mode = PARALLEL_INVOKER_THREAD_POOL;
#endif // !__APPLE__ && !__EMSCRIPTEN__ && !__ANDROID__
// If OpenMP is requested, make sure we can actually use it, and fall back
// to ThreadPool if not.
if (flags_parallel_invoker_mode == PARALLEL_INVOKER_OPENMP) {
#if !defined(_OPENMP)
LOG(ERROR) << "OpenMP invoker mode selected but not compiling with OpenMP "
<< "enabled. Falling back to ThreadPool";
flags_parallel_invoker_mode = PARALLEL_INVOKER_THREAD_POOL;
#endif // _OPENMP
}
#else // PARALLEL_INVOKER_ACTIVE
if (flags_parallel_invoker_mode != PARALLEL_INVOKER_NONE) {
LOG(ERROR) << "Parallel execution requested but PARALLEL_INVOKER_ACTIVE "
<< "compile flag is not set. Falling back to single threaded "
<< "execution.";
flags_parallel_invoker_mode = PARALLEL_INVOKER_NONE;
}
#endif // PARALLEL_INVOKER_ACTIVE
CHECK_LT(flags_parallel_invoker_mode, PARALLEL_INVOKER_MAX_VALUE)
<< "Invalid invoker mode specified.";
CHECK_GE(flags_parallel_invoker_mode, 0) << "Invalid invoker mode specified.";
}
// Performs parallel iteration from [start to end), scheduling grain_size
// iterations per thread. For each iteration
// invoker(BlockedRange(thread_local_start, thread_local_end))
// is called. Each thread is given its local copy of invoker, i.e.
// invoker needs to have copy constructor defined.
template <class Invoker>
void ParallelFor(size_t start, size_t end, size_t grain_size,
const Invoker& invoker) {
#ifdef PARALLEL_INVOKER_ACTIVE
CheckAndSetInvokerOptions();
switch (flags_parallel_invoker_mode) {
#if defined(__APPLE__)
case PARALLEL_INVOKER_GCD: {
int iterations_remain = (end - start + grain_size - 1) / grain_size;
CHECK_GT(iterations_remain, 0);
if (iterations_remain == 1) {
// Execute invoker serially.
invoker(BlockedRange(start, std::min(end, start + grain_size), 1));
} else {
BlockedRange all_tasks(start, end, grain_size);
ParallelInvokerGCDContext<Invoker> context(invoker, all_tasks);
dispatch_queue_t concurrent_queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply_f(iterations_remain, concurrent_queue, &context,
ParallelForGCDTask<Invoker>);
#if CHECK_GCD_PARALLEL_WORK_COUNT
CHECK_EQ(iterations_remain, context.count());
#endif
}
break;
}
#endif // __APPLE__
case PARALLEL_INVOKER_THREAD_POOL: {
int iterations_remain = (end - start + grain_size - 1) / grain_size;
CHECK_GT(iterations_remain, 0);
if (iterations_remain == 1) {
// Execute invoker serially.
invoker(BlockedRange(start, std::min(end, start + grain_size), 1));
break;
}
struct {
absl::Mutex mutex;
absl::CondVar completed;
int iterations_remain ABSL_GUARDED_BY(mutex);
} loop;
{
absl::MutexLock lock(&loop.mutex);
loop.iterations_remain = iterations_remain;
}
for (int x = start; x < end; x += grain_size) {
auto loop_func = [x, end, grain_size, &loop, invoker]() {
// Execute invoker.
invoker(BlockedRange(x, std::min(end, x + grain_size), 1));
// Decrement counter.
absl::MutexLock lock(&loop.mutex);
--loop.iterations_remain;
if (loop.iterations_remain == 0) {
loop.completed.SignalAll();
}
};
// Attempt to run in parallel, if busy run serial to avoid deadlocking.
// This can happen during nested invocation of ParallelFor, as if the
// loop iteration itself is calling ParallelFor we might deadlock if
// we can not guarantee for the iteration to be scheduled.
ParallelInvokerThreadPool()->Schedule(loop_func);
}
// Wait on termination of all iterations.
loop.mutex.Lock();
while (loop.iterations_remain > 0) {
loop.completed.Wait(&loop.mutex);
}
loop.mutex.Unlock();
break;
}
case PARALLEL_INVOKER_OPENMP: {
// Use thread-local copy of invoker.
Invoker local_invoker(invoker);
#pragma omp parallel for firstprivate(local_invoker) \
num_threads(flags_parallel_invoker_max_threads)
for (int x = start; x < end; ++x) {
local_invoker(BlockedRange(x, x + 1, 1));
}
break;
}
case PARALLEL_INVOKER_NONE: {
SerialFor(start, end, grain_size, invoker);
break;
}
case PARALLEL_INVOKER_MAX_VALUE: {
LOG(FATAL) << "Impossible.";
break;
}
}
#else
SerialFor(start, end, grain_size, invoker);
#endif // PARALLEL_INVOKER_ACTIVE
}
// Simple wrapper for compatibility with below ParallelFor2D function.
template <class Invoker>
void SerialFor2D(size_t start_row, size_t end_row, size_t start_col,
size_t end_col, size_t grain_size, const Invoker& invoker) {
invoker(BlockedRange2D(BlockedRange(start_row, end_row, 1),
BlockedRange(start_col, end_col, 1)));
}
// Same as above ParallelFor for 2D iteration.
template <class Invoker>
void ParallelFor2D(size_t start_row, size_t end_row, size_t start_col,
size_t end_col, size_t grain_size, const Invoker& invoker) {
#ifdef PARALLEL_INVOKER_ACTIVE
CheckAndSetInvokerOptions();
switch (flags_parallel_invoker_mode) {
#if defined(__APPLE__)
case PARALLEL_INVOKER_GCD: {
const int iterations_remain =
(end_row - start_row + grain_size - 1) / grain_size;
CHECK_GT(iterations_remain, 0);
if (iterations_remain == 1) {
// Execute invoker serially.
invoker(BlockedRange2D(BlockedRange(start_row, end_row, 1),
BlockedRange(start_col, end_col, 1)));
} else {
BlockedRange all_tasks(start_row, end_row, grain_size);
ParallelInvokerGCDContext2D<Invoker> context(
invoker, all_tasks, BlockedRange(start_col, end_col, grain_size));
dispatch_queue_t concurrent_queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply_f(iterations_remain, concurrent_queue, &context,
ParallelForGCDTask2D<Invoker>);
#if CHECK_GCD_PARALLEL_WORK_COUNT
CHECK_EQ(iterations_remain, context.count());
#endif
}
break;
}
#endif // __APPLE__
case PARALLEL_INVOKER_THREAD_POOL: {
int iterations_remain = end_row - start_row; // Guarded by loop_mutex
CHECK_GT(iterations_remain, 0);
if (iterations_remain == 1) {
// Execute invoker serially.
invoker(BlockedRange2D(BlockedRange(start_row, end_row, 1),
BlockedRange(start_col, end_col, 1)));
break;
}
absl::Mutex loop_mutex;
absl::CondVar loop_completed;
for (int y = start_row; y < end_row; ++y) {
auto loop_func = [y, start_col, end_col, &loop_mutex, &loop_completed,
&iterations_remain, invoker]() {
// Execute invoker.
invoker(BlockedRange2D(BlockedRange(y, y + 1, 1),
BlockedRange(start_col, end_col, 1)));
// Decrement counter.
absl::MutexLock lock(&loop_mutex);
--iterations_remain;
if (iterations_remain == 0) {
loop_completed.Signal();
}
};
// Attempt to run in parallel, if busy run serial to avoid deadlocking.
ParallelInvokerThreadPool()->Schedule(loop_func);
}
// Wait on termination of all iterations.
loop_mutex.Lock();
while (iterations_remain > 0) {
loop_completed.Wait(&loop_mutex);
}
loop_mutex.Unlock();
break;
}
case PARALLEL_INVOKER_OPENMP: {
// Use thread-local copy of invoker.
Invoker local_invoker(invoker);
#pragma omp parallel for firstprivate(local_invoker) \
num_threads(flags_parallel_invoker_max_threads)
for (int y = start_row; y < end_row; ++y) {
local_invoker(BlockedRange2D(BlockedRange(y, y + 1, 1),
BlockedRange(start_col, end_col, 1)));
}
break;
}
case PARALLEL_INVOKER_NONE: {
SerialFor2D(start_row, end_row, start_col, end_col, grain_size, invoker);
break;
}
case PARALLEL_INVOKER_MAX_VALUE: {
LOG(FATAL) << "Impossible.";
break;
}
}
#else
SerialFor2D(start_row, end_row, start_col, end_col, grain_size, invoker);
#endif // PARALLEL_INVOKER_ACTIVE
}
} // namespace mediapipe
#endif // MEDIAPIPE_UTIL_TRACKING_PARALLEL_INVOKER_H_
|
opencl_keystore_fmt_plug.c | /* Java KeyStore password cracker for JtR.
* (will NOT address password(s) for alias(es) within keystore).
*
* OpenCL plugin by Terry West.
* Derived from keystore_fmt_plug.c,
* written by Dhiru Kholia <dhiru at openwall.com> and
* Narendra Kangralkar <narendrakangralkar at gmail.com>.
*
* Input Format: $keystore$target$salt_length$salt$hash$nkeys$keylength$keydata$keylength$keydata...
*
* This software is Copyright (c) 2015, Terry West <terrybwest at gmail dot com>
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without modification,
* are permitted.
*
* Fixes/enhancements JimF, Feb, 2016.
* corrected bug where binary passwords failed.
* reduced max size of password (performance improvement)
* don't convert password to BE shorts on CPU (reduced size and perf gain)
* reduced binary returned from GPU from full sized, to 4 bytes. (perf gain)
* compute full hash in CPU during cmp_exact()
* made a common code module (for sharing code with CPU)
* added 2 additional test vectors, and benmark_length changed from -1 to 0
* Performance about 2.5x for multi-salts on my Tahiti
*/
#ifdef HAVE_OPENCL
#if FMT_EXTERNS_H
extern struct fmt_main fmt_opencl_keystore;
#elif FMT_REGISTERS_H
john_register_one(&fmt_opencl_keystore);
#else
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "arch.h"
#include "sha.h"
#include "misc.h"
#include "common-opencl.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#include "keystore_common.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#include "memdbg.h"
#define FORMAT_LABEL "keystore-opencl"
#define FORMAT_NAME "Java KeyStore"
#define ALGORITHM_NAME "SHA1 32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH 0
// reduced PLAIN_LEN from 125 bytes, and speed went from 12.2k to 16.4k
#define PLAINTEXT_LENGTH 32
// reduced BIN_SIZE from 20 bytes to 4 for the GPU, and speed went from
// 16.4k to 17.8k. cmp_exact does a CPU hash check on possible matches.
#define SALT_SIZE sizeof(struct custom_salt)
#define SALT_ALIGN 4
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
// these to pass to kernel
typedef struct {
uint32_t length;
uint8_t pass[PLAINTEXT_LENGTH];
} keystore_password;
typedef struct {
uint32_t gpu_out; // GPU only returns first 4 bytes.
} keystore_hash;
typedef struct {
uint32_t length;
uint8_t salt[SALT_LENGTH_GPU];
} keystore_salt;
// this for use here
static struct custom_salt {
int length;
unsigned char salt[SALT_LENGTH_GPU];
} *cur_salt;
static struct fmt_main *self;
static size_t insize,
outsize,
saltsize;
static keystore_password *inbuffer;
static keystore_hash *outbuffer;
static keystore_salt saltbuffer;
static cl_mem mem_in,
mem_out,
mem_salt;
static cl_int cl_err;
// This file contains auto-tuning routine(s). Has to be included after formats definitions.
#include "opencl-autotune.h"
#include "memdbg.h"
static const char * warn[] = {
"xfer: ", ", crypt: ", ", xfer: "
};
/* ------- Helper functions ------- */
static size_t get_task_max_work_group_size()
{
return autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel);
}
static void create_clobj(size_t gws, struct fmt_main *self)
{
insize = sizeof(keystore_password) * gws;
outsize = sizeof(keystore_hash) * gws;
saltsize = sizeof(keystore_salt);
inbuffer = mem_calloc(1, insize);
outbuffer = mem_alloc(outsize);
/// Allocate memory
mem_in =
clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize,
NULL, &cl_err);
HANDLE_CLERROR(cl_err, "Error allocating mem_in");
mem_salt =
clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, saltsize,
NULL, &cl_err);
HANDLE_CLERROR(cl_err, "Error allocating mem_salt");
mem_out =
clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize,
NULL, &cl_err);
HANDLE_CLERROR(cl_err, "Error allocating mem_out");
HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in),
&mem_in), "Error while setting mem_in kernel argument");
HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_out),
&mem_out), "Error while setting mem_out kernel argument");
HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_salt),
&mem_salt), "Error while setting mem_salt kernel argument");
}
static void release_clobj(void)
{
if (mem_in) {
HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem_in");
HANDLE_CLERROR(clReleaseMemObject(mem_salt), "Release mem_salt");
HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem_out");
MEM_FREE(inbuffer);
MEM_FREE(outbuffer);
mem_in = NULL;
mem_salt = NULL;
mem_out = NULL;
}
}
static void init(struct fmt_main *_self)
{
self = _self;
opencl_prepare_dev(gpu_id);
}
static void reset(struct db_main *db)
{
// TODO
if (!autotuned) {
char build_opts[64];
snprintf(build_opts, sizeof(build_opts),
"-DPASSLEN=%d -DSALTLEN=%d -DOUTLEN=%d",
PLAINTEXT_LENGTH,
SALT_LENGTH_GPU,
4);
opencl_init("$JOHN/kernels/keystore_kernel.cl",
gpu_id, build_opts);
crypt_kernel = clCreateKernel(program[gpu_id], "keystore", &cl_err);
HANDLE_CLERROR(cl_err, "Error creating keystore kernel");
// Initialize openCL tuning (library) for this format.
opencl_init_auto_setup(0, 0, NULL, warn, 1, self,
create_clobj, release_clobj,
sizeof(keystore_password), 0, db);
// Auto tune execution from shared/included code.
autotune_run(self, 1, 2, (cpu(device_info[gpu_id]) ?
1000000000 : 10000000000ULL));//2000);
}
}
static void done(void)
{
if (autotuned) {
release_clobj();
HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel");
HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program");
--autotuned;
}
}
static void *get_salt(char *ciphertext)
{
/* NOTE: do we need dynamic allocation because of underlying large object size? */
static struct custom_salt *cs;
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
char *p;
int i;
if (!cs) cs = mem_alloc_tiny(sizeof(struct custom_salt),16);
memset(cs, 0, sizeof(struct custom_salt));
ctcopy += FORMAT_TAG_LEN; // skip over "$keystore$"
p = strtokm(ctcopy, "$"); // skip target
p = strtokm(NULL, "$");
cs->length = atoi(p);
p = strtokm(NULL, "$");
for (i = 0; i < cs->length; ++i)
cs->salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
/* we've got the salt, we can skip all the rest
p = strtokm(NULL, "$"); // skip hash
p = strtokm(NULL, "$");
cs->count = atoi(p);
p = strtokm(NULL, "$");
cs->keysize = atoi(p);
for (i = 0; i < cs->keysize; i++)
cs->keydata[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
*/
MEM_FREE(keeptr);
return (void *)cs;
}
static void set_salt(void *salt)
{
// Before the salt from the ciphertext, prepend
// "Mighty Aphrodite":
const char *magic = "Mighty Aphrodite";
int maglen = 16;
int i, j;
cur_salt = (struct custom_salt*)salt;
saltbuffer.length = maglen + cur_salt->length;
for (i = 0; i < maglen; ++i) {
saltbuffer.salt[i] = (uint8_t)magic[i];
}
for (j = 0; j < cur_salt->length; ++i, ++j) {
saltbuffer.salt[i] = cur_salt->salt[j];
}
HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_salt,
CL_FALSE, 0, saltsize,
&saltbuffer, 0, NULL, NULL),
"Copy salt to gpu");
}
static void keystore_set_key(char *key, int index)
{
uint32_t len = strlen(key);
memcpy(inbuffer[index].pass, key, len);
inbuffer[index].length = len;
}
static char *get_key(int index)
{
static char key[PLAINTEXT_LENGTH + 1];
memcpy(key, inbuffer[index].pass, inbuffer[index].length);
key[inbuffer[index].length] = 0;
return key;
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
size_t *lws = local_work_size ? &local_work_size : NULL;
global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size);
/// Copy password buffer to gpu
BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0,
insize, inbuffer, 0, NULL, multi_profilingEvent[0]),
"Copy data to gpu");
/// Run kernel
BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1,
NULL, &global_work_size, lws, 0, NULL,
multi_profilingEvent[1]), "Run kernel");
/// Read the result back
BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0,
outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back");
///Await completion of all the above
BENCH_CLERROR(clFinish(queue[gpu_id]), "clFinish error");
/*
if (ocl_autotune_running)
return count;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < count; index++)
if (memcmp(outbuffer[index].key//)
{
cracked[index] = 1;
#ifdef _OPENMP
#pragma omp atomic
#endif
any_cracked |= 1;
}
*/
return count;
}
/*tbw useful in debugging in cmp_all() keep for the mo ...
uint8_t out[20];
SHA_CTX ctx;
printf("\n");
printf("cmp_all() - count =%i\n", count);
printf("cmp_all() - pass length: %i\n",inbuffer[0].length);
printf("cmp_all() - pass: %s\n", get_key(0));
printf("cmp_all() - hash: %x %x %x %x %x\n",
outbuffer[0].key[0],
outbuffer[0].key[1],
outbuffer[0].key[2],
outbuffer[0].key[3],
outbuffer[0].key[4]);
printf("cmp_all() - binary: %x %x %x %x %x\n",
((uint32_t *)binary)[0],
((uint32_t *)binary)[1],
((uint32_t *)binary)[2],
((uint32_t *)binary)[3],
((uint32_t *)binary)[4]);
printf("----------------------------------------\n");
SHA1_Init(&ctx);
SHA1_Update(&ctx,inbuffer[0].pass,inbuffer[0].length);
SHA1_Update(&ctx,saltbuffer.salt,saltbuffer.length);
SHA1_Final(out, &ctx);
printf("cmp_all() - SHA1 hash: %x %x %x %x %x\n",
((uint32_t *)out)[0],
((uint32_t *)out)[1],
((uint32_t *)out)[2],
((uint32_t *)out)[3],
((uint32_t *)out)[4]);
*/
static int cmp_all(void *binary, int count)
{
uint32_t i, b = ((ARCH_WORD_32 *)binary)[0];
for (i = 0; i < count; ++i) {
if (b == outbuffer[i].gpu_out) {
return 1;
}
}
return 0;
}
static int cmp_one(void *binary, int index)
{
if (((ARCH_WORD_32*)binary)[0] != outbuffer[index].gpu_out) {
return 0;
}
return 1;
}
static int cmp_exact(char *source, int index)
{
// we do a CPU check here.
unsigned char *binary = (unsigned char *)keystore_common_get_binary(source);
unsigned char out[20];
SHA_CTX ctx;
unsigned char Pass[PLAINTEXT_LENGTH*2];
int i;
for (i = 0; i < inbuffer[index].length; ++i) {
Pass[i<<1] = 0;
Pass[(i<<1)+1] = inbuffer[index].pass[i];
}
SHA1_Init(&ctx);
SHA1_Update(&ctx, Pass, inbuffer[index].length<<1);
SHA1_Update(&ctx, "Mighty Aphrodite", 16);
SHA1_Update(&ctx, cur_salt->salt, cur_salt->length);
SHA1_Final(out, &ctx);
return !memcmp(binary, out, 20);
}
struct fmt_main fmt_opencl_keystore = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP,
/* FIXME: report cur_salt->length as tunable cost? */
{ NULL },
{ FORMAT_TAG },
keystore_common_tests
}, {
init,
done,
reset,
fmt_default_prepare,
keystore_common_valid_cpu,
fmt_default_split,
keystore_common_get_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash /* Not usable with $SOURCE_HASH$ */
},
fmt_default_salt_hash,
NULL,
set_salt,
keystore_set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash /* Not usable with $SOURCE_HASH$ */
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
#endif /* ifdef HAVE_OPENCL */
|
Sema.h | //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the Sema class, which performs semantic analysis and
// builds ASTs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SEMA_H
#define LLVM_CLANG_SEMA_SEMA_H
#include "clang/AST/Attr.h"
#include "clang/AST/Availability.h"
#include "clang/AST/ComparisonCategories.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/LocInfoType.h"
#include "clang/AST/MangleNumberingContext.h"
#include "clang/AST/NSAPI.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/TypeLoc.h"
#include "clang/AST/TypeOrdering.h"
#include "clang/Basic/ExpressionTraits.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/PragmaKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TemplateKinds.h"
#include "clang/Basic/TypeTraits.h"
#include "clang/Sema/AnalysisBasedWarnings.h"
#include "clang/Sema/CleanupInfo.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ExternalSemaSource.h"
#include "clang/Sema/IdentifierResolver.h"
#include "clang/Sema/ObjCMethodList.h"
#include "clang/Sema/Ownership.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/TypoCorrection.h"
#include "clang/Sema/Weak.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include <deque>
#include <memory>
#include <string>
#include <vector>
namespace llvm {
class APSInt;
template <typename ValueT> struct DenseMapInfo;
template <typename ValueT, typename ValueInfoT> class DenseSet;
class SmallBitVector;
struct InlineAsmIdentifierInfo;
}
namespace clang {
class ADLResult;
class ASTConsumer;
class ASTContext;
class ASTMutationListener;
class ASTReader;
class ASTWriter;
class ArrayType;
class ParsedAttr;
class BindingDecl;
class BlockDecl;
class CapturedDecl;
class CXXBasePath;
class CXXBasePaths;
class CXXBindTemporaryExpr;
typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
class CXXConstructorDecl;
class CXXConversionDecl;
class CXXDeleteExpr;
class CXXDestructorDecl;
class CXXFieldCollector;
class CXXMemberCallExpr;
class CXXMethodDecl;
class CXXScopeSpec;
class CXXTemporary;
class CXXTryStmt;
class CallExpr;
class ClassTemplateDecl;
class ClassTemplatePartialSpecializationDecl;
class ClassTemplateSpecializationDecl;
class VarTemplatePartialSpecializationDecl;
class CodeCompleteConsumer;
class CodeCompletionAllocator;
class CodeCompletionTUInfo;
class CodeCompletionResult;
class CoroutineBodyStmt;
class Decl;
class DeclAccessPair;
class DeclContext;
class DeclRefExpr;
class DeclaratorDecl;
class DeducedTemplateArgument;
class DependentDiagnostic;
class DesignatedInitExpr;
class Designation;
class EnableIfAttr;
class EnumConstantDecl;
class Expr;
class ExtVectorType;
class FormatAttr;
class FriendDecl;
class FunctionDecl;
class FunctionProtoType;
class FunctionTemplateDecl;
class ImplicitConversionSequence;
typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
class InitListExpr;
class InitializationKind;
class InitializationSequence;
class InitializedEntity;
class IntegerLiteral;
class LabelStmt;
class LambdaExpr;
class LangOptions;
class LocalInstantiationScope;
class LookupResult;
class MacroInfo;
typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
class ModuleLoader;
class MultiLevelTemplateArgumentList;
class NamedDecl;
class ObjCCategoryDecl;
class ObjCCategoryImplDecl;
class ObjCCompatibleAliasDecl;
class ObjCContainerDecl;
class ObjCImplDecl;
class ObjCImplementationDecl;
class ObjCInterfaceDecl;
class ObjCIvarDecl;
template <class T> class ObjCList;
class ObjCMessageExpr;
class ObjCMethodDecl;
class ObjCPropertyDecl;
class ObjCProtocolDecl;
class OMPThreadPrivateDecl;
class OMPRequiresDecl;
class OMPDeclareReductionDecl;
class OMPDeclareSimdDecl;
class OMPClause;
struct OMPVarListLocTy;
struct OverloadCandidate;
class OverloadCandidateSet;
class OverloadExpr;
class ParenListExpr;
class ParmVarDecl;
class Preprocessor;
class PseudoDestructorTypeStorage;
class PseudoObjectExpr;
class QualType;
class StandardConversionSequence;
class Stmt;
class StringLiteral;
class SwitchStmt;
class TemplateArgument;
class TemplateArgumentList;
class TemplateArgumentLoc;
class TemplateDecl;
class TemplateInstantiationCallback;
class TemplateParameterList;
class TemplatePartialOrderingContext;
class TemplateTemplateParmDecl;
class Token;
class TypeAliasDecl;
class TypedefDecl;
class TypedefNameDecl;
class TypeLoc;
class TypoCorrectionConsumer;
class UnqualifiedId;
class UnresolvedLookupExpr;
class UnresolvedMemberExpr;
class UnresolvedSetImpl;
class UnresolvedSetIterator;
class UsingDecl;
class UsingShadowDecl;
class ValueDecl;
class VarDecl;
class VarTemplateSpecializationDecl;
class VisibilityAttr;
class VisibleDeclConsumer;
class IndirectFieldDecl;
struct DeductionFailureInfo;
class TemplateSpecCandidateSet;
namespace sema {
class AccessedEntity;
class BlockScopeInfo;
class Capture;
class CapturedRegionScopeInfo;
class CapturingScopeInfo;
class CompoundScopeInfo;
class DelayedDiagnostic;
class DelayedDiagnosticPool;
class FunctionScopeInfo;
class LambdaScopeInfo;
class PossiblyUnreachableDiag;
class SemaPPCallbacks;
class TemplateDeductionInfo;
}
namespace threadSafety {
class BeforeSet;
void threadSafetyCleanup(BeforeSet* Cache);
}
// FIXME: No way to easily map from TemplateTypeParmTypes to
// TemplateTypeParmDecls, so we have this horrible PointerUnion.
typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
SourceLocation> UnexpandedParameterPack;
/// Describes whether we've seen any nullability information for the given
/// file.
struct FileNullability {
/// The first pointer declarator (of any pointer kind) in the file that does
/// not have a corresponding nullability annotation.
SourceLocation PointerLoc;
/// The end location for the first pointer declarator in the file. Used for
/// placing fix-its.
SourceLocation PointerEndLoc;
/// Which kind of pointer declarator we saw.
uint8_t PointerKind;
/// Whether we saw any type nullability annotations in the given file.
bool SawTypeNullability = false;
};
/// A mapping from file IDs to a record of whether we've seen nullability
/// information in that file.
class FileNullabilityMap {
/// A mapping from file IDs to the nullability information for each file ID.
llvm::DenseMap<FileID, FileNullability> Map;
/// A single-element cache based on the file ID.
struct {
FileID File;
FileNullability Nullability;
} Cache;
public:
FileNullability &operator[](FileID file) {
// Check the single-element cache.
if (file == Cache.File)
return Cache.Nullability;
// It's not in the single-element cache; flush the cache if we have one.
if (!Cache.File.isInvalid()) {
Map[Cache.File] = Cache.Nullability;
}
// Pull this entry into the cache.
Cache.File = file;
Cache.Nullability = Map[file];
return Cache.Nullability;
}
};
// TODO SYCL Integration header approach relies on an assumption that kernel
// lambda objects created by the host compiler and any of the device compilers
// will be identical wrt to field types, order and offsets. Some verification
// mechanism should be developed to enforce that.
// TODO FIXME SYCL Support for SYCL in FE should be refactored:
// - kernel identification and generation should be made a separate pass over
// AST. RecursiveASTVisitor + VisitFunctionTemplateDecl +
// FunctionTemplateDecl::getSpecializations() mechanism could be used for that.
// - All SYCL stuff on Sema level should be encapsulated into a single Sema
// field
// - Move SYCL stuff into a separate header
// Represents contents of a SYCL integration header file produced by a SYCL
// device compiler and used by SYCL host compiler (via forced inclusion into
// compiled SYCL source):
// - SYCL kernel names
// - SYCL kernel parameters and offsets of corresponding actual arguments
class SYCLIntegrationHeader {
public:
// Kind of kernel's parameters as captured by the compiler in the
// kernel lambda or function object
enum kernel_param_kind_t {
kind_first,
kind_accessor = kind_first,
kind_std_layout,
kind_sampler,
kind_pointer,
kind_last = kind_pointer
};
public:
SYCLIntegrationHeader(DiagnosticsEngine &Diag, bool UnnamedLambdaSupport);
/// Emits contents of the header into given stream.
void emit(raw_ostream &Out);
/// Emits contents of the header into a file with given name.
/// Returns true/false on success/failure.
bool emit(const StringRef &MainSrc);
/// Signals that subsequent parameter descriptor additions will go to
/// the kernel with given name. Starts new kernel invocation descriptor.
void startKernel(StringRef KernelName, QualType KernelNameType,
StringRef KernelStableName);
/// Adds a kernel parameter descriptor to current kernel invocation
/// descriptor.
void addParamDesc(kernel_param_kind_t Kind, int Info, unsigned Offset);
/// Signals that addition of parameter descriptors to current kernel
/// invocation descriptor has finished.
void endKernel();
private:
// Kernel actual parameter descriptor.
struct KernelParamDesc {
// Represents a parameter kind.
kernel_param_kind_t Kind = kind_last;
// If Kind is kind_scalar or kind_struct, then
// denotes parameter size in bytes (includes padding for structs)
// If Kind is kind_accessor
// denotes access target; possible access targets are defined in
// access/access.hpp
int Info = 0;
// Offset of the captured parameter value in the lambda or function object.
unsigned Offset = 0;
KernelParamDesc() = default;
};
// Kernel invocation descriptor
struct KernelDesc {
/// Kernel name.
std::string Name;
/// Kernel name type.
QualType NameType;
/// Kernel name with stable lambda name mangling
std::string StableName;
/// Descriptor of kernel actual parameters.
SmallVector<KernelParamDesc, 8> Params;
KernelDesc() = default;
};
/// Returns the latest invocation descriptor started by
/// SYCLIntegrationHeader::startKernel
KernelDesc *getCurKernelDesc() {
return KernelDescs.size() > 0 ? &KernelDescs[KernelDescs.size() - 1]
: nullptr;
}
/// Emits a forward declaration for given declaration.
void emitFwdDecl(raw_ostream &O, const Decl *D);
/// Emits forward declarations of classes and template classes on which
/// declaration of given type depends. See example in the comments for the
/// implementation.
/// \param O
/// stream to emit to
/// \param T
/// type to emit forward declarations for
/// \param Emitted
/// a set of declarations forward declrations has been emitted for already
void emitForwardClassDecls(raw_ostream &O, QualType T,
llvm::SmallPtrSetImpl<const void*> &Emitted);
private:
/// Keeps invocation descriptors for each kernel invocation started by
/// SYCLIntegrationHeader::startKernel
SmallVector<KernelDesc, 4> KernelDescs;
/// Used for emitting diagnostics.
DiagnosticsEngine &Diag;
/// Whether header is generated with unnamed lambda support
bool UnnamedLambdaSupport;
};
/// Keeps track of expected type during expression parsing. The type is tied to
/// a particular token, all functions that update or consume the type take a
/// start location of the token they are looking at as a parameter. This allows
/// to avoid updating the type on hot paths in the parser.
class PreferredTypeBuilder {
public:
PreferredTypeBuilder() = default;
explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
void enterCondition(Sema &S, SourceLocation Tok);
void enterReturn(Sema &S, SourceLocation Tok);
void enterVariableInit(SourceLocation Tok, Decl *D);
/// Computing a type for the function argument may require running
/// overloading, so we postpone its computation until it is actually needed.
///
/// Clients should be very careful when using this funciton, as it stores a
/// function_ref, clients should make sure all calls to get() with the same
/// location happen while function_ref is alive.
void enterFunctionArgument(SourceLocation Tok,
llvm::function_ref<QualType()> ComputeType);
void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
SourceLocation OpLoc);
void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
/// Handles all type casts, including C-style cast, C++ casts, etc.
void enterTypeCast(SourceLocation Tok, QualType CastType);
QualType get(SourceLocation Tok) const {
if (Tok != ExpectedLoc)
return QualType();
if (!Type.isNull())
return Type;
if (ComputeType)
return ComputeType();
return QualType();
}
private:
/// Start position of a token for which we store expected type.
SourceLocation ExpectedLoc;
/// Expected type for a token starting at ExpectedLoc.
QualType Type;
/// A function to compute expected type at ExpectedLoc. It is only considered
/// if Type is null.
llvm::function_ref<QualType()> ComputeType;
};
/// Sema - This implements semantic analysis and AST building for C.
class Sema {
Sema(const Sema &) = delete;
void operator=(const Sema &) = delete;
///Source of additional semantic information.
ExternalSemaSource *ExternalSource;
///Whether Sema has generated a multiplexer and has to delete it.
bool isMultiplexExternalSource;
static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
bool isVisibleSlow(const NamedDecl *D);
/// Determine whether two declarations should be linked together, given that
/// the old declaration might not be visible and the new declaration might
/// not have external linkage.
bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
const NamedDecl *New) {
if (isVisible(Old))
return true;
// See comment in below overload for why it's safe to compute the linkage
// of the new declaration here.
if (New->isExternallyDeclarable()) {
assert(Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl");
return true;
}
return false;
}
bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
QualType ResultTy,
ArrayRef<QualType> Args);
public:
typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
typedef OpaquePtr<TemplateName> TemplateTy;
typedef OpaquePtr<QualType> TypeTy;
OpenCLOptions OpenCLFeatures;
FPOptions FPFeatures;
const LangOptions &LangOpts;
Preprocessor &PP;
ASTContext &Context;
ASTConsumer &Consumer;
DiagnosticsEngine &Diags;
SourceManager &SourceMgr;
/// Flag indicating whether or not to collect detailed statistics.
bool CollectStats;
/// Code-completion consumer.
CodeCompleteConsumer *CodeCompleter;
/// CurContext - This is the current declaration context of parsing.
DeclContext *CurContext;
/// Generally null except when we temporarily switch decl contexts,
/// like in \see ActOnObjCTemporaryExitContainerContext.
DeclContext *OriginalLexicalContext;
/// VAListTagName - The declaration name corresponding to __va_list_tag.
/// This is used as part of a hack to omit that class from ADL results.
DeclarationName VAListTagName;
bool MSStructPragmaOn; // True when \#pragma ms_struct on
/// Controls member pointer representation format under the MS ABI.
LangOptions::PragmaMSPointersToMembersKind
MSPointerToMemberRepresentationMethod;
/// Stack of active SEH __finally scopes. Can be empty.
SmallVector<Scope*, 2> CurrentSEHFinally;
/// Source location for newly created implicit MSInheritanceAttrs
SourceLocation ImplicitMSInheritanceAttrLoc;
/// pragma clang section kind
enum PragmaClangSectionKind {
PCSK_Invalid = 0,
PCSK_BSS = 1,
PCSK_Data = 2,
PCSK_Rodata = 3,
PCSK_Text = 4
};
enum PragmaClangSectionAction {
PCSA_Set = 0,
PCSA_Clear = 1
};
struct PragmaClangSection {
std::string SectionName;
bool Valid = false;
SourceLocation PragmaLocation;
void Act(SourceLocation PragmaLocation,
PragmaClangSectionAction Action,
StringLiteral* Name);
};
PragmaClangSection PragmaClangBSSSection;
PragmaClangSection PragmaClangDataSection;
PragmaClangSection PragmaClangRodataSection;
PragmaClangSection PragmaClangTextSection;
enum PragmaMsStackAction {
PSK_Reset = 0x0, // #pragma ()
PSK_Set = 0x1, // #pragma (value)
PSK_Push = 0x2, // #pragma (push[, id])
PSK_Pop = 0x4, // #pragma (pop[, id])
PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
};
template<typename ValueType>
struct PragmaStack {
struct Slot {
llvm::StringRef StackSlotLabel;
ValueType Value;
SourceLocation PragmaLocation;
SourceLocation PragmaPushLocation;
Slot(llvm::StringRef StackSlotLabel, ValueType Value,
SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
: StackSlotLabel(StackSlotLabel), Value(Value),
PragmaLocation(PragmaLocation),
PragmaPushLocation(PragmaPushLocation) {}
};
void Act(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
ValueType Value);
// MSVC seems to add artificial slots to #pragma stacks on entering a C++
// method body to restore the stacks on exit, so it works like this:
//
// struct S {
// #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
// void Method {}
// #pragma <name>(pop, InternalPragmaSlot)
// };
//
// It works even with #pragma vtordisp, although MSVC doesn't support
// #pragma vtordisp(push [, id], n)
// syntax.
//
// Push / pop a named sentinel slot.
void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
assert((Action == PSK_Push || Action == PSK_Pop) &&
"Can only push / pop #pragma stack sentinels!");
Act(CurrentPragmaLocation, Action, Label, CurrentValue);
}
// Constructors.
explicit PragmaStack(const ValueType &Default)
: DefaultValue(Default), CurrentValue(Default) {}
bool hasValue() const { return CurrentValue != DefaultValue; }
SmallVector<Slot, 2> Stack;
ValueType DefaultValue; // Value used for PSK_Reset action.
ValueType CurrentValue;
SourceLocation CurrentPragmaLocation;
};
// FIXME: We should serialize / deserialize these if they occur in a PCH (but
// we shouldn't do so if they're in a module).
/// Whether to insert vtordisps prior to virtual bases in the Microsoft
/// C++ ABI. Possible values are 0, 1, and 2, which mean:
///
/// 0: Suppress all vtordisps
/// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
/// structors
/// 2: Always insert vtordisps to support RTTI on partially constructed
/// objects
PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
// #pragma pack.
// Sentinel to represent when the stack is set to mac68k alignment.
static const unsigned kMac68kAlignmentSentinel = ~0U;
PragmaStack<unsigned> PackStack;
// The current #pragma pack values and locations at each #include.
struct PackIncludeState {
unsigned CurrentValue;
SourceLocation CurrentPragmaLocation;
bool HasNonDefaultValue, ShouldWarnOnInclude;
};
SmallVector<PackIncludeState, 8> PackIncludeStack;
// Segment #pragmas.
PragmaStack<StringLiteral *> DataSegStack;
PragmaStack<StringLiteral *> BSSSegStack;
PragmaStack<StringLiteral *> ConstSegStack;
PragmaStack<StringLiteral *> CodeSegStack;
// RAII object to push / pop sentinel slots for all MS #pragma stacks.
// Actions should be performed only if we enter / exit a C++ method body.
class PragmaStackSentinelRAII {
public:
PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
~PragmaStackSentinelRAII();
private:
Sema &S;
StringRef SlotLabel;
bool ShouldAct;
};
/// A mapping that describes the nullability we've seen in each header file.
FileNullabilityMap NullabilityMap;
/// Last section used with #pragma init_seg.
StringLiteral *CurInitSeg;
SourceLocation CurInitSegLoc;
/// VisContext - Manages the stack for \#pragma GCC visibility.
void *VisContext; // Really a "PragmaVisStack*"
/// This an attribute introduced by \#pragma clang attribute.
struct PragmaAttributeEntry {
SourceLocation Loc;
ParsedAttr *Attribute;
SmallVector<attr::SubjectMatchRule, 4> MatchRules;
bool IsUsed;
};
/// A push'd group of PragmaAttributeEntries.
struct PragmaAttributeGroup {
/// The location of the push attribute.
SourceLocation Loc;
/// The namespace of this push group.
const IdentifierInfo *Namespace;
SmallVector<PragmaAttributeEntry, 2> Entries;
};
SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
/// The declaration that is currently receiving an attribute from the
/// #pragma attribute stack.
const Decl *PragmaAttributeCurrentTargetDecl;
/// This represents the last location of a "#pragma clang optimize off"
/// directive if such a directive has not been closed by an "on" yet. If
/// optimizations are currently "on", this is set to an invalid location.
SourceLocation OptimizeOffPragmaLocation;
/// Flag indicating if Sema is building a recovery call expression.
///
/// This flag is used to avoid building recovery call expressions
/// if Sema is already doing so, which would cause infinite recursions.
bool IsBuildingRecoveryCallExpr;
/// Used to control the generation of ExprWithCleanups.
CleanupInfo Cleanup;
/// ExprCleanupObjects - This is the stack of objects requiring
/// cleanup that are created by the current full expression. The
/// element type here is ExprWithCleanups::Object.
SmallVector<BlockDecl*, 8> ExprCleanupObjects;
/// Store a set of either DeclRefExprs or MemberExprs that contain a reference
/// to a variable (constant) that may or may not be odr-used in this Expr, and
/// we won't know until all lvalue-to-rvalue and discarded value conversions
/// have been applied to all subexpressions of the enclosing full expression.
/// This is cleared at the end of each full expression.
using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
MaybeODRUseExprSet MaybeODRUseExprs;
std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
/// Stack containing information about each of the nested
/// function, block, and method scopes that are currently active.
SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadExtVectorDecls, 2, 2>
ExtVectorDeclsType;
/// ExtVectorDecls - This is a list all the extended vector types. This allows
/// us to associate a raw vector type with one of the ext_vector type names.
/// This is only necessary for issuing pretty diagnostics.
ExtVectorDeclsType ExtVectorDecls;
/// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
std::unique_ptr<CXXFieldCollector> FieldCollector;
typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
/// Set containing all declared private fields that are not used.
NamedDeclSetType UnusedPrivateFields;
/// Set containing all typedefs that are likely unused.
llvm::SmallSetVector<const TypedefNameDecl *, 4>
UnusedLocalTypedefNameCandidates;
/// Delete-expressions to be analyzed at the end of translation unit
///
/// This list contains class members, and locations of delete-expressions
/// that could not be proven as to whether they mismatch with new-expression
/// used in initializer of the field.
typedef std::pair<SourceLocation, bool> DeleteExprLoc;
typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
/// PureVirtualClassDiagSet - a set of class declarations which we have
/// emitted a list of pure virtual functions. Used to prevent emitting the
/// same list more than once.
std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
/// ParsingInitForAutoVars - a set of declarations with auto types for which
/// we are currently parsing the initializer.
llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
/// Look for a locally scoped extern "C" declaration by the given name.
NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
typedef LazyVector<VarDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
TentativeDefinitionsType;
/// All the tentative definitions encountered in the TU.
TentativeDefinitionsType TentativeDefinitions;
typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
UnusedFileScopedDeclsType;
/// The set of file scoped decls seen so far that have not been used
/// and must warn if not used. Only contains the first declaration.
UnusedFileScopedDeclsType UnusedFileScopedDecls;
typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
DelegatingCtorDeclsType;
/// All the delegating constructors seen so far in the file, used for
/// cycle detection at the end of the TU.
DelegatingCtorDeclsType DelegatingCtorDecls;
/// All the overriding functions seen during a class definition
/// that had their exception spec checks delayed, plus the overridden
/// function.
SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
DelayedOverridingExceptionSpecChecks;
/// All the function redeclarations seen during a class definition that had
/// their exception spec checks delayed, plus the prior declaration they
/// should be checked against. Except during error recovery, the new decl
/// should always be a friend declaration, as that's the only valid way to
/// redeclare a special member before its class is complete.
SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
DelayedEquivalentExceptionSpecChecks;
typedef llvm::MapVector<const FunctionDecl *,
std::unique_ptr<LateParsedTemplate>>
LateParsedTemplateMapT;
LateParsedTemplateMapT LateParsedTemplateMap;
/// Callback to the parser to parse templated functions when needed.
typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
typedef void LateTemplateParserCleanupCB(void *P);
LateTemplateParserCB *LateTemplateParser;
LateTemplateParserCleanupCB *LateTemplateParserCleanup;
void *OpaqueParser;
void SetLateTemplateParser(LateTemplateParserCB *LTP,
LateTemplateParserCleanupCB *LTPCleanup,
void *P) {
LateTemplateParser = LTP;
LateTemplateParserCleanup = LTPCleanup;
OpaqueParser = P;
}
class DelayedDiagnostics;
class DelayedDiagnosticsState {
sema::DelayedDiagnosticPool *SavedPool;
friend class Sema::DelayedDiagnostics;
};
typedef DelayedDiagnosticsState ParsingDeclState;
typedef DelayedDiagnosticsState ProcessingContextState;
/// A class which encapsulates the logic for delaying diagnostics
/// during parsing and other processing.
class DelayedDiagnostics {
/// The current pool of diagnostics into which delayed
/// diagnostics should go.
sema::DelayedDiagnosticPool *CurPool;
public:
DelayedDiagnostics() : CurPool(nullptr) {}
/// Adds a delayed diagnostic.
void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
/// Determines whether diagnostics should be delayed.
bool shouldDelayDiagnostics() { return CurPool != nullptr; }
/// Returns the current delayed-diagnostics pool.
sema::DelayedDiagnosticPool *getCurrentPool() const {
return CurPool;
}
/// Enter a new scope. Access and deprecation diagnostics will be
/// collected in this pool.
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = &pool;
return state;
}
/// Leave a delayed-diagnostic state that was previously pushed.
/// Do not emit any of the diagnostics. This is performed as part
/// of the bookkeeping of popping a pool "properly".
void popWithoutEmitting(DelayedDiagnosticsState state) {
CurPool = state.SavedPool;
}
/// Enter a new scope where access and deprecation diagnostics are
/// not delayed.
DelayedDiagnosticsState pushUndelayed() {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = nullptr;
return state;
}
/// Undo a previous pushUndelayed().
void popUndelayed(DelayedDiagnosticsState state) {
assert(CurPool == nullptr);
CurPool = state.SavedPool;
}
} DelayedDiagnostics;
/// A RAII object to temporarily push a declaration context.
class ContextRAII {
private:
Sema &S;
DeclContext *SavedContext;
ProcessingContextState SavedContextState;
QualType SavedCXXThisTypeOverride;
public:
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
: S(S), SavedContext(S.CurContext),
SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
{
assert(ContextToPush && "pushing null context");
S.CurContext = ContextToPush;
if (NewThisContext)
S.CXXThisTypeOverride = QualType();
}
void pop() {
if (!SavedContext) return;
S.CurContext = SavedContext;
S.DelayedDiagnostics.popUndelayed(SavedContextState);
S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
SavedContext = nullptr;
}
~ContextRAII() {
pop();
}
};
/// Used to change context to isConstantEvaluated without pushing a heavy
/// ExpressionEvaluationContextRecord object.
bool isConstantEvaluatedOverride;
bool isConstantEvaluated() {
return ExprEvalContexts.back().isConstantEvaluated() ||
isConstantEvaluatedOverride;
}
/// RAII object to handle the state changes required to synthesize
/// a function body.
class SynthesizedFunctionScope {
Sema &S;
Sema::ContextRAII SavedContext;
bool PushedCodeSynthesisContext = false;
public:
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
: S(S), SavedContext(S, DC) {
S.PushFunctionScope();
S.PushExpressionEvaluationContext(
Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
if (auto *FD = dyn_cast<FunctionDecl>(DC))
FD->setWillHaveBody(true);
else
assert(isa<ObjCMethodDecl>(DC));
}
void addContextNote(SourceLocation UseLoc) {
assert(!PushedCodeSynthesisContext);
Sema::CodeSynthesisContext Ctx;
Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
Ctx.PointOfInstantiation = UseLoc;
Ctx.Entity = cast<Decl>(S.CurContext);
S.pushCodeSynthesisContext(Ctx);
PushedCodeSynthesisContext = true;
}
~SynthesizedFunctionScope() {
if (PushedCodeSynthesisContext)
S.popCodeSynthesisContext();
if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
FD->setWillHaveBody(false);
S.PopExpressionEvaluationContext();
S.PopFunctionScopeInfo();
}
};
/// WeakUndeclaredIdentifiers - Identifiers contained in
/// \#pragma weak before declared. rare. may alias another
/// identifier, declared or undeclared
llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
/// ExtnameUndeclaredIdentifiers - Identifiers contained in
/// \#pragma redefine_extname before declared. Used in Solaris system headers
/// to define functions that occur in multiple standards to call the version
/// in the currently selected standard.
llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
/// Load weak undeclared identifiers from the external source.
void LoadExternalWeakUndeclaredIdentifiers();
/// WeakTopLevelDecl - Translation-unit scoped declarations generated by
/// \#pragma weak during processing of other Decls.
/// I couldn't figure out a clean way to generate these in-line, so
/// we store them here and handle separately -- which is a hack.
/// It would be best to refactor this.
SmallVector<Decl*,2> WeakTopLevelDecl;
IdentifierResolver IdResolver;
/// Translation Unit Scope - useful to Objective-C actions that need
/// to lookup file scope declarations in the "ordinary" C decl namespace.
/// For example, user-defined classes, built-in "id" type, etc.
Scope *TUScope;
/// The C++ "std" namespace, where the standard library resides.
LazyDeclPtr StdNamespace;
/// The C++ "std::bad_alloc" class, which is defined by the C++
/// standard library.
LazyDeclPtr StdBadAlloc;
/// The C++ "std::align_val_t" enum class, which is defined by the C++
/// standard library.
LazyDeclPtr StdAlignValT;
/// The C++ "std::experimental" namespace, where the experimental parts
/// of the standard library resides.
NamespaceDecl *StdExperimentalNamespaceCache;
/// The C++ "std::initializer_list" template, which is defined in
/// \<initializer_list>.
ClassTemplateDecl *StdInitializerList;
/// The C++ "std::coroutine_traits" template, which is defined in
/// \<coroutine_traits>
ClassTemplateDecl *StdCoroutineTraitsCache;
/// The C++ "type_info" declaration, which is defined in \<typeinfo>.
RecordDecl *CXXTypeInfoDecl;
/// The MSVC "_GUID" struct, which is defined in MSVC header files.
RecordDecl *MSVCGuidDecl;
/// Caches identifiers/selectors for NSFoundation APIs.
std::unique_ptr<NSAPI> NSAPIObj;
/// The declaration of the Objective-C NSNumber class.
ObjCInterfaceDecl *NSNumberDecl;
/// The declaration of the Objective-C NSValue class.
ObjCInterfaceDecl *NSValueDecl;
/// Pointer to NSNumber type (NSNumber *).
QualType NSNumberPointer;
/// Pointer to NSValue type (NSValue *).
QualType NSValuePointer;
/// The Objective-C NSNumber methods used to create NSNumber literals.
ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
/// The declaration of the Objective-C NSString class.
ObjCInterfaceDecl *NSStringDecl;
/// Pointer to NSString type (NSString *).
QualType NSStringPointer;
/// The declaration of the stringWithUTF8String: method.
ObjCMethodDecl *StringWithUTF8StringMethod;
/// The declaration of the valueWithBytes:objCType: method.
ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
/// The declaration of the Objective-C NSArray class.
ObjCInterfaceDecl *NSArrayDecl;
/// The declaration of the arrayWithObjects:count: method.
ObjCMethodDecl *ArrayWithObjectsMethod;
/// The declaration of the Objective-C NSDictionary class.
ObjCInterfaceDecl *NSDictionaryDecl;
/// The declaration of the dictionaryWithObjects:forKeys:count: method.
ObjCMethodDecl *DictionaryWithObjectsMethod;
/// id<NSCopying> type.
QualType QIDNSCopying;
/// will hold 'respondsToSelector:'
Selector RespondsToSelectorSel;
/// A flag to remember whether the implicit forms of operator new and delete
/// have been declared.
bool GlobalNewDeleteDeclared;
/// A flag to indicate that we're in a context that permits abstract
/// references to fields. This is really a
bool AllowAbstractFieldReference;
/// Describes how the expressions currently being parsed are
/// evaluated at run-time, if at all.
enum class ExpressionEvaluationContext {
/// The current expression and its subexpressions occur within an
/// unevaluated operand (C++11 [expr]p7), such as the subexpression of
/// \c sizeof, where the type of the expression may be significant but
/// no code will be generated to evaluate the value of the expression at
/// run time.
Unevaluated,
/// The current expression occurs within a braced-init-list within
/// an unevaluated operand. This is mostly like a regular unevaluated
/// context, except that we still instantiate constexpr functions that are
/// referenced here so that we can perform narrowing checks correctly.
UnevaluatedList,
/// The current expression occurs within a discarded statement.
/// This behaves largely similarly to an unevaluated operand in preventing
/// definitions from being required, but not in other ways.
DiscardedStatement,
/// The current expression occurs within an unevaluated
/// operand that unconditionally permits abstract references to
/// fields, such as a SIZE operator in MS-style inline assembly.
UnevaluatedAbstract,
/// The current context is "potentially evaluated" in C++11 terms,
/// but the expression is evaluated at compile-time (like the values of
/// cases in a switch statement).
ConstantEvaluated,
/// The current expression is potentially evaluated at run time,
/// which means that code may be generated to evaluate the value of the
/// expression at run time.
PotentiallyEvaluated,
/// The current expression is potentially evaluated, but any
/// declarations referenced inside that expression are only used if
/// in fact the current expression is used.
///
/// This value is used when parsing default function arguments, for which
/// we would like to provide diagnostics (e.g., passing non-POD arguments
/// through varargs) but do not want to mark declarations as "referenced"
/// until the default argument is used.
PotentiallyEvaluatedIfUsed
};
/// Data structure used to record current or nested
/// expression evaluation contexts.
struct ExpressionEvaluationContextRecord {
/// The expression evaluation context.
ExpressionEvaluationContext Context;
/// Whether the enclosing context needed a cleanup.
CleanupInfo ParentCleanup;
/// Whether we are in a decltype expression.
bool IsDecltype;
/// The number of active cleanup objects when we entered
/// this expression evaluation context.
unsigned NumCleanupObjects;
/// The number of typos encountered during this expression evaluation
/// context (i.e. the number of TypoExprs created).
unsigned NumTypos;
MaybeODRUseExprSet SavedMaybeODRUseExprs;
/// The lambdas that are present within this context, if it
/// is indeed an unevaluated context.
SmallVector<LambdaExpr *, 2> Lambdas;
/// The declaration that provides context for lambda expressions
/// and block literals if the normal declaration context does not
/// suffice, e.g., in a default function argument.
Decl *ManglingContextDecl;
/// The context information used to mangle lambda expressions
/// and block literals within this context.
///
/// This mangling information is allocated lazily, since most contexts
/// do not have lambda expressions or block literals.
std::unique_ptr<MangleNumberingContext> MangleNumbering;
/// If we are processing a decltype type, a set of call expressions
/// for which we have deferred checking the completeness of the return type.
SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
/// If we are processing a decltype type, a set of temporary binding
/// expressions for which we have deferred checking the destructor.
SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
/// \brief Describes whether we are in an expression constext which we have
/// to handle differently.
enum ExpressionKind {
EK_Decltype, EK_TemplateArgument, EK_Other
} ExprContext;
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
unsigned NumCleanupObjects,
CleanupInfo ParentCleanup,
Decl *ManglingContextDecl,
ExpressionKind ExprContext)
: Context(Context), ParentCleanup(ParentCleanup),
NumCleanupObjects(NumCleanupObjects), NumTypos(0),
ManglingContextDecl(ManglingContextDecl), MangleNumbering(),
ExprContext(ExprContext) {}
/// Retrieve the mangling numbering context, used to consistently
/// number constructs like lambdas for mangling.
MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
bool isUnevaluated() const {
return Context == ExpressionEvaluationContext::Unevaluated ||
Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
Context == ExpressionEvaluationContext::UnevaluatedList;
}
bool isConstantEvaluated() const {
return Context == ExpressionEvaluationContext::ConstantEvaluated;
}
};
/// A stack of expression evaluation contexts.
SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
/// Emit a warning for all pending noderef expressions that we recorded.
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
/// Compute the mangling number context for a lambda expression or
/// block literal.
///
/// \param DC - The DeclContext containing the lambda expression or
/// block literal.
/// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
/// associated with the context, if relevant.
MangleNumberingContext *getCurrentMangleNumberContext(
const DeclContext *DC,
Decl *&ManglingContextDecl);
/// SpecialMemberOverloadResult - The overloading result for a special member
/// function.
///
/// This is basically a wrapper around PointerIntPair. The lowest bits of the
/// integer are used to determine whether overload resolution succeeded.
class SpecialMemberOverloadResult {
public:
enum Kind {
NoMemberOrDeleted,
Ambiguous,
Success
};
private:
llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
public:
SpecialMemberOverloadResult() : Pair() {}
SpecialMemberOverloadResult(CXXMethodDecl *MD)
: Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
void setKind(Kind K) { Pair.setInt(K); }
};
class SpecialMemberOverloadResultEntry
: public llvm::FastFoldingSetNode,
public SpecialMemberOverloadResult {
public:
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
: FastFoldingSetNode(ID)
{}
};
/// A cache of special member function overload resolution results
/// for C++ records.
llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
/// A cache of the flags available in enumerations with the flag_bits
/// attribute.
mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
/// The kind of translation unit we are processing.
///
/// When we're processing a complete translation unit, Sema will perform
/// end-of-translation-unit semantic tasks (such as creating
/// initializers for tentative definitions in C) once parsing has
/// completed. Modules and precompiled headers perform different kinds of
/// checks.
TranslationUnitKind TUKind;
llvm::BumpPtrAllocator BumpAlloc;
/// The number of SFINAE diagnostics that have been trapped.
unsigned NumSFINAEErrors;
typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
UnparsedDefaultArgInstantiationsMap;
/// A mapping from parameters with unparsed default arguments to the
/// set of instantiations of each parameter.
///
/// This mapping is a temporary data structure used when parsing
/// nested class templates or nested classes of class templates,
/// where we might end up instantiating an inner class before the
/// default arguments of its methods have been parsed.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
// Contains the locations of the beginning of unparsed default
// argument locations.
llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
/// UndefinedInternals - all the used, undefined objects which require a
/// definition in this translation unit.
llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
/// Determine if VD, which must be a variable or function, is an external
/// symbol that nonetheless can't be referenced from outside this translation
/// unit because its type has no linkage and it's not extern "C".
bool isExternalWithNoLinkageType(ValueDecl *VD);
/// Obtain a sorted list of functions that are undefined but ODR-used.
void getUndefinedButUsed(
SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
/// Retrieves list of suspicious delete-expressions that will be checked at
/// the end of translation unit.
const llvm::MapVector<FieldDecl *, DeleteLocs> &
getMismatchingDeleteExpressions() const;
typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
/// Method Pool - allows efficient lookup when typechecking messages to "id".
/// We need to maintain a list, since selectors can have differing signatures
/// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
/// of selectors are "overloaded").
/// At the head of the list it is recorded whether there were 0, 1, or >= 2
/// methods inside categories with a particular selector.
GlobalMethodPool MethodPool;
/// Method selectors used in a \@selector expression. Used for implementation
/// of -Wselector.
llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
/// List of SourceLocations where 'self' is implicitly retained inside a
/// block.
llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
ImplicitlyRetainedSelfLocs;
/// Kinds of C++ special members.
enum CXXSpecialMember {
CXXDefaultConstructor,
CXXCopyConstructor,
CXXMoveConstructor,
CXXCopyAssignment,
CXXMoveAssignment,
CXXDestructor,
CXXInvalid
};
typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
SpecialMemberDecl;
/// The C++ special members which we are currently in the process of
/// declaring. If this process recursively triggers the declaration of the
/// same special member, we should act as if it is not yet declared.
llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
/// The function definitions which were renamed as part of typo-correction
/// to match their respective declarations. We want to keep track of them
/// to ensure that we don't emit a "redefinition" error if we encounter a
/// correctly named definition after the renamed definition.
llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
/// Stack of types that correspond to the parameter entities that are
/// currently being copy-initialized. Can be empty.
llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
void ReadMethodPool(Selector Sel);
void updateOutOfDateSelector(Selector Sel);
/// Private Helper predicate to check for 'self'.
bool isSelfExpr(Expr *RExpr);
bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
/// Cause the active diagnostic on the DiagosticsEngine to be
/// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
/// should not be used elsewhere.
void EmitCurrentDiagnostic(unsigned DiagID);
/// Records and restores the FP_CONTRACT state on entry/exit of compound
/// statements.
class FPContractStateRAII {
public:
FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
private:
Sema& S;
FPOptions OldFPFeaturesState;
};
void addImplicitTypedef(StringRef Name, QualType T);
public:
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
TranslationUnitKind TUKind = TU_Complete,
CodeCompleteConsumer *CompletionConsumer = nullptr);
~Sema();
/// Perform initialization that occurs after the parser has been
/// initialized but before it parses anything.
void Initialize();
const LangOptions &getLangOpts() const { return LangOpts; }
OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
FPOptions &getFPOptions() { return FPFeatures; }
DiagnosticsEngine &getDiagnostics() const { return Diags; }
SourceManager &getSourceManager() const { return SourceMgr; }
Preprocessor &getPreprocessor() const { return PP; }
ASTContext &getASTContext() const { return Context; }
ASTConsumer &getASTConsumer() const { return Consumer; }
ASTMutationListener *getASTMutationListener() const;
ExternalSemaSource* getExternalSource() const { return ExternalSource; }
///Registers an external source. If an external source already exists,
/// creates a multiplex external source and appends to it.
///
///\param[in] E - A non-null external sema source.
///
void addExternalSource(ExternalSemaSource *E);
void PrintStats() const;
/// Helper class that creates diagnostics with optional
/// template instantiation stacks.
///
/// This class provides a wrapper around the basic DiagnosticBuilder
/// class that emits diagnostics. SemaDiagnosticBuilder is
/// responsible for emitting the diagnostic (as DiagnosticBuilder
/// does) and, if the diagnostic comes from inside a template
/// instantiation, printing the template instantiation stack as
/// well.
class SemaDiagnosticBuilder : public DiagnosticBuilder {
Sema &SemaRef;
unsigned DiagID;
public:
SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
: DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
// This is a cunning lie. DiagnosticBuilder actually performs move
// construction in its copy constructor (but due to varied uses, it's not
// possible to conveniently express this as actual move construction). So
// the default copy ctor here is fine, because the base class disables the
// source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
// in that case anwyay.
SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
~SemaDiagnosticBuilder() {
// If we aren't active, there is nothing to do.
if (!isActive()) return;
// Otherwise, we need to emit the diagnostic. First flush the underlying
// DiagnosticBuilder data, and clear the diagnostic builder itself so it
// won't emit the diagnostic in its own destructor.
//
// This seems wasteful, in that as written the DiagnosticBuilder dtor will
// do its own needless checks to see if the diagnostic needs to be
// emitted. However, because we take care to ensure that the builder
// objects never escape, a sufficiently smart compiler will be able to
// eliminate that code.
FlushCounts();
Clear();
// Dispatch to Sema to emit the diagnostic.
SemaRef.EmitCurrentDiagnostic(DiagID);
}
/// Teach operator<< to produce an object of the correct type.
template<typename T>
friend const SemaDiagnosticBuilder &operator<<(
const SemaDiagnosticBuilder &Diag, const T &Value) {
const DiagnosticBuilder &BaseDiag = Diag;
BaseDiag << Value;
return Diag;
}
};
/// Emit a diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
return SemaDiagnosticBuilder(DB, *this, DiagID);
}
/// Emit a partial diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
/// Build a partial diagnostic.
PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
bool findMacroSpelling(SourceLocation &loc, StringRef name);
/// Get a string to suggest for zero-initialization of a type.
std::string
getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
/// Calls \c Lexer::getLocForEndOfToken()
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
/// Retrieve the module loader associated with the preprocessor.
ModuleLoader &getModuleLoader() const;
void emitAndClearUnusedLocalTypedefWarnings();
enum TUFragmentKind {
/// The global module fragment, between 'module;' and a module-declaration.
Global,
/// A normal translation unit fragment. For a non-module unit, this is the
/// entire translation unit. Otherwise, it runs from the module-declaration
/// to the private-module-fragment (if any) or the end of the TU (if not).
Normal,
/// The private module fragment, between 'module :private;' and the end of
/// the translation unit.
Private
};
void ActOnStartOfTranslationUnit();
void ActOnEndOfTranslationUnit();
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
void CheckDelegatingCtorCycles();
Scope *getScopeForContext(DeclContext *Ctx);
void PushFunctionScope();
void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
sema::LambdaScopeInfo *PushLambdaScope();
/// This is used to inform Sema what the current TemplateParameterDepth
/// is during Parsing. Currently it is used to pass on the depth
/// when parsing generic lambda 'auto' parameters.
void RecordParsingTemplateParameterDepth(unsigned Depth);
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
RecordDecl *RD,
CapturedRegionKind K);
/// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
/// time after they've been popped.
class PoppedFunctionScopeDeleter {
Sema *Self;
public:
explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
void operator()(sema::FunctionScopeInfo *Scope) const;
};
using PoppedFunctionScopePtr =
std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
PoppedFunctionScopePtr
PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
const Decl *D = nullptr,
QualType BlockType = QualType());
sema::FunctionScopeInfo *getCurFunction() const {
return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
}
sema::FunctionScopeInfo *getEnclosingFunction() const;
void setFunctionHasBranchIntoScope();
void setFunctionHasBranchProtectedScope();
void setFunctionHasIndirectGoto();
void PushCompoundScope(bool IsStmtExpr);
void PopCompoundScope();
sema::CompoundScopeInfo &getCurCompoundScope() const;
bool hasAnyUnrecoverableErrorsInThisFunction() const;
/// Retrieve the current block, if any.
sema::BlockScopeInfo *getCurBlock();
/// Retrieve the current lambda scope info, if any.
/// \param IgnoreNonLambdaCapturingScope true if should find the top-most
/// lambda scope info ignoring all inner capturing scopes that are not
/// lambda scopes.
sema::LambdaScopeInfo *
getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
/// Retrieve the current generic lambda info, if any.
sema::LambdaScopeInfo *getCurGenericLambda();
/// Retrieve the current captured region, if any.
sema::CapturedRegionScopeInfo *getCurCapturedRegion();
/// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
void ActOnComment(SourceRange Comment);
//===--------------------------------------------------------------------===//
// Type Analysis / Processing: SemaType.cpp.
//
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
const DeclSpec *DS = nullptr);
QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
const DeclSpec *DS = nullptr);
QualType BuildPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildReferenceType(QualType T, bool LValueRef,
SourceLocation Loc, DeclarationName Entity);
QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
Expr *ArraySize, unsigned Quals,
SourceRange Brackets, DeclarationName Entity);
QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
QualType BuildExtVectorType(QualType T, Expr *ArraySize,
SourceLocation AttrLoc);
QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
SourceLocation AttrLoc);
/// Same as above, but constructs the AddressSpace index if not provided.
QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
SourceLocation AttrLoc);
bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
/// Build a function type.
///
/// This routine checks the function type according to C++ rules and
/// under the assumption that the result type and parameter types have
/// just been instantiated from a template. It therefore duplicates
/// some of the behavior of GetTypeForDeclarator, but in a much
/// simpler form that is only suitable for this narrow use case.
///
/// \param T The return type of the function.
///
/// \param ParamTypes The parameter types of the function. This array
/// will be modified to account for adjustments to the types of the
/// function parameters.
///
/// \param Loc The location of the entity whose type involves this
/// function type or, if there is no such entity, the location of the
/// type that will have function type.
///
/// \param Entity The name of the entity that involves the function
/// type, if known.
///
/// \param EPI Extra information about the function type. Usually this will
/// be taken from an existing function with the same prototype.
///
/// \returns A suitable function type, if there are no errors. The
/// unqualified type will always be a FunctionProtoType.
/// Otherwise, returns a NULL type.
QualType BuildFunctionType(QualType T,
MutableArrayRef<QualType> ParamTypes,
SourceLocation Loc, DeclarationName Entity,
const FunctionProtoType::ExtProtoInfo &EPI);
QualType BuildMemberPointerType(QualType T, QualType Class,
SourceLocation Loc,
DeclarationName Entity);
QualType BuildBlockPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildParenType(QualType T);
QualType BuildAtomicType(QualType T, SourceLocation Loc);
QualType BuildReadPipeType(QualType T,
SourceLocation Loc);
QualType BuildWritePipeType(QualType T,
SourceLocation Loc);
TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
/// Package the given type and TSI into a ParsedType.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
DeclarationNameInfo GetNameForDeclarator(Declarator &D);
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
static QualType GetTypeFromParser(ParsedType Ty,
TypeSourceInfo **TInfo = nullptr);
CanThrowResult canThrow(const Expr *E);
const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
const FunctionProtoType *FPT);
void UpdateExceptionSpec(FunctionDecl *FD,
const FunctionProtoType::ExceptionSpecInfo &ESI);
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
bool CheckDistantExceptionSpec(QualType T);
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
bool CheckEquivalentExceptionSpec(
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool CheckEquivalentExceptionSpec(
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
const PartialDiagnostic &NestedDiagID,
const PartialDiagnostic &NoteID,
const PartialDiagnostic &NoThrowDiagID,
const FunctionProtoType *Superset,
SourceLocation SuperLoc,
const FunctionProtoType *Subset,
SourceLocation SubLoc);
bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
const PartialDiagnostic &NoteID,
const FunctionProtoType *Target,
SourceLocation TargetLoc,
const FunctionProtoType *Source,
SourceLocation SourceLoc);
TypeResult ActOnTypeName(Scope *S, Declarator &D);
/// The parser has parsed the context-sensitive type 'instancetype'
/// in an Objective-C message declaration. Return the appropriate type.
ParsedType ActOnObjCInstanceType(SourceLocation Loc);
/// Abstract class used to diagnose incomplete types.
struct TypeDiagnoser {
TypeDiagnoser() {}
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
virtual ~TypeDiagnoser() {}
};
static int getPrintable(int I) { return I; }
static unsigned getPrintable(unsigned I) { return I; }
static bool getPrintable(bool B) { return B; }
static const char * getPrintable(const char *S) { return S; }
static StringRef getPrintable(StringRef S) { return S; }
static const std::string &getPrintable(const std::string &S) { return S; }
static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
return II;
}
static DeclarationName getPrintable(DeclarationName N) { return N; }
static QualType getPrintable(QualType T) { return T; }
static SourceRange getPrintable(SourceRange R) { return R; }
static SourceRange getPrintable(SourceLocation L) { return L; }
static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
unsigned DiagID;
std::tuple<const Ts &...> Args;
template <std::size_t... Is>
void emit(const SemaDiagnosticBuilder &DB,
llvm::index_sequence<Is...>) const {
// Apply all tuple elements to the builder in order.
bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
(void)Dummy;
}
public:
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
: TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
assert(DiagID != 0 && "no diagnostic for type diagnoser");
}
void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
emit(DB, llvm::index_sequence_for<Ts...>());
DB << T;
}
};
private:
/// Methods for marking which expressions involve dereferencing a pointer
/// marked with the 'noderef' attribute. Expressions are checked bottom up as
/// they are parsed, meaning that a noderef pointer may not be accessed. For
/// example, in `&*p` where `p` is a noderef pointer, we will first parse the
/// `*p`, but need to check that `address of` is called on it. This requires
/// keeping a container of all pending expressions and checking if the address
/// of them are eventually taken.
void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
void CheckAddressOfNoDeref(const Expr *E);
void CheckMemberAccessOfNoDeref(const MemberExpr *E);
bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
TypeDiagnoser *Diagnoser);
struct ModuleScope {
SourceLocation BeginLoc;
clang::Module *Module = nullptr;
bool ModuleInterface = false;
bool ImplicitGlobalModuleFragment = false;
VisibleModuleSet OuterVisibleModules;
};
/// The modules we're currently parsing.
llvm::SmallVector<ModuleScope, 16> ModuleScopes;
/// Namespace definitions that we will export when they finish.
llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
/// Get the module whose scope we are currently within.
Module *getCurrentModule() const {
return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
}
VisibleModuleSet VisibleModules;
public:
/// Get the module owning an entity.
Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
/// Make a merged definition of an existing hidden definition \p ND
/// visible at the specified location.
void makeMergedDefinitionVisible(NamedDecl *ND);
bool isModuleVisible(const Module *M, bool ModulePrivate = false);
/// Determine whether a declaration is visible to name lookup.
bool isVisible(const NamedDecl *D) {
return !D->isHidden() || isVisibleSlow(D);
}
/// Determine whether any declaration of an entity is visible.
bool
hasVisibleDeclaration(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
}
bool hasVisibleDeclarationSlow(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules);
bool hasVisibleMergedDefinition(NamedDecl *Def);
bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
/// Determine if \p D and \p Suggested have a structurally compatible
/// layout as described in C11 6.2.7/1.
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
/// Determine if \p D has a visible definition. If not, suggest a declaration
/// that should be made visible to expose the definition.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
bool OnlyNeedComplete = false);
bool hasVisibleDefinition(const NamedDecl *D) {
NamedDecl *Hidden;
return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
}
/// Determine if the template parameter \p D has a visible default argument.
bool
hasVisibleDefaultArgument(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if there is a visible declaration of \p D that is an explicit
/// specialization declaration for a specialization of a template. (For a
/// member specialization, use hasVisibleMemberSpecialization.)
bool hasVisibleExplicitSpecialization(
const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if there is a visible declaration of \p D that is a member
/// specialization declaration (as opposed to an instantiated declaration).
bool hasVisibleMemberSpecialization(
const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if \p A and \p B are equivalent internal linkage declarations
/// from different modules, and thus an ambiguity error can be downgraded to
/// an extension warning.
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
const NamedDecl *B);
void diagnoseEquivalentInternalLinkageDeclarations(
SourceLocation Loc, const NamedDecl *D,
ArrayRef<const NamedDecl *> Equiv);
bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
bool isCompleteType(SourceLocation Loc, QualType T) {
return !RequireCompleteTypeImpl(Loc, T, nullptr);
}
bool RequireCompleteType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireCompleteType(SourceLocation Loc, QualType T,
unsigned DiagID);
template <typename... Ts>
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteType(Loc, T, Diagnoser);
}
void completeExprArrayBound(Expr *E);
bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
bool RequireCompleteExprType(Expr *E, unsigned DiagID);
template <typename... Ts>
bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteExprType(E, Diagnoser);
}
bool RequireLiteralType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
template <typename... Ts>
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireLiteralType(Loc, T, Diagnoser);
}
QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
const CXXScopeSpec &SS, QualType T,
TagDecl *OwnedTagDecl = nullptr);
QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
/// If AsUnevaluated is false, E is treated as though it were an evaluated
/// context, such as when building a type for decltype(auto).
QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
bool AsUnevaluated = true);
QualType BuildUnaryTransformType(QualType BaseType,
UnaryTransformType::UTTKind UKind,
SourceLocation Loc);
//===--------------------------------------------------------------------===//
// Symbol table / Decl tracking callbacks: SemaDecl.cpp.
//
struct SkipBodyInfo {
SkipBodyInfo()
: ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
New(nullptr) {}
bool ShouldSkip;
bool CheckSameAsPrevious;
NamedDecl *Previous;
NamedDecl *New;
};
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
void DiagnoseUseOfUnimplementedSelectors();
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec *SS = nullptr,
bool isClassName = false, bool HasTrailingDot = false,
ParsedType ObjectType = nullptr,
bool IsCtorOrDtorName = false,
bool WantNontrivialTypeSourceInfo = false,
bool IsClassTemplateDeductionContext = true,
IdentifierInfo **CorrectedII = nullptr);
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
void DiagnoseUnknownTypeName(IdentifierInfo *&II,
SourceLocation IILoc,
Scope *S,
CXXScopeSpec *SS,
ParsedType &SuggestedType,
bool IsTemplateName = false);
/// Attempt to behave like MSVC in situations where lookup of an unqualified
/// type name has failed in a dependent context. In these situations, we
/// automatically form a DependentTypeName that will retry lookup in a related
/// scope during instantiation.
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
SourceLocation NameLoc,
bool IsTemplateTypeArg);
/// Describes the result of the name lookup and resolution performed
/// by \c ClassifyName().
enum NameClassificationKind {
NC_Unknown,
NC_Error,
NC_Keyword,
NC_Type,
NC_Expression,
NC_NestedNameSpecifier,
NC_TypeTemplate,
NC_VarTemplate,
NC_FunctionTemplate,
NC_UndeclaredTemplate,
};
class NameClassification {
NameClassificationKind Kind;
ExprResult Expr;
TemplateName Template;
ParsedType Type;
explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
public:
NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
static NameClassification Error() {
return NameClassification(NC_Error);
}
static NameClassification Unknown() {
return NameClassification(NC_Unknown);
}
static NameClassification NestedNameSpecifier() {
return NameClassification(NC_NestedNameSpecifier);
}
static NameClassification TypeTemplate(TemplateName Name) {
NameClassification Result(NC_TypeTemplate);
Result.Template = Name;
return Result;
}
static NameClassification VarTemplate(TemplateName Name) {
NameClassification Result(NC_VarTemplate);
Result.Template = Name;
return Result;
}
static NameClassification FunctionTemplate(TemplateName Name) {
NameClassification Result(NC_FunctionTemplate);
Result.Template = Name;
return Result;
}
static NameClassification UndeclaredTemplate(TemplateName Name) {
NameClassification Result(NC_UndeclaredTemplate);
Result.Template = Name;
return Result;
}
NameClassificationKind getKind() const { return Kind; }
ParsedType getType() const {
assert(Kind == NC_Type);
return Type;
}
ExprResult getExpression() const {
assert(Kind == NC_Expression);
return Expr;
}
TemplateName getTemplateName() const {
assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate);
return Template;
}
TemplateNameKind getTemplateNameKind() const {
switch (Kind) {
case NC_TypeTemplate:
return TNK_Type_template;
case NC_FunctionTemplate:
return TNK_Function_template;
case NC_VarTemplate:
return TNK_Var_template;
case NC_UndeclaredTemplate:
return TNK_Undeclared_template;
default:
llvm_unreachable("unsupported name classification.");
}
}
};
/// Perform name lookup on the given name, classifying it based on
/// the results of name lookup and the following token.
///
/// This routine is used by the parser to resolve identifiers and help direct
/// parsing. When the identifier cannot be found, this routine will attempt
/// to correct the typo and classify based on the resulting name.
///
/// \param S The scope in which we're performing name lookup.
///
/// \param SS The nested-name-specifier that precedes the name.
///
/// \param Name The identifier. If typo correction finds an alternative name,
/// this pointer parameter will be updated accordingly.
///
/// \param NameLoc The location of the identifier.
///
/// \param NextToken The token following the identifier. Used to help
/// disambiguate the name.
///
/// \param IsAddressOfOperand True if this name is the operand of a unary
/// address of ('&') expression, assuming it is classified as an
/// expression.
///
/// \param CCC The correction callback, if typo correction is desired.
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
IdentifierInfo *&Name, SourceLocation NameLoc,
const Token &NextToken,
bool IsAddressOfOperand,
CorrectionCandidateCallback *CCC = nullptr);
/// Describes the detailed kind of a template name. Used in diagnostics.
enum class TemplateNameKindForDiagnostics {
ClassTemplate,
FunctionTemplate,
VarTemplate,
AliasTemplate,
TemplateTemplateParam,
Concept,
DependentTemplate
};
TemplateNameKindForDiagnostics
getTemplateNameKindForDiagnostics(TemplateName Name);
/// Determine whether it's plausible that E was intended to be a
/// template-name.
bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
if (!getLangOpts().CPlusPlus || E.isInvalid())
return false;
Dependent = false;
if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
return !DRE->hasExplicitTemplateArgs();
if (auto *ME = dyn_cast<MemberExpr>(E.get()))
return !ME->hasExplicitTemplateArgs();
Dependent = true;
if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
return !DSDRE->hasExplicitTemplateArgs();
if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
return !DSME->hasExplicitTemplateArgs();
// Any additional cases recognized here should also be handled by
// diagnoseExprIntendedAsTemplateName.
return false;
}
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
SourceLocation Less,
SourceLocation Greater);
Decl *ActOnDeclarator(Scope *S, Declarator &D);
NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParameterLists);
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
DeclarationName Name, SourceLocation Loc,
bool IsTemplateId);
void
diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
SourceLocation FallbackLoc,
SourceLocation ConstQualLoc = SourceLocation(),
SourceLocation VolatileQualLoc = SourceLocation(),
SourceLocation RestrictQualLoc = SourceLocation(),
SourceLocation AtomicQualLoc = SourceLocation(),
SourceLocation UnalignedQualLoc = SourceLocation());
static bool adjustContextForLocalExternDecl(DeclContext *&DC);
void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
const LookupResult &R);
NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
const LookupResult &R);
void CheckShadow(Scope *S, VarDecl *D);
/// Warn if 'E', which is an expression that is about to be modified, refers
/// to a shadowing declaration.
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
private:
/// Map of current shadowing declarations to shadowed declarations. Warn if
/// it looks like the user is trying to modify the shadowing declaration.
llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
public:
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
TypedefNameDecl *NewTD);
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous);
NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
LookupResult &Previous, bool &Redeclaration);
NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope,
ArrayRef<BindingDecl *> Bindings = None);
NamedDecl *
ActOnDecompositionDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists);
// Returns true if the variable declaration is a redeclaration
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
void CheckVariableDeclarationType(VarDecl *NewVD);
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
Expr *Init);
void CheckCompleteVariableDeclaration(VarDecl *VD);
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope);
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
void FindHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
// Returns true if the function declaration is a redeclaration
bool CheckFunctionDeclaration(Scope *S,
FunctionDecl *NewFD, LookupResult &Previous,
bool IsMemberSpecialization);
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
QualType NewT, QualType OldT);
void CheckMain(FunctionDecl *FD, const DeclSpec &D);
void CheckMSVCRTEntryPoint(FunctionDecl *FD);
Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
bool IsDefinition);
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
SourceLocation Loc,
QualType T);
ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
SourceLocation NameLoc, IdentifierInfo *Name,
QualType T, TypeSourceInfo *TSInfo,
StorageClass SC);
void ActOnParamDefaultArgument(Decl *param,
SourceLocation EqualLoc,
Expr *defarg);
void ActOnParamUnparsedDefaultArgument(Decl *param,
SourceLocation EqualLoc,
SourceLocation ArgLoc);
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
SourceLocation EqualLoc);
// Contexts where using non-trivial C union types can be disallowed. This is
// passed to err_non_trivial_c_union_in_invalid_context.
enum NonTrivialCUnionContext {
// Function parameter.
NTCUC_FunctionParam,
// Function return.
NTCUC_FunctionReturn,
// Default-initialized object.
NTCUC_DefaultInitializedObject,
// Variable with automatic storage duration.
NTCUC_AutoVar,
// Initializer expression that might copy from another object.
NTCUC_CopyInit,
// Assignment.
NTCUC_Assignment,
// Compound literal.
NTCUC_CompoundLiteral,
// Block capture.
NTCUC_BlockCapture,
// lvalue-to-rvalue conversion of volatile type.
NTCUC_LValueToRValueVolatile,
};
/// Emit diagnostics if the initializer or any of its explicit or
/// implicitly-generated subexpressions require copying or
/// default-initializing a type that is or contains a C union type that is
/// non-trivial to copy or default-initialize.
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
// These flags are passed to checkNonTrivialCUnion.
enum NonTrivialCUnionKind {
NTCUK_Init = 0x1,
NTCUK_Destruct = 0x2,
NTCUK_Copy = 0x4,
};
/// Emit diagnostics if a non-trivial C union type or a struct that contains
/// a non-trivial C union is used in an invalid context.
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
NonTrivialCUnionContext UseContext,
unsigned NonTrivialKind);
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
void ActOnUninitializedDecl(Decl *dcl);
void ActOnInitializerError(Decl *Dcl);
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
void ActOnCXXForRangeDecl(Decl *D);
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
IdentifierInfo *Ident,
ParsedAttributes &Attrs,
SourceLocation AttrEnd);
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
void CheckStaticLocalForDllExport(VarDecl *VD);
void FinalizeDeclaration(Decl *D);
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
ArrayRef<Decl *> Group);
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
/// Should be called on all declarations that might have attached
/// documentation comments.
void ActOnDocumentableDecl(Decl *D);
void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
SourceLocation LocAfterDecls);
void CheckForFunctionRedefinition(
FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
SkipBodyInfo *SkipBody = nullptr);
void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
bool isObjCMethodDecl(Decl *D) {
return D && isa<ObjCMethodDecl>(D);
}
/// Determine whether we can delay parsing the body of a function or
/// function template until it is used, assuming we don't care about emitting
/// code for that function.
///
/// This will be \c false if we may need the body of the function in the
/// middle of parsing an expression (where it's impractical to switch to
/// parsing a different function), for instance, if it's constexpr in C++11
/// or has an 'auto' return type in C++14. These cases are essentially bugs.
bool canDelayFunctionBody(const Declarator &D);
/// Determine whether we can skip parsing the body of a function
/// definition, assuming we don't care about analyzing its body or emitting
/// code for that function.
///
/// This will be \c false only if we may need the body of the function in
/// order to parse the rest of the program (for instance, if it is
/// \c constexpr in C++11 or has an 'auto' return type in C++14).
bool canSkipFunctionBody(Decl *D);
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
Decl *ActOnSkippedFunctionBody(Decl *Decl);
void ActOnFinishInlineFunctionDef(FunctionDecl *D);
/// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
/// attribute for which parsing is delayed.
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
/// Diagnose any unused parameters in the given sequence of
/// ParmVarDecl pointers.
void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
/// Diagnose whether the size of parameters or return value of a
/// function or obj-c method definition is pass-by-value and larger than a
/// specified threshold.
void
DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
QualType ReturnTy, NamedDecl *D);
void DiagnoseInvalidJumps(Stmt *Body);
Decl *ActOnFileScopeAsmDecl(Expr *expr,
SourceLocation AsmLoc,
SourceLocation RParenLoc);
/// Handle a C++11 empty-declaration and attribute-declaration.
Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
SourceLocation SemiLoc);
enum class ModuleDeclKind {
Interface, ///< 'export module X;'
Implementation, ///< 'module X;'
};
/// The parser has processed a module-declaration that begins the definition
/// of a module interface or implementation.
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
SourceLocation ModuleLoc, ModuleDeclKind MDK,
ModuleIdPath Path, bool IsFirstDecl);
/// The parser has processed a global-module-fragment declaration that begins
/// the definition of the global module fragment of the current module unit.
/// \param ModuleLoc The location of the 'module' keyword.
DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
/// The parser has processed a private-module-fragment declaration that begins
/// the definition of the private module fragment of the current module unit.
/// \param ModuleLoc The location of the 'module' keyword.
/// \param PrivateLoc The location of the 'private' keyword.
DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
SourceLocation PrivateLoc);
/// The parser has processed a module import declaration.
///
/// \param StartLoc The location of the first token in the declaration. This
/// could be the location of an '@', 'export', or 'import'.
/// \param ExportLoc The location of the 'export' keyword, if any.
/// \param ImportLoc The location of the 'import' keyword.
/// \param Path The module access path.
DeclResult ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, ModuleIdPath Path);
DeclResult ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, Module *M,
ModuleIdPath Path = {});
/// The parser has processed a module import translated from a
/// #include or similar preprocessing directive.
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
/// The parsed has entered a submodule.
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
/// The parser has left a submodule.
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
/// Create an implicit import of the given module at the given
/// source location, for error recovery, if possible.
///
/// This routine is typically used when an entity found by name lookup
/// is actually hidden within a module that we know about but the user
/// has forgotten to import.
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
Module *Mod);
/// Kinds of missing import. Note, the values of these enumerators correspond
/// to %select values in diagnostics.
enum class MissingImportKind {
Declaration,
Definition,
DefaultArgument,
ExplicitSpecialization,
PartialSpecialization
};
/// Diagnose that the specified declaration needs to be visible but
/// isn't, and suggest a module import that would resolve the problem.
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
MissingImportKind MIK, bool Recover = true);
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
SourceLocation DeclLoc, ArrayRef<Module *> Modules,
MissingImportKind MIK, bool Recover);
Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
SourceLocation LBraceLoc);
Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
SourceLocation RBraceLoc);
/// We've found a use of a templated declaration that would trigger an
/// implicit instantiation. Check that any relevant explicit specializations
/// and partial specializations are visible, and diagnose if not.
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
/// We've found a use of a template specialization that would select a
/// partial specialization. Check that the partial specialization is visible,
/// and diagnose if not.
void checkPartialSpecializationVisibility(SourceLocation Loc,
NamedDecl *Spec);
/// Retrieve a suitable printing policy for diagnostics.
PrintingPolicy getPrintingPolicy() const {
return getPrintingPolicy(Context, PP);
}
/// Retrieve a suitable printing policy for diagnostics.
static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
const Preprocessor &PP);
/// Scope actions.
void ActOnPopScope(SourceLocation Loc, Scope *S);
void ActOnTranslationUnitScope(Scope *S);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
RecordDecl *&AnonRecord);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
MultiTemplateParamsArg TemplateParams,
bool IsExplicitInstantiation,
RecordDecl *&AnonRecord);
Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
AccessSpecifier AS,
RecordDecl *Record,
const PrintingPolicy &Policy);
Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
RecordDecl *Record);
/// Common ways to introduce type names without a tag for use in diagnostics.
/// Keep in sync with err_tag_reference_non_tag.
enum NonTagKind {
NTK_NonStruct,
NTK_NonClass,
NTK_NonUnion,
NTK_NonEnum,
NTK_Typedef,
NTK_TypeAlias,
NTK_Template,
NTK_TypeAliasTemplate,
NTK_TemplateTemplateArgument,
};
/// Given a non-tag type declaration, returns an enum useful for indicating
/// what kind of non-tag type this is.
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
bool isAcceptableTagRedeclaration(const TagDecl *Previous,
TagTypeKind NewTag, bool isDefinition,
SourceLocation NewTagLoc,
const IdentifierInfo *Name);
enum TagUseKind {
TUK_Reference, // Reference to a tag: 'struct foo *X;'
TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
TUK_Friend // Friend declaration: 'friend struct foo;'
};
Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc, const ParsedAttributesView &Attr,
AccessSpecifier AS, SourceLocation ModulePrivateLoc,
MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
bool &IsDependent, SourceLocation ScopedEnumKWLoc,
bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
bool IsTypeSpecifier, bool IsTemplateParamOrArg,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
unsigned TagSpec, SourceLocation TagLoc,
CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc,
const ParsedAttributesView &Attr,
MultiTemplateParamsArg TempParamLists);
TypeResult ActOnDependentTag(Scope *S,
unsigned TagSpec,
TagUseKind TUK,
const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation TagLoc,
SourceLocation NameLoc);
void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
IdentifierInfo *ClassName,
SmallVectorImpl<Decl *> &Decls);
Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth);
FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS);
MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
SourceLocation DeclStart, Declarator &D,
Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS,
const ParsedAttr &MSPropertyAttr);
FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
TypeSourceInfo *TInfo,
RecordDecl *Record, SourceLocation Loc,
bool Mutable, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
SourceLocation TSSL,
AccessSpecifier AS, NamedDecl *PrevDecl,
Declarator *D = nullptr);
bool CheckNontrivialField(FieldDecl *FD);
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
enum TrivialABIHandling {
/// The triviality of a method unaffected by "trivial_abi".
TAH_IgnoreTrivialABI,
/// The triviality of a method affected by "trivial_abi".
TAH_ConsiderTrivialABI
};
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
bool Diagnose = false);
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
void ActOnLastBitfield(SourceLocation DeclStart,
SmallVectorImpl<Decl *> &AllIvarDecls);
Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
tok::ObjCKeywordKind visibility);
// This is used for both record definitions and ObjC interface declarations.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
ArrayRef<Decl *> Fields, SourceLocation LBrac,
SourceLocation RBrac, const ParsedAttributesView &AttrList);
/// ActOnTagStartDefinition - Invoked when we have entered the
/// scope of a tag's definition (e.g., for an enumeration, class,
/// struct, or union).
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
/// Perform ODR-like check for C/ObjC when merging tag types from modules.
/// Differently from C++, actually parse the body and reject / error out
/// in case of a structural mismatch.
bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
SkipBodyInfo &SkipBody);
typedef void *SkippedDefinitionContext;
/// Invoked when we enter a tag definition that we're skipping.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
/// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
/// C++ record definition's base-specifiers clause and are starting its
/// member declarations.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
SourceLocation FinalLoc,
bool IsFinalSpelledSealed,
SourceLocation LBraceLoc);
/// ActOnTagFinishDefinition - Invoked once we have finished parsing
/// the definition of a tag (enumeration, class, struct, or union).
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
SourceRange BraceRange);
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
void ActOnObjCContainerFinishDefinition();
/// Invoked when we must temporarily exit the objective-c container
/// scope for parsing/looking-up C constructs.
///
/// Must be followed by a call to \see ActOnObjCReenterContainerContext
void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
void ActOnObjCReenterContainerContext(DeclContext *DC);
/// ActOnTagDefinitionError - Invoked when there was an unrecoverable
/// error parsing the definition of a tag.
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
EnumConstantDecl *LastEnumConst,
SourceLocation IdLoc,
IdentifierInfo *Id,
Expr *val);
bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
QualType EnumUnderlyingTy, bool IsFixed,
const EnumDecl *Prev);
/// Determine whether the body of an anonymous enumeration should be skipped.
/// \param II The name of the first enumerator.
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
SourceLocation IILoc);
Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
SourceLocation IdLoc, IdentifierInfo *Id,
const ParsedAttributesView &Attrs,
SourceLocation EqualLoc, Expr *Val);
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
const ParsedAttributesView &Attr);
DeclContext *getContainingDC(DeclContext *DC);
/// Set the current declaration context until it gets popped.
void PushDeclContext(Scope *S, DeclContext *DC);
void PopDeclContext();
/// EnterDeclaratorContext - Used when we must lookup names in the context
/// of a declarator's nested name specifier.
void EnterDeclaratorContext(Scope *S, DeclContext *DC);
void ExitDeclaratorContext(Scope *S);
/// Push the parameters of D, which must be a function, into scope.
void ActOnReenterFunctionContext(Scope* S, Decl* D);
void ActOnExitFunctionContext();
DeclContext *getFunctionLevelDeclContext();
/// getCurFunctionDecl - If inside of a function body, this returns a pointer
/// to the function decl for the function being parsed. If we're currently
/// in a 'block', this returns the containing context.
FunctionDecl *getCurFunctionDecl();
/// getCurMethodDecl - If inside of a method body, this returns a pointer to
/// the method decl for the method being parsed. If we're currently
/// in a 'block', this returns the containing context.
ObjCMethodDecl *getCurMethodDecl();
/// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
/// or C function we're in, otherwise return null. If we're currently
/// in a 'block', this returns the containing context.
NamedDecl *getCurFunctionOrMethodDecl();
/// Add this decl to the scope shadowed decl chains.
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
/// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
/// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
/// true if 'D' belongs to the given declaration context.
///
/// \param AllowInlineNamespace If \c true, allow the declaration to be in the
/// enclosing namespace set of the context, rather than contained
/// directly within it.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
bool AllowInlineNamespace = false);
/// Finds the scope corresponding to the given decl context, if it
/// happens to be an enclosing scope. Otherwise return NULL.
static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
/// Subroutines of ActOnDeclarator().
TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
TypeSourceInfo *TInfo);
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
/// Describes the kind of merge to perform for availability
/// attributes (including "deprecated", "unavailable", and "availability").
enum AvailabilityMergeKind {
/// Don't merge availability attributes at all.
AMK_None,
/// Merge availability attributes for a redeclaration, which requires
/// an exact match.
AMK_Redeclaration,
/// Merge availability attributes for an override, which requires
/// an exact match or a weakening of constraints.
AMK_Override,
/// Merge availability attributes for an implementation of
/// a protocol requirement.
AMK_ProtocolImplementation,
};
/// Describes the kind of priority given to an availability attribute.
///
/// The sum of priorities deteremines the final priority of the attribute.
/// The final priority determines how the attribute will be merged.
/// An attribute with a lower priority will always remove higher priority
/// attributes for the specified platform when it is being applied. An
/// attribute with a higher priority will not be applied if the declaration
/// already has an availability attribute with a lower priority for the
/// specified platform. The final prirority values are not expected to match
/// the values in this enumeration, but instead should be treated as a plain
/// integer value. This enumeration just names the priority weights that are
/// used to calculate that final vaue.
enum AvailabilityPriority : int {
/// The availability attribute was specified explicitly next to the
/// declaration.
AP_Explicit = 0,
/// The availability attribute was applied using '#pragma clang attribute'.
AP_PragmaClangAttribute = 1,
/// The availability attribute for a specific platform was inferred from
/// an availability attribute for another platform.
AP_InferredFromOtherPlatform = 2
};
/// Attribute merging methods. Return true if a new attribute was added.
AvailabilityAttr *mergeAvailabilityAttr(
NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit,
VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted,
bool IsUnavailable, StringRef Message, bool IsStrict,
StringRef Replacement, AvailabilityMergeKind AMK, int Priority,
unsigned AttrSpellingListIndex);
TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
TypeVisibilityAttr::VisibilityType Vis,
unsigned AttrSpellingListIndex);
VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
VisibilityAttr::VisibilityType Vis,
unsigned AttrSpellingListIndex);
UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex, StringRef Uuid);
DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
MSInheritanceAttr *
mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
unsigned AttrSpellingListIndex,
MSInheritanceAttr::Spelling SemanticSpelling);
FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
IdentifierInfo *Format, int FormatIdx,
int FirstArg, unsigned AttrSpellingListIndex);
SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
unsigned AttrSpellingListIndex);
CodeSegAttr *mergeCodeSegAttr(Decl *D, SourceRange Range, StringRef Name,
unsigned AttrSpellingListIndex);
AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
IdentifierInfo *Ident,
unsigned AttrSpellingListIndex);
MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
NoSpeculativeLoadHardeningAttr *
mergeNoSpeculativeLoadHardeningAttr(Decl *D,
const NoSpeculativeLoadHardeningAttr &AL);
SpeculativeLoadHardeningAttr *
mergeSpeculativeLoadHardeningAttr(Decl *D,
const SpeculativeLoadHardeningAttr &AL);
OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
const InternalLinkageAttr &AL);
CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
void mergeDeclAttributes(NamedDecl *New, Decl *Old,
AvailabilityMergeKind AMK = AMK_Redeclaration);
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
LookupResult &OldDecls);
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
bool MergeTypeWithOld);
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Scope *S, bool MergeTypeWithOld);
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
void MergeVarDecl(VarDecl *New, LookupResult &Previous);
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
// AssignmentAction - This is used by all the assignment diagnostic functions
// to represent what is actually causing the operation
enum AssignmentAction {
AA_Assigning,
AA_Passing,
AA_Returning,
AA_Converting,
AA_Initializing,
AA_Sending,
AA_Casting,
AA_Passing_CFAudited
};
/// C++ Overloading.
enum OverloadKind {
/// This is a legitimate overload: the existing declarations are
/// functions or function templates with different signatures.
Ovl_Overload,
/// This is not an overload because the signature exactly matches
/// an existing declaration.
Ovl_Match,
/// This is not an overload because the lookup results contain a
/// non-function.
Ovl_NonFunction
};
OverloadKind CheckOverload(Scope *S,
FunctionDecl *New,
const LookupResult &OldDecls,
NamedDecl *&OldDecl,
bool IsForUsingDecl);
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
bool ConsiderCudaAttrs = true);
ImplicitConversionSequence
TryImplicitConversion(Expr *From, QualType ToType,
bool SuppressUserConversions,
bool AllowExplicit,
bool InOverloadResolution,
bool CStyle,
bool AllowObjCWritebackConversion);
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
bool IsComplexPromotion(QualType FromType, QualType ToType);
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCWritebackConversion(QualType FromType, QualType ToType,
QualType &ConvertedType);
bool IsBlockPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType);
bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
const FunctionProtoType *NewType,
unsigned *ArgPos = nullptr);
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
QualType FromType, QualType ToType);
void maybeExtendBlockObject(ExprResult &E);
CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
bool CheckPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath& BasePath,
bool IgnoreBaseAccess,
bool Diagnose = true);
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType &ConvertedType);
bool CheckMemberPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath &BasePath,
bool IgnoreBaseAccess);
bool IsQualificationConversion(QualType FromType, QualType ToType,
bool CStyle, bool &ObjCLifetimeConversion);
bool IsFunctionConversion(QualType FromType, QualType ToType,
QualType &ResultTy);
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
const VarDecl *NRVOCandidate,
QualType ResultType,
Expr *Value,
bool AllowNRVO = true);
bool CanPerformCopyInitialization(const InitializedEntity &Entity,
ExprResult Init);
ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
SourceLocation EqualLoc,
ExprResult Init,
bool TopLevelOfInitList = false,
bool AllowExplicit = false);
ExprResult PerformObjectArgumentInitialization(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
CXXMethodDecl *Method);
/// Check that the lifetime of the initializer (and its subobjects) is
/// sufficient for initializing the entity, and perform lifetime extension
/// (when permitted) if not.
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
ExprResult PerformContextuallyConvertToBool(Expr *From);
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
/// Contexts in which a converted constant expression is required.
enum CCEKind {
CCEK_CaseValue, ///< Expression in a case label.
CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
CCEK_TemplateArg, ///< Value of a non-type template parameter.
CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
};
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
llvm::APSInt &Value, CCEKind CCE);
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
APValue &Value, CCEKind CCE);
/// Abstract base class used to perform a contextual implicit
/// conversion from an expression to any type passing a filter.
class ContextualImplicitConverter {
public:
bool Suppress;
bool SuppressConversion;
ContextualImplicitConverter(bool Suppress = false,
bool SuppressConversion = false)
: Suppress(Suppress), SuppressConversion(SuppressConversion) {}
/// Determine whether the specified type is a valid destination type
/// for this conversion.
virtual bool match(QualType T) = 0;
/// Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a diagnostic when the expression has incomplete class type.
virtual SemaDiagnosticBuilder
diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a diagnostic when the only matching conversion function
/// is explicit.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
/// Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder
noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// Emits a diagnostic when there are multiple possible conversion
/// functions.
virtual SemaDiagnosticBuilder
diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder
noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// Emits a diagnostic when we picked a conversion function
/// (for cases when we are not allowed to pick a conversion function).
virtual SemaDiagnosticBuilder diagnoseConversion(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
virtual ~ContextualImplicitConverter() {}
};
class ICEConvertDiagnoser : public ContextualImplicitConverter {
bool AllowScopedEnumerations;
public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,
bool Suppress, bool SuppressConversion)
: ContextualImplicitConverter(Suppress, SuppressConversion),
AllowScopedEnumerations(AllowScopedEnumerations) {}
/// Match an integral or (possibly scoped) enumeration type.
bool match(QualType T) override;
SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
return diagnoseNotInt(S, Loc, T);
}
/// Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
};
/// Perform a contextual implicit conversion.
ExprResult PerformContextualImplicitConversion(
SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
enum ObjCSubscriptKind {
OS_Array,
OS_Dictionary,
OS_Error
};
ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
// Note that LK_String is intentionally after the other literals, as
// this is used for diagnostics logic.
enum ObjCLiteralKind {
LK_Array,
LK_Dictionary,
LK_Numeric,
LK_Boxed,
LK_String,
LK_Block,
LK_None
};
ObjCLiteralKind CheckLiteralKind(Expr *FromE);
ExprResult PerformObjectMemberConversion(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
NamedDecl *Member);
// Members have to be NamespaceDecl* or TranslationUnitDecl*.
// TODO: make this is a typesafe union.
typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
using ADLCallKind = CallExpr::ADLCallKind;
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool AllowExplicit = true,
bool AllowExplicitConversion = false,
ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
ConversionSequenceList EarlyConversions = None);
void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool FirstArgumentIsBase = false);
void AddMethodCandidate(DeclAccessPair FoundDecl,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversion = false);
void AddMethodCandidate(CXXMethodDecl *Method,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
ConversionSequenceList EarlyConversions = None);
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddTemplateOverloadCandidate(
FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
bool PartialOverloading = false, bool AllowExplicit = true,
ADLCallKind IsADLCandidate = ADLCallKind::NotADL);
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate,
ArrayRef<QualType> ParamTypes,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
ConversionSequenceList &Conversions,
bool SuppressUserConversions,
CXXRecordDecl *ActingContext = nullptr,
QualType ObjectType = QualType(),
Expr::Classification
ObjectClassification = {});
void AddConversionCandidate(
CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
bool AllowExplicit, bool AllowResultConversion = true);
void AddTemplateConversionCandidate(
FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
bool AllowExplicit, bool AllowResultConversion = true);
void AddSurrogateCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
const FunctionProtoType *Proto,
Expr *Object, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
SourceRange OpRange = SourceRange());
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool IsAssignmentOperator = false,
unsigned NumContextualBoolArguments = 0);
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddArgumentDependentLookupCandidates(DeclarationName Name,
SourceLocation Loc,
ArrayRef<Expr *> Args,
TemplateArgumentListInfo *ExplicitTemplateArgs,
OverloadCandidateSet& CandidateSet,
bool PartialOverloading = false);
// Emit as a 'note' the specific overload candidate
void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
QualType DestType = QualType(),
bool TakingAddress = false);
// Emit as a series of 'note's all template and non-templates identified by
// the expression Expr
void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
bool TakingAddress = false);
/// Check the enable_if expressions on the given function. Returns the first
/// failing attribute, or NULL if they were all successful.
EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
bool MissingImplicitThis = false);
/// Find the failed Boolean condition within a given Boolean
/// constant expression, and describe it with a string.
std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
/// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
/// non-ArgDependent DiagnoseIfAttrs.
///
/// Argument-dependent diagnose_if attributes should be checked each time a
/// function is used as a direct callee of a function call.
///
/// Returns true if any errors were emitted.
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
const Expr *ThisArg,
ArrayRef<const Expr *> Args,
SourceLocation Loc);
/// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
/// ArgDependent DiagnoseIfAttrs.
///
/// Argument-independent diagnose_if attributes should be checked on every use
/// of a function.
///
/// Returns true if any errors were emitted.
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
SourceLocation Loc);
/// Returns whether the given function's address can be taken or not,
/// optionally emitting a diagnostic if the address can't be taken.
///
/// Returns false if taking the address of the function is illegal.
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
bool Complain = false,
SourceLocation Loc = SourceLocation());
// [PossiblyAFunctionType] --> [Return]
// NonFunctionType --> NonFunctionType
// R (A) --> R(A)
// R (*)(A) --> R (A)
// R (&)(A) --> R (A)
// R (S::*)(A) --> R (A)
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
QualType TargetType,
bool Complain,
DeclAccessPair &Found,
bool *pHadMultipleCandidates = nullptr);
FunctionDecl *
resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
DeclAccessPair &FoundResult);
bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
bool Complain = false,
DeclAccessPair *Found = nullptr);
bool ResolveAndFixSingleFunctionTemplateSpecialization(
ExprResult &SrcExpr,
bool DoFunctionPointerConverion = false,
bool Complain = false,
SourceRange OpRangeForComplaining = SourceRange(),
QualType DestTypeForComplaining = QualType(),
unsigned DiagIDForComplaining = 0);
Expr *FixOverloadedFunctionReference(Expr *E,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
ExprResult FixOverloadedFunctionReference(ExprResult,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool PartialOverloading = false);
// An enum used to represent the different possible results of building a
// range-based for loop.
enum ForRangeStatus {
FRS_Success,
FRS_NoViableFunction,
FRS_DiagnosticIssued
};
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
SourceLocation RangeLoc,
const DeclarationNameInfo &NameInfo,
LookupResult &MemberLookup,
OverloadCandidateSet *CandidateSet,
Expr *Range, ExprResult *CallExpr);
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
UnresolvedLookupExpr *ULE,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc,
Expr *ExecConfig,
bool AllowTypoCorrection=true,
bool CalleesAddressIsTaken=false);
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
MultiExprArg Args, SourceLocation RParenLoc,
OverloadCandidateSet *CandidateSet,
ExprResult *Result);
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
UnaryOperatorKind Opc,
const UnresolvedSetImpl &Fns,
Expr *input, bool RequiresADL = true);
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
BinaryOperatorKind Opc,
const UnresolvedSetImpl &Fns,
Expr *LHS, Expr *RHS,
bool RequiresADL = true);
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
SourceLocation RLoc,
Expr *Base,Expr *Idx);
ExprResult
BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult
BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
bool *NoArrowOperatorFound = nullptr);
/// CheckCallReturnType - Checks that a call expression's return type is
/// complete. Returns true on failure. The location passed in is the location
/// that best represents the call.
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
CallExpr *CE, FunctionDecl *FD);
/// Helpers for dealing with blocks and functions.
bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
bool CheckParameterNames);
void CheckCXXDefaultArguments(FunctionDecl *FD);
void CheckExtraCXXDefaultArguments(Declarator &D);
Scope *getNonFieldDeclScope(Scope *S);
/// \name Name lookup
///
/// These routines provide name lookup that is used during semantic
/// analysis to resolve the various kinds of names (identifiers,
/// overloaded operator names, constructor names, etc.) into zero or
/// more declarations within a particular scope. The major entry
/// points are LookupName, which performs unqualified name lookup,
/// and LookupQualifiedName, which performs qualified name lookup.
///
/// All name lookup is performed based on some specific criteria,
/// which specify what names will be visible to name lookup and how
/// far name lookup should work. These criteria are important both
/// for capturing language semantics (certain lookups will ignore
/// certain names, for example) and for performance, since name
/// lookup is often a bottleneck in the compilation of C++. Name
/// lookup criteria is specified via the LookupCriteria enumeration.
///
/// The results of name lookup can vary based on the kind of name
/// lookup performed, the current language, and the translation
/// unit. In C, for example, name lookup will either return nothing
/// (no entity found) or a single declaration. In C++, name lookup
/// can additionally refer to a set of overloaded functions or
/// result in an ambiguity. All of the possible results of name
/// lookup are captured by the LookupResult class, which provides
/// the ability to distinguish among them.
//@{
/// Describes the kind of name lookup to perform.
enum LookupNameKind {
/// Ordinary name lookup, which finds ordinary names (functions,
/// variables, typedefs, etc.) in C and most kinds of names
/// (functions, variables, members, types, etc.) in C++.
LookupOrdinaryName = 0,
/// Tag name lookup, which finds the names of enums, classes,
/// structs, and unions.
LookupTagName,
/// Label name lookup.
LookupLabel,
/// Member name lookup, which finds the names of
/// class/struct/union members.
LookupMemberName,
/// Look up of an operator name (e.g., operator+) for use with
/// operator overloading. This lookup is similar to ordinary name
/// lookup, but will ignore any declarations that are class members.
LookupOperatorName,
/// Look up of a name that precedes the '::' scope resolution
/// operator in C++. This lookup completely ignores operator, object,
/// function, and enumerator names (C++ [basic.lookup.qual]p1).
LookupNestedNameSpecifierName,
/// Look up a namespace name within a C++ using directive or
/// namespace alias definition, ignoring non-namespace names (C++
/// [basic.lookup.udir]p1).
LookupNamespaceName,
/// Look up all declarations in a scope with the given name,
/// including resolved using declarations. This is appropriate
/// for checking redeclarations for a using declaration.
LookupUsingDeclName,
/// Look up an ordinary name that is going to be redeclared as a
/// name with linkage. This lookup ignores any declarations that
/// are outside of the current scope unless they have linkage. See
/// C99 6.2.2p4-5 and C++ [basic.link]p6.
LookupRedeclarationWithLinkage,
/// Look up a friend of a local class. This lookup does not look
/// outside the innermost non-class scope. See C++11 [class.friend]p11.
LookupLocalFriendName,
/// Look up the name of an Objective-C protocol.
LookupObjCProtocolName,
/// Look up implicit 'self' parameter of an objective-c method.
LookupObjCImplicitSelfParam,
/// Look up the name of an OpenMP user-defined reduction operation.
LookupOMPReductionName,
/// Look up the name of an OpenMP user-defined mapper.
LookupOMPMapperName,
/// Look up any declaration with any name.
LookupAnyName
};
/// Specifies whether (or how) name lookup is being performed for a
/// redeclaration (vs. a reference).
enum RedeclarationKind {
/// The lookup is a reference to this name that is not for the
/// purpose of redeclaring the name.
NotForRedeclaration = 0,
/// The lookup results will be used for redeclaration of a name,
/// if an entity by that name already exists and is visible.
ForVisibleRedeclaration,
/// The lookup results will be used for redeclaration of a name
/// with external linkage; non-visible lookup results with external linkage
/// may also be found.
ForExternalRedeclaration
};
RedeclarationKind forRedeclarationInCurContext() {
// A declaration with an owning module for linkage can never link against
// anything that is not visible. We don't need to check linkage here; if
// the context has internal linkage, redeclaration lookup won't find things
// from other TUs, and we can't safely compute linkage yet in general.
if (cast<Decl>(CurContext)
->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
return ForVisibleRedeclaration;
return ForExternalRedeclaration;
}
/// The possible outcomes of name lookup for a literal operator.
enum LiteralOperatorLookupResult {
/// The lookup resulted in an error.
LOLR_Error,
/// The lookup found no match but no diagnostic was issued.
LOLR_ErrorNoDiagnostic,
/// The lookup found a single 'cooked' literal operator, which
/// expects a normal literal to be built and passed to it.
LOLR_Cooked,
/// The lookup found a single 'raw' literal operator, which expects
/// a string literal containing the spelling of the literal token.
LOLR_Raw,
/// The lookup found an overload set of literal operator templates,
/// which expect the characters of the spelling of the literal token to be
/// passed as a non-type template argument pack.
LOLR_Template,
/// The lookup found an overload set of literal operator templates,
/// which expect the character type and characters of the spelling of the
/// string literal token to be passed as template arguments.
LOLR_StringTemplate
};
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
CXXSpecialMember SM,
bool ConstArg,
bool VolatileArg,
bool RValueThis,
bool ConstThis,
bool VolatileThis);
typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
TypoRecoveryCallback;
private:
bool CppLookupName(LookupResult &R, Scope *S);
struct TypoExprState {
std::unique_ptr<TypoCorrectionConsumer> Consumer;
TypoDiagnosticGenerator DiagHandler;
TypoRecoveryCallback RecoveryHandler;
TypoExprState();
TypoExprState(TypoExprState &&other) noexcept;
TypoExprState &operator=(TypoExprState &&other) noexcept;
};
/// The set of unhandled TypoExprs and their associated state.
llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
/// Creates a new TypoExpr AST node.
TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC);
// The set of known/encountered (unique, canonicalized) NamespaceDecls.
//
// The boolean value will be true to indicate that the namespace was loaded
// from an AST/PCH file, or false otherwise.
llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
/// Whether we have already loaded known namespaces from an extenal
/// source.
bool LoadedExternalKnownNamespaces;
/// Helper for CorrectTypo and CorrectTypoDelayed used to create and
/// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
/// should be skipped entirely.
std::unique_ptr<TypoCorrectionConsumer>
makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
DeclContext *MemberContext, bool EnteringContext,
const ObjCObjectPointerType *OPT,
bool ErrorRecovery);
public:
const TypoExprState &getTypoExprState(TypoExpr *TE) const;
/// Clears the state of the given TypoExpr.
void clearDelayedTypo(TypoExpr *TE);
/// Look up a name, looking for a single declaration. Return
/// null if the results were absent, ambiguous, or overloaded.
///
/// It is preferable to use the elaborated form and explicitly handle
/// ambiguity and overloaded.
NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
SourceLocation Loc,
LookupNameKind NameKind,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupName(LookupResult &R, Scope *S,
bool AllowBuiltinCreation = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
bool InUnqualifiedLookup = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
CXXScopeSpec &SS);
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
bool AllowBuiltinCreation = false,
bool EnteringContext = false);
ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
QualType T1, QualType T2,
UnresolvedSetImpl &Functions);
LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
SourceLocation GnuLabelLoc = SourceLocation());
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
ArrayRef<QualType> ArgTys,
bool AllowRaw,
bool AllowTemplate,
bool AllowStringTemplate,
bool DiagnoseMissing);
bool isKnownName(StringRef name);
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
ArrayRef<Expr *> Args, ADLResult &Functions);
void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true,
bool LoadExternal = true);
void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true,
bool IncludeDependentBases = false,
bool LoadExternal = true);
enum CorrectTypoKind {
CTK_NonError, // CorrectTypo used in a non error recovery situation.
CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
};
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind,
Scope *S, CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr,
bool RecordFailure = true);
TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC, CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr);
/// Process any TypoExprs in the given Expr and its children,
/// generating diagnostics as appropriate and returning a new Expr if there
/// were typos that were all successfully corrected and ExprError if one or
/// more typos could not be corrected.
///
/// \param E The Expr to check for TypoExprs.
///
/// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
/// initializer.
///
/// \param Filter A function applied to a newly rebuilt Expr to determine if
/// it is an acceptable/usable result from a single combination of typo
/// corrections. As long as the filter returns ExprError, different
/// combinations of corrections will be tried until all are exhausted.
ExprResult
CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; });
ExprResult
CorrectDelayedTyposInExpr(Expr *E,
llvm::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(E, nullptr, Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; }) {
return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER,
llvm::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
}
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
bool ErrorRecovery = true);
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
const PartialDiagnostic &PrevNote,
bool ErrorRecovery = true);
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
ArrayRef<Expr *> Args,
AssociatedNamespaceSet &AssociatedNamespaces,
AssociatedClassSet &AssociatedClasses);
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
bool ConsiderLinkage, bool AllowInlineNamespace);
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
void DiagnoseAmbiguousLookup(LookupResult &Result);
//@}
ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
SourceLocation IdLoc,
bool TypoCorrection = false);
NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
Scope *S, bool ForRedeclaration,
SourceLocation Loc);
NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
Scope *S);
void AddKnownFunctionAttributes(FunctionDecl *FD);
// More parsing and symbol table subroutines.
void ProcessPragmaWeak(Scope *S, Decl *D);
// Decl attributes - this routine is the top level dispatcher.
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
// Helper for delayed processing of attributes.
void ProcessDeclAttributeDelayed(Decl *D,
const ParsedAttributesView &AttrList);
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
bool IncludeCXX11Attributes = true);
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
const ParsedAttributesView &AttrList);
void checkUnusedDeclAttributes(Declarator &D);
/// Determine if type T is a valid subject for a nonnull and similar
/// attributes. By default, we look through references (the behavior used by
/// nonnull), but if the second parameter is true, then we treat a reference
/// type as valid.
bool isValidPointerAttrType(QualType T, bool RefOkay = false);
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
const FunctionDecl *FD = nullptr);
bool CheckAttrTarget(const ParsedAttr &CurrAttr);
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
StringRef &Str,
SourceLocation *ArgLocation = nullptr);
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
bool checkMSInheritanceAttrOnDefinition(
CXXRecordDecl *RD, SourceRange Range, bool BestCase,
MSInheritanceAttr::Spelling SemanticSpelling);
void CheckAlignasUnderalignment(Decl *D);
/// Adjust the calling convention of a method to be the ABI default if it
/// wasn't specified explicitly. This handles method types formed from
/// function type typedefs and typename template arguments.
void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
SourceLocation Loc);
// Check if there is an explicit attribute, but only look through parens.
// The intent is to look for an attribute on the current declarator, but not
// one that came from a typedef.
bool hasExplicitCallingConv(QualType T);
/// Get the outermost AttributedType node that sets a calling convention.
/// Valid types should not have multiple attributes with different CCs.
const AttributedType *getCallingConvAttributedType(QualType T) const;
/// Stmt attributes - this routine is the top level dispatcher.
StmtResult ProcessStmtAttributes(Stmt *Stmt,
const ParsedAttributesView &Attrs,
SourceRange Range);
void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
ObjCMethodDecl *Overridden,
bool IsProtocolMethodDecl);
/// WarnExactTypedMethods - This routine issues a warning if method
/// implementation declaration matches exactly that of its declaration.
void WarnExactTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
/// CheckImplementationIvars - This routine checks if the instance variables
/// listed in the implelementation match those listed in the interface.
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
ObjCIvarDecl **Fields, unsigned nIvars,
SourceLocation Loc);
/// ImplMethodsVsClassMethods - This is main routine to warn if any method
/// remains unimplemented in the class or category \@implementation.
void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool IncompleteImpl = false);
/// DiagnoseUnimplementedProperties - This routine warns on those properties
/// which must be implemented by this implementation.
void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl *CDecl,
bool SynthesizeProperties);
/// Diagnose any null-resettable synthesized setters.
void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
/// DefaultSynthesizeProperties - This routine default synthesizes all
/// properties which must be synthesized in the class's \@implementation.
void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
ObjCInterfaceDecl *IDecl,
SourceLocation AtEnd);
void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
/// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
/// an ivar synthesized for 'Method' and 'Method' is a property accessor
/// declared in class 'IFace'.
bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
ObjCMethodDecl *Method, ObjCIvarDecl *IV);
/// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
/// backs the property is not used in the property's accessor.
void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
const ObjCImplementationDecl *ImplD);
/// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
/// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
/// It also returns ivar's property on success.
ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
const ObjCPropertyDecl *&PDecl) const;
/// Called by ActOnProperty to handle \@property declarations in
/// class extensions.
ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
SourceLocation GetterNameLoc,
Selector SetterSel,
SourceLocation SetterNameLoc,
const bool isReadWrite,
unsigned &Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind);
/// Called by ActOnProperty and HandlePropertyInClassExtension to
/// handle creating the ObjcPropertyDecl for a category or \@interface.
ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
ObjCContainerDecl *CDecl,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
SourceLocation GetterNameLoc,
Selector SetterSel,
SourceLocation SetterNameLoc,
const bool isReadWrite,
const unsigned Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
/// AtomicPropertySetterGetterRules - This routine enforces the rule (via
/// warning) when atomic property has one but not the other user-declared
/// setter or getter.
void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
ObjCInterfaceDecl* IDecl);
void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
void DiagnoseMissingDesignatedInitOverrides(
const ObjCImplementationDecl *ImplD,
const ObjCInterfaceDecl *IFD);
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
enum MethodMatchStrategy {
MMS_loose,
MMS_strict
};
/// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
/// true, or false, accordingly.
bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
const ObjCMethodDecl *PrevMethod,
MethodMatchStrategy strategy = MMS_strict);
/// MatchAllMethodDeclarations - Check methods declaraed in interface or
/// or protocol against those declared in their implementations.
void MatchAllMethodDeclarations(const SelectorSet &InsMap,
const SelectorSet &ClsMap,
SelectorSet &InsMapSeen,
SelectorSet &ClsMapSeen,
ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool &IncompleteImpl,
bool ImmediateClass,
bool WarnCategoryMethodImpl=false);
/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
/// category matches with those implemented in its primary class and
/// warns each time an exact match is found.
void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
/// Add the given method to the list of globally-known methods.
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
private:
/// AddMethodToGlobalPool - Add an instance or factory method to the global
/// pool. See descriptoin of AddInstanceMethodToGlobalPool.
void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
/// LookupMethodInGlobalPool - Returns the instance or factory method and
/// optionally warns if there are multiple signatures.
ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass,
bool instance);
public:
/// - Returns instance or factory methods in global method pool for
/// given selector. It checks the desired kind first, if none is found, and
/// parameter checkTheOther is set, it then checks the other kind. If no such
/// method or only one method is found, function returns false; otherwise, it
/// returns true.
bool
CollectMultipleMethodsInGlobalPool(Selector Sel,
SmallVectorImpl<ObjCMethodDecl*>& Methods,
bool InstanceFirst, bool CheckTheOther,
const ObjCObjectType *TypeBound = nullptr);
bool
AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
SourceRange R, bool receiverIdOrClass,
SmallVectorImpl<ObjCMethodDecl*>& Methods);
void
DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
Selector Sel, SourceRange R,
bool receiverIdOrClass);
private:
/// - Returns a selector which best matches given argument list or
/// nullptr if none could be found
ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
bool IsInstance,
SmallVectorImpl<ObjCMethodDecl*>& Methods);
/// Record the typo correction failure and return an empty correction.
TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
bool RecordFailure = true) {
if (RecordFailure)
TypoCorrectionFailures[Typo].insert(TypoLoc);
return TypoCorrection();
}
public:
/// AddInstanceMethodToGlobalPool - All instance methods in a translation
/// unit are added to a global pool. This allows us to efficiently associate
/// a selector with a method declaraation for purposes of typechecking
/// messages sent to "id" (where the class of the object is unknown).
void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/true);
}
/// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/false);
}
/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
/// pool.
void AddAnyMethodToGlobalPool(Decl *D);
/// LookupInstanceMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/true);
}
/// LookupFactoryMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/false);
}
const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
QualType ObjectType=QualType());
/// LookupImplementedMethodInGlobalPool - Returns the method which has an
/// implementation.
ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
/// initialization.
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
SmallVectorImpl<ObjCIvarDecl*> &Ivars);
//===--------------------------------------------------------------------===//
// Statement Parsing Callbacks: SemaStmt.cpp.
public:
class FullExprArg {
public:
FullExprArg() : E(nullptr) { }
FullExprArg(Sema &actions) : E(nullptr) { }
ExprResult release() {
return E;
}
Expr *get() const { return E; }
Expr *operator->() {
return E;
}
private:
// FIXME: No need to make the entire Sema class a friend when it's just
// Sema::MakeFullExpr that needs access to the constructor below.
friend class Sema;
explicit FullExprArg(Expr *expr) : E(expr) {}
Expr *E;
};
FullExprArg MakeFullExpr(Expr *Arg) {
return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
}
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
return FullExprArg(
ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
}
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
ExprResult FE =
ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
/*DiscardedValue*/ true);
return FullExprArg(FE.get());
}
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
StmtResult ActOnExprStmtError();
StmtResult ActOnNullStmt(SourceLocation SemiLoc,
bool HasLeadingEmptyMacro = false);
void ActOnStartOfCompoundStmt(bool IsStmtExpr);
void ActOnFinishOfCompoundStmt();
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
ArrayRef<Stmt *> Elts, bool isStmtExpr);
/// A RAII object to enter scope of a compound statement.
class CompoundScopeRAII {
public:
CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
S.ActOnStartOfCompoundStmt(IsStmtExpr);
}
~CompoundScopeRAII() {
S.ActOnFinishOfCompoundStmt();
}
private:
Sema &S;
};
/// An RAII helper that pops function a function scope on exit.
struct FunctionScopeRAII {
Sema &S;
bool Active;
FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAII() {
if (Active)
S.PopFunctionScopeInfo();
}
void disable() { Active = false; }
};
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
StmtResult ActOnForEachLValueExpr(Expr *E);
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
SourceLocation DotDotDotLoc, ExprResult RHS,
SourceLocation ColonLoc);
void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
SourceLocation ColonLoc,
Stmt *SubStmt, Scope *CurScope);
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
SourceLocation ColonLoc, Stmt *SubStmt);
StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
ArrayRef<const Attr*> Attrs,
Stmt *SubStmt);
class ConditionResult;
StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Stmt *InitStmt,
ConditionResult Cond, Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Stmt *InitStmt,
ConditionResult Cond, Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
Stmt *InitStmt,
ConditionResult Cond);
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
Stmt *Switch, Stmt *Body);
StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
Stmt *Body);
StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
SourceLocation WhileLoc, SourceLocation CondLParen,
Expr *Cond, SourceLocation CondRParen);
StmtResult ActOnForStmt(SourceLocation ForLoc,
SourceLocation LParenLoc,
Stmt *First,
ConditionResult Second,
FullExprArg Third,
SourceLocation RParenLoc,
Stmt *Body);
ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
Expr *collection);
StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
Stmt *First, Expr *collection,
SourceLocation RParenLoc);
StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
enum BuildForRangeKind {
/// Initial building of a for-range statement.
BFRK_Build,
/// Instantiation or recovery rebuild of a for-range statement. Don't
/// attempt any typo-correction.
BFRK_Rebuild,
/// Determining whether a for-range statement could be built. Avoid any
/// unnecessary or irreversible actions.
BFRK_Check
};
StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
SourceLocation CoawaitLoc,
Stmt *InitStmt,
Stmt *LoopVar,
SourceLocation ColonLoc, Expr *Collection,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
SourceLocation CoawaitLoc,
Stmt *InitStmt,
SourceLocation ColonLoc,
Stmt *RangeDecl, Stmt *Begin, Stmt *End,
Expr *Cond, Expr *Inc,
Stmt *LoopVarDecl,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
SourceLocation LabelLoc,
LabelDecl *TheDecl);
StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
SourceLocation StarLoc,
Expr *DestExp);
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind, unsigned NumParams);
typedef std::pair<StringRef, QualType> CapturedParamNameType;
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind,
ArrayRef<CapturedParamNameType> Params);
StmtResult ActOnCapturedRegionEnd(Stmt *S);
void ActOnCapturedRegionError();
RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
SourceLocation Loc,
unsigned NumParams);
enum CopyElisionSemanticsKind {
CES_Strict = 0,
CES_AllowParameters = 1,
CES_AllowDifferentTypes = 2,
CES_AllowExceptionVariables = 4,
CES_FormerDefault = (CES_AllowParameters),
CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
CES_AllowExceptionVariables),
};
VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
CopyElisionSemanticsKind CESK);
bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
CopyElisionSemanticsKind CESK);
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
Scope *CurScope);
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
bool IsVolatile, unsigned NumOutputs,
unsigned NumInputs, IdentifierInfo **Names,
MultiExprArg Constraints, MultiExprArg Exprs,
Expr *AsmString, MultiExprArg Clobbers,
unsigned NumLabels,
SourceLocation RParenLoc);
void FillInlineAsmIdentifierInfo(Expr *Res,
llvm::InlineAsmIdentifierInfo &Info);
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Id,
bool IsUnevaluatedContext);
bool LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset, SourceLocation AsmLoc);
ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
SourceLocation AsmLoc);
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
ArrayRef<Token> AsmToks,
StringRef AsmString,
unsigned NumOutputs, unsigned NumInputs,
ArrayRef<StringRef> Constraints,
ArrayRef<StringRef> Clobbers,
ArrayRef<Expr*> Exprs,
SourceLocation EndLoc);
LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
SourceLocation Location,
bool AlwaysCreate);
VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
bool Invalid = false);
Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
Decl *Parm, Stmt *Body);
StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
MultiStmtArg Catch, Stmt *Finally);
StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Scope *CurScope);
ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
Expr *operand);
StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
Expr *SynchExpr,
Stmt *SynchBody);
StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
SourceLocation StartLoc,
SourceLocation IdLoc,
IdentifierInfo *Id);
Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
Decl *ExDecl, Stmt *HandlerBlock);
StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
ArrayRef<Stmt *> Handlers);
StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
SourceLocation TryLoc, Stmt *TryBlock,
Stmt *Handler);
StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
Expr *FilterExpr,
Stmt *Block);
void ActOnStartSEHFinallyBlock();
void ActOnAbortSEHFinallyBlock();
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
/// If it's a file scoped decl that must warn if not used, keep track
/// of it.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
/// DiagnoseUnusedExprResult - If the statement passed in is an expression
/// whose result is unused, warn.
void DiagnoseUnusedExprResult(const Stmt *S);
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
void DiagnoseUnusedDecl(const NamedDecl *ND);
/// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
/// statement as a \p Body, and it is located on the same line.
///
/// This helps prevent bugs due to typos, such as:
/// if (condition);
/// do_stuff();
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
const Stmt *Body,
unsigned DiagID);
/// Warn if a for/while loop statement \p S, which is followed by
/// \p PossibleBody, has a suspicious null statement as a body.
void DiagnoseEmptyLoopBody(const Stmt *S,
const Stmt *PossibleBody);
/// Warn if a value is moved to itself.
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
SourceLocation OpLoc);
/// Warn if we're implicitly casting from a _Nullable pointer type to a
/// _Nonnull one.
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
SourceLocation Loc);
/// Warn when implicitly casting 0 to nullptr.
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
return DelayedDiagnostics.push(pool);
}
void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
typedef ProcessingContextState ParsingClassState;
ParsingClassState PushParsingClass() {
return DelayedDiagnostics.pushUndelayed();
}
void PopParsingClass(ParsingClassState state) {
DelayedDiagnostics.popUndelayed(state);
}
void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
const ObjCInterfaceDecl *UnknownObjCClass,
bool ObjCPropertyAccess,
bool AvoidPartialAvailabilityChecks = false,
ObjCInterfaceDecl *ClassReceiver = nullptr);
bool makeUnavailableInSystemHeader(SourceLocation loc,
UnavailableAttr::ImplicitReason reason);
/// Issue any -Wunguarded-availability warnings in \c FD
void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
//===--------------------------------------------------------------------===//
// Expression Parsing Callbacks: SemaExpr.cpp.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
bool ObjCPropertyAccess = false,
bool AvoidPartialAvailabilityChecks = false,
ObjCInterfaceDecl *ClassReciever = nullptr);
void NoteDeletedFunction(FunctionDecl *FD);
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
ObjCMethodDecl *Getter,
SourceLocation Loc);
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
ArrayRef<Expr *> Args);
void PushExpressionEvaluationContext(
ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
ExpressionEvaluationContextRecord::ExpressionKind Type =
ExpressionEvaluationContextRecord::EK_Other);
enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
void PushExpressionEvaluationContext(
ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
ExpressionEvaluationContextRecord::ExpressionKind Type =
ExpressionEvaluationContextRecord::EK_Other);
void PopExpressionEvaluationContext();
void DiscardCleanupsInEvaluationContext();
ExprResult TransformToPotentiallyEvaluated(Expr *E);
ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
ExprResult ActOnConstantExpression(ExprResult Res);
// Functions for marking a declaration referenced. These functions also
// contain the relevant logic for marking if a reference to a function or
// variable is an odr-use (in the C++11 sense). There are separate variants
// for expressions referring to a decl; these exist because odr-use marking
// needs to be delayed for some constant variables when we build one of the
// named expressions.
//
// MightBeOdrUse indicates whether the use could possibly be an odr-use, and
// should usually be true. This only needs to be set to false if the lack of
// odr-use cannot be determined from the current context (for instance,
// because the name denotes a virtual function and was written without an
// explicit nested-name-specifier).
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
bool MightBeOdrUse = true);
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
void MarkMemberReferenced(MemberExpr *E);
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
unsigned CapturingScopeIndex);
ExprResult CheckLValueToRValueConversionOperand(Expr *E);
void CleanupVarDeclMarking();
enum TryCaptureKind {
TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
};
/// Try to capture the given variable.
///
/// \param Var The variable to capture.
///
/// \param Loc The location at which the capture occurs.
///
/// \param Kind The kind of capture, which may be implicit (for either a
/// block or a lambda), or explicit by-value or by-reference (for a lambda).
///
/// \param EllipsisLoc The location of the ellipsis, if one is provided in
/// an explicit lambda capture.
///
/// \param BuildAndDiagnose Whether we are actually supposed to add the
/// captures or diagnose errors. If false, this routine merely check whether
/// the capture can occur without performing the capture itself or complaining
/// if the variable cannot be captured.
///
/// \param CaptureType Will be set to the type of the field used to capture
/// this variable in the innermost block or lambda. Only valid when the
/// variable can be captured.
///
/// \param DeclRefType Will be set to the type of a reference to the capture
/// from within the current scope. Only valid when the variable can be
/// captured.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// variables that may or may not be used in certain specializations of
/// a nested generic lambda.
///
/// \returns true if an error occurred (i.e., the variable cannot be
/// captured) and false if the capture succeeded.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
SourceLocation EllipsisLoc, bool BuildAndDiagnose,
QualType &CaptureType,
QualType &DeclRefType,
const unsigned *const FunctionScopeIndexToStopAt);
/// Try to capture the given variable.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
TryCaptureKind Kind = TryCapture_Implicit,
SourceLocation EllipsisLoc = SourceLocation());
/// Checks if the variable must be captured.
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
/// Given a variable, determine the type that a reference to that
/// variable will have in the given scope.
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
/// Mark all of the declarations referenced within a particular AST node as
/// referenced. Used when template instantiation instantiates a non-dependent
/// type -- entities referenced by the type are now referenced.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
void MarkDeclarationsReferencedInExpr(Expr *E,
bool SkipLocalVariables = false);
/// Try to recover by turning the given expression into a
/// call. Returns true if recovery was attempted or an error was
/// emitted; this may also leave the ExprResult invalid.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
bool ForceComplain = false,
bool (*IsPlausibleResult)(QualType) = nullptr);
/// Figure out if an expression could be turned into a call.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
UnresolvedSetImpl &NonTemplateOverloads);
/// Conditionally issue a diagnostic based on the current
/// evaluation context.
///
/// \param Statement If Statement is non-null, delay reporting the
/// diagnostic until the function body is parsed, and then do a basic
/// reachability analysis to determine if the statement is reachable.
/// If it is unreachable, the diagnostic will not be emitted.
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
const PartialDiagnostic &PD);
/// Similar, but diagnostic is only produced if all the specified statements
/// are reachable.
bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
const PartialDiagnostic &PD);
// Primary Expressions.
SourceRange getExprRange(Expr *E) const;
ExprResult ActOnIdExpression(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
CorrectionCandidateCallback *CCC = nullptr,
bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
void DecomposeUnqualifiedId(const UnqualifiedId &Id,
TemplateArgumentListInfo &Buffer,
DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *&TemplateArgs);
bool
DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
CorrectionCandidateCallback &CCC,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
IdentifierInfo *II,
bool AllowBuiltinCreation=false);
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
bool isAddressOfOperand,
const TemplateArgumentListInfo *TemplateArgs);
/// If \p D cannot be odr-used in the current expression evaluation context,
/// return a reason explaining why. Otherwise, return NOUR_None.
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
SourceLocation Loc,
const CXXScopeSpec *SS = nullptr);
DeclRefExpr *
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
const CXXScopeSpec *SS = nullptr,
NamedDecl *FoundD = nullptr,
SourceLocation TemplateKWLoc = SourceLocation(),
const TemplateArgumentListInfo *TemplateArgs = nullptr);
DeclRefExpr *
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
NestedNameSpecifierLoc NNS,
NamedDecl *FoundD = nullptr,
SourceLocation TemplateKWLoc = SourceLocation(),
const TemplateArgumentListInfo *TemplateArgs = nullptr);
ExprResult
BuildAnonymousStructUnionMemberReference(
const CXXScopeSpec &SS,
SourceLocation nameLoc,
IndirectFieldDecl *indirectField,
DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
Expr *baseObjectExpr = nullptr,
SourceLocation opLoc = SourceLocation());
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S);
ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
bool IsDefiniteInstance,
const Scope *S);
bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
const LookupResult &R,
bool HasTrailingLParen);
ExprResult
BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
bool IsAddressOfOperand, const Scope *S,
TypeSourceInfo **RecoveryTSI = nullptr);
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
LookupResult &R,
bool NeedsADL,
bool AcceptInvalidDecl = false);
ExprResult BuildDeclarationNameExpr(
const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
NamedDecl *FoundD = nullptr,
const TemplateArgumentListInfo *TemplateArgs = nullptr,
bool AcceptInvalidDecl = false);
ExprResult BuildLiteralOperatorCall(LookupResult &R,
DeclarationNameInfo &SuffixInfo,
ArrayRef<Expr *> Args,
SourceLocation LitEndLoc,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
ExprResult BuildPredefinedExpr(SourceLocation Loc,
PredefinedExpr::IdentKind IK);
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
ExprResult BuildUniqueStableName(SourceLocation OpLoc,
TypeSourceInfo *Operand);
ExprResult BuildUniqueStableName(SourceLocation OpLoc, Expr *E);
ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation L,
SourceLocation R, ParsedType Ty);
ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation L,
SourceLocation R, Expr *Operand);
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
ExprResult ActOnCharacterConstant(const Token &Tok,
Scope *UDLScope = nullptr);
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
ExprResult ActOnParenListExpr(SourceLocation L,
SourceLocation R,
MultiExprArg Val);
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
/// fragments (e.g. "foo" "bar" L"baz").
ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
Scope *UDLScope = nullptr);
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<ParsedType> ArgTypes,
ArrayRef<Expr *> ArgExprs);
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<TypeSourceInfo *> Types,
ArrayRef<Expr *> Exprs);
// Binary/Unary Operators. 'Tok' is the token for the operator.
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
Expr *InputExpr);
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opc, Expr *Input);
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Op, Expr *Input);
bool isQualifiedMemberAccess(Expr *E);
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
SourceRange R);
ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind);
ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
bool IsType, void *TyOrEx,
SourceRange ArgRange);
ExprResult CheckPlaceholderExpr(Expr *E);
bool CheckVecStepExpr(Expr *E);
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
SourceRange ExprRange,
UnaryExprOrTypeTrait ExprKind);
ExprResult ActOnSizeofParameterPackExpr(Scope *S,
SourceLocation OpLoc,
IdentifierInfo &Name,
SourceLocation NameLoc,
SourceLocation RParenLoc);
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Kind, Expr *Input);
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
Expr *LowerBound, SourceLocation ColonLoc,
Expr *Length, SourceLocation RBLoc);
// This struct is for use by ActOnMemberAccess to allow
// BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
// changing the access operator from a '.' to a '->' (to see if that is the
// change needed to fix an error about an unknown member, e.g. when the class
// defines a custom operator->).
struct ActOnMemberAccessExtraArgs {
Scope *S;
UnqualifiedId &Id;
Decl *ObjCImpDecl;
};
ExprResult BuildMemberReferenceExpr(
Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult
BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
bool IsArrow, const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S,
bool SuppressQualifierCheck = false,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
SourceLocation OpLoc,
const CXXScopeSpec &SS, FieldDecl *Field,
DeclAccessPair FoundDecl,
const DeclarationNameInfo &MemberNameInfo);
ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
const CXXScopeSpec &SS,
const LookupResult &R);
ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Member,
Decl *ObjCImpDecl);
MemberExpr *
BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
ValueDecl *Member, DeclAccessPair FoundDecl,
bool HadMultipleCandidates,
const DeclarationNameInfo &MemberNameInfo, QualType Ty,
ExprValueKind VK, ExprObjectKind OK,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
MemberExpr *
BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
ValueDecl *Member, DeclAccessPair FoundDecl,
bool HadMultipleCandidates,
const DeclarationNameInfo &MemberNameInfo, QualType Ty,
ExprValueKind VK, ExprObjectKind OK,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
FunctionDecl *FDecl,
const FunctionProtoType *Proto,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
bool ExecConfig = false);
void CheckStaticArrayArgument(SourceLocation CallLoc,
ParmVarDecl *Param,
const Expr *ArgExpr);
/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
/// This provides the location of the left/right parens and a list of comma
/// locations.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr);
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr,
bool IsExecConfig = false);
ExprResult
BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
Expr *Config = nullptr, bool IsExecConfig = false,
ADLCallKind UsesADL = ADLCallKind::NotADL);
ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
MultiExprArg ExecConfig,
SourceLocation GGGLoc);
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
Declarator &D, ParsedType &Ty,
SourceLocation RParenLoc, Expr *CastExpr);
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
TypeSourceInfo *Ty,
SourceLocation RParenLoc,
Expr *Op);
CastKind PrepareScalarCast(ExprResult &src, QualType destType);
/// Build an altivec or OpenCL literal.
ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
SourceLocation RParenLoc, Expr *E,
TypeSourceInfo *TInfo);
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc,
Expr *InitExpr);
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
TypeSourceInfo *TInfo,
SourceLocation RParenLoc,
Expr *LiteralExpr);
ExprResult ActOnInitList(SourceLocation LBraceLoc,
MultiExprArg InitArgList,
SourceLocation RBraceLoc);
ExprResult ActOnDesignatedInitializer(Designation &Desig,
SourceLocation Loc,
bool GNUSyntax,
ExprResult Init);
private:
static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
public:
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
Expr *LHSExpr, Expr *RHSExpr);
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
/// in the case of a the GNU conditional expr extension.
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
SourceLocation ColonLoc,
Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
LabelDecl *TheDecl);
void ActOnStartStmtExpr();
ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
SourceLocation RPLoc); // "({..})"
// Handle the final expression in a statement expression.
ExprResult ActOnStmtExprResult(ExprResult E);
void ActOnStmtExprError();
// __builtin_offsetof(type, identifier(.identifier|[expr])*)
struct OffsetOfComponent {
SourceLocation LocStart, LocEnd;
bool isBrackets; // true if [expr], false if .ident
union {
IdentifierInfo *IdentInfo;
Expr *E;
} U;
};
/// __builtin_offsetof(type, a.b[123][456].c)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
TypeSourceInfo *TInfo,
ArrayRef<OffsetOfComponent> Components,
SourceLocation RParenLoc);
ExprResult ActOnBuiltinOffsetOf(Scope *S,
SourceLocation BuiltinLoc,
SourceLocation TypeLoc,
ParsedType ParsedArgTy,
ArrayRef<OffsetOfComponent> Components,
SourceLocation RParenLoc);
// __builtin_choose_expr(constExpr, expr1, expr2)
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
Expr *CondExpr, Expr *LHSExpr,
Expr *RHSExpr, SourceLocation RPLoc);
// __builtin_va_arg(expr, type)
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
SourceLocation RPLoc);
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
TypeSourceInfo *TInfo, SourceLocation RPLoc);
// __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
// __builtin_COLUMN()
ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
SourceLocation BuiltinLoc,
SourceLocation RPLoc);
// Build a potentially resolved SourceLocExpr.
ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
SourceLocation BuiltinLoc, SourceLocation RPLoc,
DeclContext *ParentContext);
// __null
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
bool CheckCaseExpression(Expr *E);
/// Describes the result of an "if-exists" condition check.
enum IfExistsResult {
/// The symbol exists.
IER_Exists,
/// The symbol does not exist.
IER_DoesNotExist,
/// The name is a dependent name, so the results will differ
/// from one instantiation to the next.
IER_Dependent,
/// An error occurred.
IER_Error
};
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
const DeclarationNameInfo &TargetNameInfo);
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
bool IsIfExists, CXXScopeSpec &SS,
UnqualifiedId &Name);
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
NestedNameSpecifierLoc QualifierLoc,
DeclarationNameInfo NameInfo,
Stmt *Nested);
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
CXXScopeSpec &SS, UnqualifiedId &Name,
Stmt *Nested);
//===------------------------- "Block" Extension ------------------------===//
/// ActOnBlockStart - This callback is invoked when a block literal is
/// started.
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockArguments - This callback allows processing of block arguments.
/// If there are no arguments, this is still invoked.
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
Scope *CurScope);
/// ActOnBlockError - If there is an error parsing a block, this callback
/// is invoked to pop the information about the block from the action impl.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockStmtExpr - This is called when the body of a block statement
/// literal was successfully completed. ^(int x){...}
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
Scope *CurScope);
//===---------------------------- Clang Extensions ----------------------===//
/// __builtin_convertvector(...)
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- OpenCL Features -----------------------===//
/// __builtin_astype(...)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- C++ Features --------------------------===//
// Act on C++ namespaces
Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
SourceLocation NamespaceLoc,
SourceLocation IdentLoc, IdentifierInfo *Ident,
SourceLocation LBrace,
const ParsedAttributesView &AttrList,
UsingDirectiveDecl *&UsingDecl);
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
NamespaceDecl *getStdNamespace() const;
NamespaceDecl *getOrCreateStdNamespace();
NamespaceDecl *lookupStdExperimentalNamespace();
CXXRecordDecl *getStdBadAlloc() const;
EnumDecl *getStdAlignValT() const;
private:
// A cache representing if we've fully checked the various comparison category
// types stored in ASTContext. The bit-index corresponds to the integer value
// of a ComparisonCategoryType enumerator.
llvm::SmallBitVector FullyCheckedComparisonCategories;
ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
CXXScopeSpec &SS,
ParsedType TemplateTypeTy,
IdentifierInfo *MemberOrBase);
public:
/// Lookup the specified comparison category types in the standard
/// library, an check the VarDecls possibly returned by the operator<=>
/// builtins for that type.
///
/// \return The type of the comparison category type corresponding to the
/// specified Kind, or a null type if an error occurs
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
SourceLocation Loc);
/// Tests whether Ty is an instance of std::initializer_list and, if
/// it is and Element is not NULL, assigns the element type to Element.
bool isStdInitializerList(QualType Ty, QualType *Element);
/// Looks for the std::initializer_list template and instantiates it
/// with Element, or emits an error if it's not found.
///
/// \returns The instantiated template, or null on error.
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
/// Determine whether Ctor is an initializer-list constructor, as
/// defined in [dcl.init.list]p2.
bool isInitListConstructor(const FunctionDecl *Ctor);
Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
SourceLocation NamespcLoc, CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *NamespcName,
const ParsedAttributesView &AttrList);
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
Decl *ActOnNamespaceAliasDef(Scope *CurScope,
SourceLocation NamespaceLoc,
SourceLocation AliasLoc,
IdentifierInfo *Alias,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *Ident);
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
const LookupResult &PreviousDecls,
UsingShadowDecl *&PrevShadow);
UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
NamedDecl *Target,
UsingShadowDecl *PrevDecl);
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
bool HasTypenameKeyword,
const CXXScopeSpec &SS,
SourceLocation NameLoc,
const LookupResult &Previous);
bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
bool HasTypename,
const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
SourceLocation NameLoc);
NamedDecl *BuildUsingDeclaration(
Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList, bool IsInstantiation);
NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
ArrayRef<NamedDecl *> Expansions);
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
/// Given a derived-class using shadow declaration for a constructor and the
/// correspnding base class constructor, find or create the implicit
/// synthesized derived class constructor to use for this initialization.
CXXConstructorDecl *
findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
ConstructorUsingShadowDecl *DerivedShadow);
Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
SourceLocation UsingLoc,
SourceLocation TypenameLoc, CXXScopeSpec &SS,
UnqualifiedId &Name, SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
MultiTemplateParamsArg TemplateParams,
SourceLocation UsingLoc, UnqualifiedId &Name,
const ParsedAttributesView &AttrList,
TypeResult Type, Decl *DeclFromDeclSpec);
/// BuildCXXConstructExpr - Creates a complete call to a constructor,
/// including handling of its default argument expressions.
///
/// \param ConstructKind - a CXXConstructExpr::ConstructionKind
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
NamedDecl *FoundDecl,
CXXConstructorDecl *Constructor, MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
/// Build a CXXConstructExpr whose constructor has already been resolved if
/// it denotes an inherited constructor.
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
// FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
// the constructor can be elidable?
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
NamedDecl *FoundDecl,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs, bool HadMultipleCandidates,
bool IsListInitialization,
bool IsStdInitListInitialization, bool RequiresZeroInit,
unsigned ConstructKind, SourceRange ParenRange);
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
/// Instantiate or parse a C++ default argument expression as necessary.
/// Return true on error.
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
ParmVarDecl *Param);
/// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
/// the default expr if needed.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
FunctionDecl *FD,
ParmVarDecl *Param);
/// FinalizeVarWithDestructor - Prepare for calling destructor on the
/// constructed variable.
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
/// Helper class that collects exception specifications for
/// implicitly-declared special member functions.
class ImplicitExceptionSpecification {
// Pointer to allow copying
Sema *Self;
// We order exception specifications thus:
// noexcept is the most restrictive, but is only used in C++11.
// throw() comes next.
// Then a throw(collected exceptions)
// Finally no specification, which is expressed as noexcept(false).
// throw(...) is used instead if any called function uses it.
ExceptionSpecificationType ComputedEST;
llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
SmallVector<QualType, 4> Exceptions;
void ClearExceptions() {
ExceptionsSeen.clear();
Exceptions.clear();
}
public:
explicit ImplicitExceptionSpecification(Sema &Self)
: Self(&Self), ComputedEST(EST_BasicNoexcept) {
if (!Self.getLangOpts().CPlusPlus11)
ComputedEST = EST_DynamicNone;
}
/// Get the computed exception specification type.
ExceptionSpecificationType getExceptionSpecType() const {
assert(!isComputedNoexcept(ComputedEST) &&
"noexcept(expr) should not be a possible result");
return ComputedEST;
}
/// The number of exceptions in the exception specification.
unsigned size() const { return Exceptions.size(); }
/// The set of exceptions in the exception specification.
const QualType *data() const { return Exceptions.data(); }
/// Integrate another called method into the collected data.
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
/// Integrate an invoked expression into the collected data.
void CalledExpr(Expr *E);
/// Overwrite an EPI's exception specification with this
/// computed exception specification.
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
FunctionProtoType::ExceptionSpecInfo ESI;
ESI.Type = getExceptionSpecType();
if (ESI.Type == EST_Dynamic) {
ESI.Exceptions = Exceptions;
} else if (ESI.Type == EST_None) {
/// C++11 [except.spec]p14:
/// The exception-specification is noexcept(false) if the set of
/// potential exceptions of the special member function contains "any"
ESI.Type = EST_NoexceptFalse;
ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
tok::kw_false).get();
}
return ESI;
}
};
/// Determine what sort of exception specification a defaulted
/// copy constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// default constructor of a class will have, and whether the parameter
/// will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// copy assignment operator of a class will have, and whether the
/// parameter will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted move
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted move
/// assignment operator of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// destructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification an inheriting
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
CXXConstructorDecl *CD);
/// Evaluate the implicit exception specification for a defaulted
/// special member function.
void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
/// Check the given noexcept-specifier, convert its expression, and compute
/// the appropriate ExceptionSpecificationType.
ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
ExceptionSpecificationType &EST);
/// Check the given exception-specification and update the
/// exception specification information with the results.
void checkExceptionSpecification(bool IsTopLevel,
ExceptionSpecificationType EST,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr,
SmallVectorImpl<QualType> &Exceptions,
FunctionProtoType::ExceptionSpecInfo &ESI);
/// Determine if we're in a case where we need to (incorrectly) eagerly
/// parse an exception specification to work around a libstdc++ bug.
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
/// Add an exception-specification to the given member function
/// (or member function template). The exception-specification was parsed
/// after the method itself was declared.
void actOnDelayedExceptionSpecification(Decl *Method,
ExceptionSpecificationType EST,
SourceRange SpecificationRange,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr);
class InheritedConstructorInfo;
/// Determine if a special member function should have a deleted
/// definition when it is defaulted.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
InheritedConstructorInfo *ICI = nullptr,
bool Diagnose = false);
/// Declare the implicit default constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// default constructor will be added.
///
/// \returns The implicitly-declared default constructor.
CXXConstructorDecl *DeclareImplicitDefaultConstructor(
CXXRecordDecl *ClassDecl);
/// DefineImplicitDefaultConstructor - Checks for feasibility of
/// defining this constructor as the default constructor.
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit destructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// destructor will be added.
///
/// \returns The implicitly-declared destructor.
CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitDestructor - Checks for feasibility of
/// defining this destructor as the default destructor.
void DefineImplicitDestructor(SourceLocation CurrentLocation,
CXXDestructorDecl *Destructor);
/// Build an exception spec for destructors that don't have one.
///
/// C++11 says that user-defined destructors with no exception spec get one
/// that looks as if the destructor was implicitly declared.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
/// Define the specified inheriting constructor.
void DefineInheritingConstructor(SourceLocation UseLoc,
CXXConstructorDecl *Constructor);
/// Declare the implicit copy constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy constructor will be added.
///
/// \returns The implicitly-declared copy constructor.
CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitCopyConstructor - Checks for feasibility of
/// defining this constructor as the copy constructor.
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit move constructor for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move constructor will be added.
///
/// \returns The implicitly-declared move constructor, or NULL if it wasn't
/// declared.
CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitMoveConstructor - Checks for feasibility of
/// defining this constructor as the move constructor.
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit copy assignment operator for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy assignment operator will be added.
///
/// \returns The implicitly-declared copy assignment operator.
CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
/// Defines an implicitly-declared copy assignment operator.
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// Declare the implicit move assignment operator for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move assignment operator will be added.
///
/// \returns The implicitly-declared move assignment operator, or NULL if it
/// wasn't declared.
CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
/// Defines an implicitly-declared move assignment operator.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// Force the declaration of any implicitly-declared members of this
/// class.
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
/// Check a completed declaration of an implicit special member.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
/// Determine whether the given function is an implicitly-deleted
/// special member function.
bool isImplicitlyDeleted(FunctionDecl *FD);
/// Check whether 'this' shows up in the type of a static member
/// function after the (naturally empty) cv-qualifier-seq would be.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
/// Whether this' shows up in the exception specification of a static
/// member function.
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
/// Check whether 'this' shows up in the attributes of the given
/// static member function.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
/// MaybeBindToTemporary - If the passed in expression has a record type with
/// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
/// it simply returns the passed in expression.
ExprResult MaybeBindToTemporary(Expr *E);
bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
MultiExprArg ArgsPtr,
SourceLocation Loc,
SmallVectorImpl<Expr*> &ConvertedArgs,
bool AllowExplicit = false,
bool IsListInitialization = false);
ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
SourceLocation NameLoc,
IdentifierInfo &Name);
ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
bool EnteringContext);
ParsedType getDestructorName(SourceLocation TildeLoc,
IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext);
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
ParsedType ObjectType);
// Checks that reinterpret casts don't have undefined behavior.
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
bool IsDereference, SourceRange Range);
/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
SourceLocation LAngleBracketLoc,
Declarator &D,
SourceLocation RAngleBracketLoc,
SourceLocation LParenLoc,
Expr *E,
SourceLocation RParenLoc);
ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
TypeSourceInfo *Ty,
Expr *E,
SourceRange AngleBrackets,
SourceRange Parens);
ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
ExprResult Operand,
SourceLocation RParenLoc);
ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
Expr *Operand, SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXTypeid - Parse typeid( something ).
ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXUuidof - Parse __uuidof( something ).
ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
/// Handle a C++1z fold-expression: ( expr op ... op expr ).
ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
tok::TokenKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
BinaryOperatorKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc,
Optional<unsigned> NumExpansions);
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
BinaryOperatorKind Operator);
//// ActOnCXXThis - Parse 'this' pointer.
ExprResult ActOnCXXThis(SourceLocation loc);
/// Build a CXXThisExpr and mark it referenced in the current context.
Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
void MarkThisReferenced(CXXThisExpr *This);
/// Try to retrieve the type of the 'this' pointer.
///
/// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
QualType getCurrentThisType();
/// When non-NULL, the C++ 'this' expression is allowed despite the
/// current context not being a non-static member function. In such cases,
/// this provides the type used for 'this'.
QualType CXXThisTypeOverride;
/// RAII object used to temporarily allow the C++ 'this' expression
/// to be used, with the given qualifiers on the current class type.
class CXXThisScopeRAII {
Sema &S;
QualType OldCXXThisTypeOverride;
bool Enabled;
public:
/// Introduce a new scope where 'this' may be allowed (when enabled),
/// using the given declaration (which is either a class template or a
/// class) along with the given qualifiers.
/// along with the qualifiers placed on '*this'.
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
bool Enabled = true);
~CXXThisScopeRAII();
};
/// Make sure the value of 'this' is actually available in the current
/// context, if it is a potentially evaluated context.
///
/// \param Loc The location at which the capture of 'this' occurs.
///
/// \param Explicit Whether 'this' is explicitly captured in a lambda
/// capture list.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// 'this' that may or may not be used in certain specializations of
/// a nested generic lambda (depending on whether the name resolves to
/// a non-static member function or a static function).
/// \return returns 'true' if failed, 'false' if success.
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
bool BuildAndDiagnose = true,
const unsigned *const FunctionScopeIndexToStopAt = nullptr,
bool ByCopy = false);
/// Determine whether the given type is the type of *this that is used
/// outside of the body of a member function for a type that is currently
/// being defined.
bool isThisOutsideMemberFunctionBody(QualType BaseType);
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
ExprResult
ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
SourceLocation AtLoc, SourceLocation RParen);
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
//// ActOnCXXThrow - Parse throw expressions.
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
bool IsThrownVarInScope);
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
/// Can be interpreted either as function-style casting ("int(x)")
/// or class type construction ("ClassType(x,y,z)")
/// or creation of a value-initialized type ("int()").
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
SourceLocation LParenOrBraceLoc,
MultiExprArg Exprs,
SourceLocation RParenOrBraceLoc,
bool ListInitialization);
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
SourceLocation LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc,
bool ListInitialization);
/// ActOnCXXNew - Parsed a C++ 'new' expression.
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens, Declarator &D,
Expr *Initializer);
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens,
QualType AllocType,
TypeSourceInfo *AllocTypeInfo,
Optional<Expr *> ArraySize,
SourceRange DirectInitRange,
Expr *Initializer);
/// Determine whether \p FD is an aligned allocation or deallocation
/// function that is unavailable.
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
/// Produce diagnostics if \p FD is an aligned allocation or deallocation
/// function that is unavailable.
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
SourceLocation Loc);
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
SourceRange R);
/// The scope in which to find allocation functions.
enum AllocationFunctionScope {
/// Only look for allocation functions in the global scope.
AFS_Global,
/// Only look for allocation functions in the scope of the
/// allocated class.
AFS_Class,
/// Look for allocation functions in both the global scope
/// and in the scope of the allocated class.
AFS_Both
};
/// Finds the overloads of operator new and delete that are appropriate
/// for the allocation.
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
AllocationFunctionScope NewScope,
AllocationFunctionScope DeleteScope,
QualType AllocType, bool IsArray,
bool &PassAlignment, MultiExprArg PlaceArgs,
FunctionDecl *&OperatorNew,
FunctionDecl *&OperatorDelete,
bool Diagnose = true);
void DeclareGlobalNewDelete();
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
ArrayRef<QualType> Params);
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
DeclarationName Name, FunctionDecl* &Operator,
bool Diagnose = true);
FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
bool CanProvideSize,
bool Overaligned,
DeclarationName Name);
FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
CXXRecordDecl *RD);
/// ActOnCXXDelete - Parsed a C++ 'delete' expression
ExprResult ActOnCXXDelete(SourceLocation StartLoc,
bool UseGlobal, bool ArrayForm,
Expr *Operand);
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
bool IsDelete, bool CallCanBeVirtual,
bool WarnOnNonAbstractTypes,
SourceLocation DtorLoc);
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
Expr *Operand, SourceLocation RParen);
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
SourceLocation RParen);
/// Parsed one of the type trait support pseudo-functions.
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<ParsedType> Args,
SourceLocation RParenLoc);
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<TypeSourceInfo *> Args,
SourceLocation RParenLoc);
/// ActOnArrayTypeTrait - Parsed one of the binary type trait support
/// pseudo-functions.
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
ParsedType LhsTy,
Expr *DimExpr,
SourceLocation RParen);
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
TypeSourceInfo *TSInfo,
Expr *DimExpr,
SourceLocation RParen);
/// ActOnExpressionTrait - Parsed one of the unary type trait support
/// pseudo-functions.
ExprResult ActOnExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult BuildExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult ActOnStartCXXMemberReference(Scope *S,
Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
ParsedType &ObjectType,
bool &MayBePseudoDestructor);
ExprResult BuildPseudoDestructorExpr(Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
const CXXScopeSpec &SS,
TypeSourceInfo *ScopeType,
SourceLocation CCLoc,
SourceLocation TildeLoc,
PseudoDestructorTypeStorage DestroyedType);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
UnqualifiedId &FirstTypeName,
SourceLocation CCLoc,
SourceLocation TildeLoc,
UnqualifiedId &SecondTypeName);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
SourceLocation TildeLoc,
const DeclSpec& DS);
/// MaybeCreateExprWithCleanups - If the current full-expression
/// requires any cleanups, surround it with a ExprWithCleanups node.
/// Otherwise, just returns the passed-in expression.
Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
MaterializeTemporaryExpr *
CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
bool BoundToLvalueReference);
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
return ActOnFinishFullExpr(
Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
}
ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
bool DiscardedValue, bool IsConstexpr = false);
StmtResult ActOnFinishFullStmt(Stmt *Stmt);
// Marks SS invalid if it represents an incomplete type.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
DeclContext *computeDeclContext(QualType T);
DeclContext *computeDeclContext(const CXXScopeSpec &SS,
bool EnteringContext = false);
bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
/// The parser has parsed a global nested-name-specifier '::'.
///
/// \param CCLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
/// The parser has parsed a '__super' nested-name-specifier.
///
/// \param SuperLoc The location of the '__super' keyword.
///
/// \param ColonColonLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
SourceLocation ColonColonLoc, CXXScopeSpec &SS);
bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
bool *CanCorrect = nullptr);
NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
/// Keeps information about an identifier in a nested-name-spec.
///
struct NestedNameSpecInfo {
/// The type of the object, if we're parsing nested-name-specifier in
/// a member access expression.
ParsedType ObjectType;
/// The identifier preceding the '::'.
IdentifierInfo *Identifier;
/// The location of the identifier.
SourceLocation IdentifierLoc;
/// The location of the '::'.
SourceLocation CCLoc;
/// Creates info object for the most typical case.
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
: ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
CCLoc(ColonColonLoc) {
}
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
SourceLocation ColonColonLoc, QualType ObjectType)
: ObjectType(ParsedType::make(ObjectType)), Identifier(II),
IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
}
};
bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
NestedNameSpecInfo &IdInfo);
bool BuildCXXNestedNameSpecifier(Scope *S,
NestedNameSpecInfo &IdInfo,
bool EnteringContext,
CXXScopeSpec &SS,
NamedDecl *ScopeLookupResult,
bool ErrorRecoveryLookup,
bool *IsCorrectedToColon = nullptr,
bool OnlyNamespace = false);
/// The parser has parsed a nested-name-specifier 'identifier::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param IdInfo Parser information about an identifier in the
/// nested-name-spec.
///
/// \param EnteringContext Whether we're entering the context nominated by
/// this nested-name-specifier.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param ErrorRecoveryLookup If true, then this method is called to improve
/// error recovery. In this case do not emit error message.
///
/// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
/// are allowed. The bool value pointed by this parameter is set to 'true'
/// if the identifier is treated as if it was followed by ':', not '::'.
///
/// \param OnlyNamespace If true, only considers namespaces in lookup.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
NestedNameSpecInfo &IdInfo,
bool EnteringContext,
CXXScopeSpec &SS,
bool ErrorRecoveryLookup = false,
bool *IsCorrectedToColon = nullptr,
bool OnlyNamespace = false);
ExprResult ActOnDecltypeExpression(Expr *E);
bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
const DeclSpec &DS,
SourceLocation ColonColonLoc);
bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
NestedNameSpecInfo &IdInfo,
bool EnteringContext);
/// The parser has parsed a nested-name-specifier
/// 'template[opt] template-name < template-args >::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param TemplateKWLoc the location of the 'template' keyword, if any.
/// \param TemplateName the template name.
/// \param TemplateNameLoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
/// \param CCLoc The location of the '::'.
///
/// \param EnteringContext Whether we're entering the context of the
/// nested-name-specifier.
///
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateName,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
SourceLocation CCLoc,
bool EnteringContext);
/// Given a C++ nested-name-specifier, produce an annotation value
/// that the parser can use later to reconstruct the given
/// nested-name-specifier.
///
/// \param SS A nested-name-specifier.
///
/// \returns A pointer containing all of the information in the
/// nested-name-specifier \p SS.
void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
/// Given an annotation pointer for a nested-name-specifier, restore
/// the nested-name-specifier structure.
///
/// \param Annotation The annotation pointer, produced by
/// \c SaveNestedNameSpecifierAnnotation().
///
/// \param AnnotationRange The source range corresponding to the annotation.
///
/// \param SS The nested-name-specifier that will be updated with the contents
/// of the annotation pointer.
void RestoreNestedNameSpecifierAnnotation(void *Annotation,
SourceRange AnnotationRange,
CXXScopeSpec &SS);
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
/// scope or nested-name-specifier) is parsed, part of a declarator-id.
/// After this method is called, according to [C++ 3.4.3p3], names should be
/// looked up in the declarator-id's scope, until the declarator is parsed and
/// ActOnCXXExitDeclaratorScope is called.
/// The 'SS' should be a non-empty valid CXXScopeSpec.
bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
/// Used to indicate that names should revert to being looked up in the
/// defining scope.
void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
/// initializer for the declaration 'Dcl'.
/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
/// static data member of class X, names should be looked up in the scope of
/// class X.
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
/// initializer for the declaration 'Dcl'.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
/// Create a new lambda closure type.
CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
TypeSourceInfo *Info,
bool KnownDependent,
LambdaCaptureDefault CaptureDefault);
/// Start the definition of a lambda expression.
CXXMethodDecl *
startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange,
TypeSourceInfo *MethodType, SourceLocation EndLoc,
ArrayRef<ParmVarDecl *> Params,
ConstexprSpecKind ConstexprKind,
Optional<std::pair<unsigned, Decl *>> Mangling = None);
/// Endow the lambda scope info with the relevant properties.
void buildLambdaScope(sema::LambdaScopeInfo *LSI,
CXXMethodDecl *CallOperator,
SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
bool ExplicitParams,
bool ExplicitResultType,
bool Mutable);
/// Perform initialization analysis of the init-capture and perform
/// any implicit conversions such as an lvalue-to-rvalue conversion if
/// not being used to initialize a reference.
ParsedType actOnLambdaInitCaptureInitialization(
SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
return ParsedType::make(buildLambdaInitCaptureInitialization(
Loc, ByRef, EllipsisLoc, None, Id,
InitKind != LambdaCaptureInitKind::CopyInit, Init));
}
QualType buildLambdaInitCaptureInitialization(
SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
Expr *&Init);
/// Create a dummy variable within the declcontext of the lambda's
/// call operator, for name lookup purposes for a lambda init capture.
///
/// CodeGen handles emission of lambda captures, ignoring these dummy
/// variables appropriately.
VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
QualType InitCaptureType,
SourceLocation EllipsisLoc,
IdentifierInfo *Id,
unsigned InitStyle, Expr *Init);
/// Add an init-capture to a lambda scope.
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
/// Note that we have finished the explicit captures for the
/// given lambda.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
/// \brief This is called after parsing the explicit template parameter list
/// on a lambda (if it exists) in C++2a.
void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
ArrayRef<NamedDecl *> TParams,
SourceLocation RAngleLoc);
/// Introduce the lambda parameters into scope.
void addLambdaParameters(
ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
CXXMethodDecl *CallOperator, Scope *CurScope);
/// Deduce a block or lambda's return type based on the return
/// statements present in the body.
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
/// ActOnStartOfLambdaDefinition - This is called just before we start
/// parsing the body of a lambda; it analyzes the explicit captures and
/// arguments, and sets up various data-structures for the body of the
/// lambda.
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Declarator &ParamInfo, Scope *CurScope);
/// ActOnLambdaError - If there is an error parsing a lambda, this callback
/// is invoked to pop the information about the lambda.
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
bool IsInstantiation = false);
/// ActOnLambdaExpr - This is called when the body of a lambda expression
/// was successfully completed.
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Scope *CurScope);
/// Does copying/destroying the captured variable have side effects?
bool CaptureHasSideEffects(const sema::Capture &From);
/// Diagnose if an explicit lambda capture is unused. Returns true if a
/// diagnostic is emitted.
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
const sema::Capture &From);
/// Build a FieldDecl suitable to hold the given capture.
FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
/// Initialize the given capture with a suitable expression.
ExprResult BuildCaptureInit(const sema::Capture &Capture,
SourceLocation ImplicitCaptureLoc,
bool IsOpenMPMapping = false);
/// Complete a lambda-expression having processed and attached the
/// lambda body.
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
sema::LambdaScopeInfo *LSI);
/// Get the return type to use for a lambda's conversion function(s) to
/// function pointer type, given the type of the call operator.
QualType
getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
/// Define the "body" of the conversion from a lambda object to a
/// function pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToFunctionPointerConversion(
SourceLocation CurrentLoc, CXXConversionDecl *Conv);
/// Define the "body" of the conversion from a lambda object to a
/// block pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
CXXConversionDecl *Conv);
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
SourceLocation ConvLocation,
CXXConversionDecl *Conv,
Expr *Src);
// ParseObjCStringLiteral - Parse Objective-C string literals.
ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
ArrayRef<Expr *> Strings);
ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
/// numeric literal expression. Type of the expression will be "NSNumber *"
/// or "id" if NSNumber is unavailable.
ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
bool Value);
ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
/// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
/// '@' prefixed parenthesized expression. The type of the expression will
/// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
/// of ValueType, which is allowed to be a built-in numeric type, "char *",
/// "const char *" or C structure with attribute 'objc_boxable'.
ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
Expr *IndexExpr,
ObjCMethodDecl *getterMethod,
ObjCMethodDecl *setterMethod);
ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
MutableArrayRef<ObjCDictionaryElement> Elements);
ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
TypeSourceInfo *EncodedTypeInfo,
SourceLocation RParenLoc);
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
CXXConversionDecl *Method,
bool HadMultipleCandidates);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
SourceLocation EncodeLoc,
SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc);
/// ParseObjCSelectorExpression - Build selector expression for \@selector
ExprResult ParseObjCSelectorExpression(Selector Sel,
SourceLocation AtLoc,
SourceLocation SelLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc,
bool WarnMultipleSelectors);
/// ParseObjCProtocolExpression - Build protocol expression for \@protocol
ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
SourceLocation AtLoc,
SourceLocation ProtoLoc,
SourceLocation LParenLoc,
SourceLocation ProtoIdLoc,
SourceLocation RParenLoc);
//===--------------------------------------------------------------------===//
// C++ Declarations
//
Decl *ActOnStartLinkageSpecification(Scope *S,
SourceLocation ExternLoc,
Expr *LangStr,
SourceLocation LBraceLoc);
Decl *ActOnFinishLinkageSpecification(Scope *S,
Decl *LinkageSpec,
SourceLocation RBraceLoc);
//===--------------------------------------------------------------------===//
// C++ Classes
//
CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
const CXXScopeSpec *SS = nullptr);
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
SourceLocation ColonLoc,
const ParsedAttributesView &Attrs);
NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
Declarator &D,
MultiTemplateParamsArg TemplateParameterLists,
Expr *BitfieldWidth, const VirtSpecifiers &VS,
InClassInitStyle InitStyle);
void ActOnStartCXXInClassMemberInitializer();
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
SourceLocation EqualLoc,
Expr *Init);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
SourceLocation LParenLoc,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
SourceLocation EllipsisLoc);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *InitList,
SourceLocation EllipsisLoc);
MemInitResult BuildMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *Init,
SourceLocation EllipsisLoc);
MemInitResult BuildMemberInitializer(ValueDecl *Member,
Expr *Init,
SourceLocation IdLoc);
MemInitResult BuildBaseInitializer(QualType BaseType,
TypeSourceInfo *BaseTInfo,
Expr *Init,
CXXRecordDecl *ClassDecl,
SourceLocation EllipsisLoc);
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Expr *Init,
CXXRecordDecl *ClassDecl);
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
CXXCtorInitializer *Initializer);
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
ArrayRef<CXXCtorInitializer *> Initializers = None);
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
/// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
/// mark all the non-trivial destructors of its members and bases as
/// referenced.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
CXXRecordDecl *Record);
/// The list of classes whose vtables have been used within
/// this translation unit, and the source locations at which the
/// first use occurred.
typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
/// The list of vtables that are required but have not yet been
/// materialized.
SmallVector<VTableUse, 16> VTableUses;
/// The set of classes whose vtables have been used within
/// this translation unit, and a bit that will be true if the vtable is
/// required to be emitted (otherwise, it should be emitted only if needed
/// by code generation).
llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
/// Load any externally-stored vtable uses.
void LoadExternalVTableUses();
/// Note that the vtable for the given class was used at the
/// given location.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
bool DefinitionRequired = false);
/// Mark the exception specifications of all virtual member functions
/// in the given class as needed.
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
const CXXRecordDecl *RD);
/// MarkVirtualMembersReferenced - Will mark all members of the given
/// CXXRecordDecl referenced.
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
bool ConstexprOnly = false);
/// Define all of the vtables that have been used in this
/// translation unit and reference any virtual members used by those
/// vtables.
///
/// \returns true if any work was done, false otherwise.
bool DefineUsedVTables();
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
void ActOnMemInitializers(Decl *ConstructorDecl,
SourceLocation ColonLoc,
ArrayRef<CXXCtorInitializer*> MemInits,
bool AnyErrors);
/// Check class-level dllimport/dllexport attribute. The caller must
/// ensure that referenceDLLExportedClassMethods is called some point later
/// when all outer classes of Class are complete.
void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
void referenceDLLExportedClassMethods();
void propagateDLLAttrToBaseClassTemplate(
CXXRecordDecl *Class, Attr *ClassAttr,
ClassTemplateSpecializationDecl *BaseTemplateSpec,
SourceLocation BaseLoc);
void CheckCompletedCXXClass(CXXRecordDecl *Record);
/// Check that the C++ class annoated with "trivial_abi" satisfies all the
/// conditions that are needed for the attribute to have an effect.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
Decl *TagDecl, SourceLocation LBrac,
SourceLocation RBrac,
const ParsedAttributesView &AttrList);
void ActOnFinishCXXMemberDecls();
void ActOnFinishCXXNonNestedClass(Decl *D);
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnFinishDelayedMemberInitializers(Decl *Record);
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
CachedTokens &Toks);
void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
bool IsInsideALocalClassWithinATemplateFunction();
Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
Expr *AssertMessageExpr,
SourceLocation RParenLoc);
Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
StringLiteral *AssertMessageExpr,
SourceLocation RParenLoc,
bool Failed);
FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
SourceLocation FriendLoc,
TypeSourceInfo *TSInfo);
Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
MultiTemplateParamsArg TemplateParams);
NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParams);
QualType CheckConstructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
void CheckConstructor(CXXConstructorDecl *Constructor);
QualType CheckDestructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
bool CheckDestructor(CXXDestructorDecl *Destructor);
void CheckConversionDeclarator(Declarator &D, QualType &R,
StorageClass& SC);
Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
StorageClass &SC);
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
void CheckDelayedMemberExceptionSpecs();
//===--------------------------------------------------------------------===//
// C++ Derived Classes
//
/// ActOnBaseSpecifier - Parsed a base specifier
CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
SourceRange SpecifierRange,
bool Virtual, AccessSpecifier Access,
TypeSourceInfo *TInfo,
SourceLocation EllipsisLoc);
BaseResult ActOnBaseSpecifier(Decl *classdecl,
SourceRange SpecifierRange,
ParsedAttributes &Attrs,
bool Virtual, AccessSpecifier Access,
ParsedType basetype,
SourceLocation BaseLoc,
SourceLocation EllipsisLoc);
bool AttachBaseSpecifiers(CXXRecordDecl *Class,
MutableArrayRef<CXXBaseSpecifier *> Bases);
void ActOnBaseSpecifiers(Decl *ClassDecl,
MutableArrayRef<CXXBaseSpecifier *> Bases);
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
CXXBasePaths &Paths);
// FIXME: I don't like this name.
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
SourceLocation Loc, SourceRange Range,
CXXCastPath *BasePath = nullptr,
bool IgnoreAccess = false);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
unsigned InaccessibleBaseID,
unsigned AmbigiousBaseConvID,
SourceLocation Loc, SourceRange Range,
DeclarationName Name,
CXXCastPath *BasePath,
bool IgnoreAccess = false);
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionReturnType - Checks whether the return types are
/// covariant, according to C++ [class.virtual]p5.
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionExceptionSpec - Checks whether the exception
/// spec is a subset of base spec.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
/// CheckOverrideControl - Check C++11 override control semantics.
void CheckOverrideControl(NamedDecl *D);
/// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
/// not used in the declaration of an overriding method.
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
/// CheckForFunctionMarkedFinal - Checks whether a virtual member function
/// overrides a virtual member function marked 'final', according to
/// C++11 [class.virtual]p4.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
//===--------------------------------------------------------------------===//
// C++ Access Control
//
enum AccessResult {
AR_accessible,
AR_inaccessible,
AR_dependent,
AR_delayed
};
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
NamedDecl *PrevMemberDecl,
AccessSpecifier LexicalAS);
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
SourceRange PlacementRange,
CXXRecordDecl *NamingClass,
DeclAccessPair FoundDecl,
bool Diagnose = true);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
DeclAccessPair FoundDecl,
const InitializedEntity &Entity,
bool IsCopyBindingRefToTemp = false);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
DeclAccessPair FoundDecl,
const InitializedEntity &Entity,
const PartialDiagnostic &PDiag);
AccessResult CheckDestructorAccess(SourceLocation Loc,
CXXDestructorDecl *Dtor,
const PartialDiagnostic &PDiag,
QualType objectType = QualType());
AccessResult CheckFriendAccess(NamedDecl *D);
AccessResult CheckMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *NamingClass,
DeclAccessPair Found);
AccessResult
CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *DecomposedClass,
DeclAccessPair Field);
AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
Expr *ObjectExpr,
Expr *ArgExpr,
DeclAccessPair FoundDecl);
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
DeclAccessPair FoundDecl);
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
QualType Base, QualType Derived,
const CXXBasePath &Path,
unsigned DiagID,
bool ForceCheck = false,
bool ForceUnprivileged = false);
void CheckLookupAccess(const LookupResult &R);
bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
QualType BaseType);
bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
AccessSpecifier access,
QualType objectType);
void HandleDependentAccessCheck(const DependentDiagnostic &DD,
const MultiLevelTemplateArgumentList &TemplateArgs);
void PerformDependentDiagnostics(const DeclContext *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
/// When true, access checking violations are treated as SFINAE
/// failures rather than hard errors.
bool AccessCheckingSFINAE;
enum AbstractDiagSelID {
AbstractNone = -1,
AbstractReturnType,
AbstractParamType,
AbstractVariableType,
AbstractFieldType,
AbstractIvarType,
AbstractSynthesizedIvarType,
AbstractArrayType
};
bool isAbstractType(SourceLocation Loc, QualType T);
bool RequireNonAbstractType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
template <typename... Ts>
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireNonAbstractType(Loc, T, Diagnoser);
}
void DiagnoseAbstractType(const CXXRecordDecl *RD);
//===--------------------------------------------------------------------===//
// C++ Overloaded Operators [C++ 13.5]
//
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
//===--------------------------------------------------------------------===//
// C++ Templates [C++ 14]
//
void FilterAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true,
bool AllowDependent = true);
bool hasAnyAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true,
bool AllowDependent = true,
bool AllowNonTemplateFunctions = false);
/// Try to interpret the lookup result D as a template-name.
///
/// \param D A declaration found by name lookup.
/// \param AllowFunctionTemplates Whether function templates should be
/// considered valid results.
/// \param AllowDependent Whether unresolved using declarations (that might
/// name templates) should be considered valid results.
NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
bool AllowFunctionTemplates = true,
bool AllowDependent = true);
enum class AssumedTemplateKind {
/// This is not assumed to be a template name.
None,
/// This is assumed to be a template name because lookup found nothing.
FoundNothing,
/// This is assumed to be a template name because lookup found one or more
/// functions (but no function templates).
FoundFunctions,
};
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
QualType ObjectType, bool EnteringContext,
bool &MemberOfUnknownSpecialization,
SourceLocation TemplateKWLoc = SourceLocation(),
AssumedTemplateKind *ATK = nullptr);
TemplateNameKind isTemplateName(Scope *S,
CXXScopeSpec &SS,
bool hasTemplateKeyword,
const UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template,
bool &MemberOfUnknownSpecialization);
/// Try to resolve an undeclared template name as a type template.
///
/// Sets II to the identifier corresponding to the template name, and updates
/// Name to a corresponding (typo-corrected) type template name and TNK to
/// the corresponding kind, if possible.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
TemplateNameKind &TNK,
SourceLocation NameLoc,
IdentifierInfo *&II);
bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
SourceLocation NameLoc,
bool Diagnose = true);
/// Determine whether a particular identifier might be the name in a C++1z
/// deduction-guide declaration.
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
SourceLocation NameLoc,
ParsedTemplateTy *Template = nullptr);
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
SourceLocation IILoc,
Scope *S,
const CXXScopeSpec *SS,
TemplateTy &SuggestedTemplate,
TemplateNameKind &SuggestedKind);
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
NamedDecl *Instantiation,
bool InstantiatedFromMember,
const NamedDecl *Pattern,
const NamedDecl *PatternDef,
TemplateSpecializationKind TSK,
bool Complain = true);
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
SourceLocation EllipsisLoc,
SourceLocation KeyLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth, unsigned Position,
SourceLocation EqualLoc,
ParsedType DefaultArg);
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
SourceLocation Loc);
QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
Expr *DefaultArg);
NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
SourceLocation TmpLoc,
TemplateParameterList *Params,
SourceLocation EllipsisLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
ParsedTemplateArgument DefaultArg);
TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,
SourceLocation ExportLoc,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ArrayRef<NamedDecl *> Params,
SourceLocation RAngleLoc,
Expr *RequiresClause);
/// The context in which we are checking a template parameter list.
enum TemplateParamListContext {
TPC_ClassTemplate,
TPC_VarTemplate,
TPC_FunctionTemplate,
TPC_ClassTemplateMember,
TPC_FriendClassTemplate,
TPC_FriendFunctionTemplate,
TPC_FriendFunctionTemplateDefinition,
TPC_TypeAliasTemplate
};
bool CheckTemplateParameterList(TemplateParameterList *NewParams,
TemplateParameterList *OldParams,
TemplateParamListContext TPC,
SkipBodyInfo *SkipBody = nullptr);
TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
SourceLocation DeclStartLoc, SourceLocation DeclLoc,
const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
ArrayRef<TemplateParameterList *> ParamLists,
bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
DeclResult CheckClassTemplate(
Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
AccessSpecifier AS, SourceLocation ModulePrivateLoc,
SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
TemplateParameterList **OuterTemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
QualType NTTPType,
SourceLocation Loc);
void translateTemplateArguments(const ASTTemplateArgsPtr &In,
TemplateArgumentListInfo &Out);
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
void NoteAllFoundTemplates(TemplateName Name);
QualType CheckTemplateIdType(TemplateName Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs);
TypeResult
ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
TemplateTy Template, IdentifierInfo *TemplateII,
SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
bool IsCtorOrDtorName = false, bool IsClassName = false);
/// Parsed an elaborated-type-specifier that refers to a template-id,
/// such as \c class T::template apply<U>.
TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
TypeSpecifierType TagSpec,
SourceLocation TagLoc,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateD,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgsIn,
SourceLocation RAngleLoc);
DeclResult ActOnVarTemplateSpecialization(
Scope *S, Declarator &D, TypeSourceInfo *DI,
SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
StorageClass SC, bool IsPartialSpecialization);
DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation TemplateNameLoc,
const TemplateArgumentListInfo &TemplateArgs);
ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
VarTemplateDecl *Template,
SourceLocation TemplateLoc,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult
CheckConceptTemplateId(const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
ConceptDecl *Template,
SourceLocation TemplateLoc,
const TemplateArgumentListInfo *TemplateArgs);
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
bool RequiresADL,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
TemplateNameKind ActOnDependentTemplateName(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
TemplateTy &Template, bool AllowInjectedClassName = false);
DeclResult ActOnClassTemplateSpecialization(
Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
const ParsedAttributesView &Attr,
MultiTemplateParamsArg TemplateParameterLists,
SkipBodyInfo *SkipBody = nullptr);
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
TemplateDecl *PrimaryTemplate,
unsigned NumExplicitArgs,
ArrayRef<TemplateArgument> Args);
void CheckTemplatePartialSpecialization(
ClassTemplatePartialSpecializationDecl *Partial);
void CheckTemplatePartialSpecialization(
VarTemplatePartialSpecializationDecl *Partial);
Decl *ActOnTemplateDeclarator(Scope *S,
MultiTemplateParamsArg TemplateParameterLists,
Declarator &D);
bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
TemplateSpecializationKind NewTSK,
NamedDecl *PrevDecl,
TemplateSpecializationKind PrevTSK,
SourceLocation PrevPtOfInstantiation,
bool &SuppressNew);
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
const TemplateArgumentListInfo &ExplicitTemplateArgs,
LookupResult &Previous);
bool CheckFunctionTemplateSpecialization(
FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
LookupResult &Previous, bool QualifiedFriend = false);
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
DeclResult ActOnExplicitInstantiation(
Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
TemplateTy Template, SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
SourceLocation TemplateLoc,
unsigned TagSpec, SourceLocation KWLoc,
CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc,
const ParsedAttributesView &Attr);
DeclResult ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
Declarator &D);
TemplateArgumentLoc
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
Decl *Param,
SmallVectorImpl<TemplateArgument>
&Converted,
bool &HasDefaultArg);
/// Specifies the context in which a particular template
/// argument is being checked.
enum CheckTemplateArgumentKind {
/// The template argument was specified in the code or was
/// instantiated with some deduced template arguments.
CTAK_Specified,
/// The template argument was deduced via template argument
/// deduction.
CTAK_Deduced,
/// The template argument was deduced from an array bound
/// via template argument deduction.
CTAK_DeducedFromArrayBound
};
bool CheckTemplateArgument(NamedDecl *Param,
TemplateArgumentLoc &Arg,
NamedDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
unsigned ArgumentPackIndex,
SmallVectorImpl<TemplateArgument> &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
/// Check that the given template arguments can be be provided to
/// the given template, converting the arguments along the way.
///
/// \param Template The template to which the template arguments are being
/// provided.
///
/// \param TemplateLoc The location of the template name in the source.
///
/// \param TemplateArgs The list of template arguments. If the template is
/// a template template parameter, this function may extend the set of
/// template arguments to also include substituted, defaulted template
/// arguments.
///
/// \param PartialTemplateArgs True if the list of template arguments is
/// intentionally partial, e.g., because we're checking just the initial
/// set of template arguments.
///
/// \param Converted Will receive the converted, canonicalized template
/// arguments.
///
/// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
/// contain the converted forms of the template arguments as written.
/// Otherwise, \p TemplateArgs will not be modified.
///
/// \returns true if an error occurred, false otherwise.
bool CheckTemplateArgumentList(TemplateDecl *Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs,
bool PartialTemplateArgs,
SmallVectorImpl<TemplateArgument> &Converted,
bool UpdateArgsWithConversions = true);
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
TemplateArgumentLoc &Arg,
SmallVectorImpl<TemplateArgument> &Converted);
bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
TypeSourceInfo *Arg);
ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
QualType InstantiatedParamType, Expr *Arg,
TemplateArgument &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
bool CheckTemplateTemplateArgument(TemplateParameterList *Params,
TemplateArgumentLoc &Arg);
ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
QualType ParamType,
SourceLocation Loc);
ExprResult
BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
SourceLocation Loc);
/// Enumeration describing how template parameter lists are compared
/// for equality.
enum TemplateParameterListEqualKind {
/// We are matching the template parameter lists of two templates
/// that might be redeclarations.
///
/// \code
/// template<typename T> struct X;
/// template<typename T> struct X;
/// \endcode
TPL_TemplateMatch,
/// We are matching the template parameter lists of two template
/// template parameters as part of matching the template parameter lists
/// of two templates that might be redeclarations.
///
/// \code
/// template<template<int I> class TT> struct X;
/// template<template<int Value> class Other> struct X;
/// \endcode
TPL_TemplateTemplateParmMatch,
/// We are matching the template parameter lists of a template
/// template argument against the template parameter lists of a template
/// template parameter.
///
/// \code
/// template<template<int Value> class Metafun> struct X;
/// template<int Value> struct integer_c;
/// X<integer_c> xic;
/// \endcode
TPL_TemplateTemplateArgumentMatch
};
bool TemplateParameterListsAreEqual(TemplateParameterList *New,
TemplateParameterList *Old,
bool Complain,
TemplateParameterListEqualKind Kind,
SourceLocation TemplateArgLoc
= SourceLocation());
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
/// Called when the parser has parsed a C++ typename
/// specifier, e.g., "typename T::type".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param II the identifier we're retrieving (e.g., 'type' in the example).
/// \param IdLoc the location of the identifier.
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS, const IdentifierInfo &II,
SourceLocation IdLoc);
/// Called when the parser has parsed a C++ typename
/// specifier that ends in a template-id, e.g.,
/// "typename MetaFun::template apply<T1, T2>".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param TemplateLoc the location of the 'template' keyword, if any.
/// \param TemplateName The template name.
/// \param TemplateII The identifier used to name the template.
/// \param TemplateIILoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateLoc,
TemplateTy TemplateName,
IdentifierInfo *TemplateII,
SourceLocation TemplateIILoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc);
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
SourceLocation KeywordLoc,
NestedNameSpecifierLoc QualifierLoc,
const IdentifierInfo &II,
SourceLocation IILoc);
TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
SourceLocation Loc,
DeclarationName Name);
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
ExprResult RebuildExprInCurrentInstantiation(Expr *E);
bool RebuildTemplateParamsInCurrentInstantiation(
TemplateParameterList *Params);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgumentList &Args);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgument *Args,
unsigned NumArgs);
// Concepts
Decl *ActOnConceptDefinition(
Scope *S, MultiTemplateParamsArg TemplateParameterLists,
IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
//===--------------------------------------------------------------------===//
// C++ Variadic Templates (C++0x [temp.variadic])
//===--------------------------------------------------------------------===//
/// Determine whether an unexpanded parameter pack might be permitted in this
/// location. Useful for error recovery.
bool isUnexpandedParameterPackPermitted();
/// The context in which an unexpanded parameter pack is
/// being diagnosed.
///
/// Note that the values of this enumeration line up with the first
/// argument to the \c err_unexpanded_parameter_pack diagnostic.
enum UnexpandedParameterPackContext {
/// An arbitrary expression.
UPPC_Expression = 0,
/// The base type of a class type.
UPPC_BaseType,
/// The type of an arbitrary declaration.
UPPC_DeclarationType,
/// The type of a data member.
UPPC_DataMemberType,
/// The size of a bit-field.
UPPC_BitFieldWidth,
/// The expression in a static assertion.
UPPC_StaticAssertExpression,
/// The fixed underlying type of an enumeration.
UPPC_FixedUnderlyingType,
/// The enumerator value.
UPPC_EnumeratorValue,
/// A using declaration.
UPPC_UsingDeclaration,
/// A friend declaration.
UPPC_FriendDeclaration,
/// A declaration qualifier.
UPPC_DeclarationQualifier,
/// An initializer.
UPPC_Initializer,
/// A default argument.
UPPC_DefaultArgument,
/// The type of a non-type template parameter.
UPPC_NonTypeTemplateParameterType,
/// The type of an exception.
UPPC_ExceptionType,
/// Partial specialization.
UPPC_PartialSpecialization,
/// Microsoft __if_exists.
UPPC_IfExists,
/// Microsoft __if_not_exists.
UPPC_IfNotExists,
/// Lambda expression.
UPPC_Lambda,
/// Block expression,
UPPC_Block
};
/// Diagnose unexpanded parameter packs.
///
/// \param Loc The location at which we should emit the diagnostic.
///
/// \param UPPC The context in which we are diagnosing unexpanded
/// parameter packs.
///
/// \param Unexpanded the set of unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
UnexpandedParameterPackContext UPPC,
ArrayRef<UnexpandedParameterPack> Unexpanded);
/// If the given type contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The source location where a diagnostc should be emitted.
///
/// \param T The type that is being checked for unexpanded parameter
/// packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
UnexpandedParameterPackContext UPPC);
/// If the given expression contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param E The expression that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(Expr *E,
UnexpandedParameterPackContext UPPC = UPPC_Expression);
/// If the given nested-name-specifier contains an unexpanded
/// parameter pack, diagnose the error.
///
/// \param SS The nested-name-specifier that is being checked for
/// unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
UnexpandedParameterPackContext UPPC);
/// If the given name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param NameInfo The name (with source location information) that
/// is being checked for unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
UnexpandedParameterPackContext UPPC);
/// If the given template name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The location of the template name.
///
/// \param Template The template name that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
TemplateName Template,
UnexpandedParameterPackContext UPPC);
/// If the given template argument contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param Arg The template argument that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
UnexpandedParameterPackContext UPPC);
/// Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgument Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param T The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(QualType T,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param TL The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TypeLoc TL,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// nested-name-specifier.
///
/// \param NNS The nested-name-specifier that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// name.
///
/// \param NameInfo The name that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Invoked when parsing a template argument followed by an
/// ellipsis, which creates a pack expansion.
///
/// \param Arg The template argument preceding the ellipsis, which
/// may already be invalid.
///
/// \param EllipsisLoc The location of the ellipsis.
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
SourceLocation EllipsisLoc);
/// Invoked when parsing a type followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Type The type preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
/// Construct a pack expansion type from the pattern of the pack
/// expansion.
TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Construct a pack expansion type from the pattern of the pack
/// expansion.
QualType CheckPackExpansion(QualType Pattern,
SourceRange PatternRange,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
/// Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Determine whether we could expand a pack expansion with the
/// given set of parameter packs into separate arguments by repeatedly
/// transforming the pattern.
///
/// \param EllipsisLoc The location of the ellipsis that identifies the
/// pack expansion.
///
/// \param PatternRange The source range that covers the entire pattern of
/// the pack expansion.
///
/// \param Unexpanded The set of unexpanded parameter packs within the
/// pattern.
///
/// \param ShouldExpand Will be set to \c true if the transformer should
/// expand the corresponding pack expansions into separate arguments. When
/// set, \c NumExpansions must also be set.
///
/// \param RetainExpansion Whether the caller should add an unexpanded
/// pack expansion after all of the expanded arguments. This is used
/// when extending explicitly-specified template argument packs per
/// C++0x [temp.arg.explicit]p9.
///
/// \param NumExpansions The number of separate arguments that will be in
/// the expanded form of the corresponding pack expansion. This is both an
/// input and an output parameter, which can be set by the caller if the
/// number of expansions is known a priori (e.g., due to a prior substitution)
/// and will be set by the callee when the number of expansions is known.
/// The callee must set this value when \c ShouldExpand is \c true; it may
/// set this value in other cases.
///
/// \returns true if an error occurred (e.g., because the parameter packs
/// are to be instantiated with arguments of different lengths), false
/// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
/// must be set.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
SourceRange PatternRange,
ArrayRef<UnexpandedParameterPack> Unexpanded,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool &ShouldExpand,
bool &RetainExpansion,
Optional<unsigned> &NumExpansions);
/// Determine the number of arguments in the given pack expansion
/// type.
///
/// This routine assumes that the number of arguments in the expansion is
/// consistent across all of the unexpanded parameter packs in its pattern.
///
/// Returns an empty Optional if the type can't be expanded.
Optional<unsigned> getNumArgumentsInExpansion(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Determine whether the given declarator contains any unexpanded
/// parameter packs.
///
/// This routine is used by the parser to disambiguate function declarators
/// with an ellipsis prior to the ')', e.g.,
///
/// \code
/// void f(T...);
/// \endcode
///
/// To determine whether we have an (unnamed) function parameter pack or
/// a variadic function.
///
/// \returns true if the declarator contains any unexpanded parameter packs,
/// false otherwise.
bool containsUnexpandedParameterPacks(Declarator &D);
/// Returns the pattern of the pack expansion for a template argument.
///
/// \param OrigLoc The template argument to expand.
///
/// \param Ellipsis Will be set to the location of the ellipsis.
///
/// \param NumExpansions Will be set to the number of expansions that will
/// be generated from this pack expansion, if known a priori.
TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
TemplateArgumentLoc OrigLoc,
SourceLocation &Ellipsis,
Optional<unsigned> &NumExpansions) const;
/// Given a template argument that contains an unexpanded parameter pack, but
/// which has already been substituted, attempt to determine the number of
/// elements that will be produced once this argument is fully-expanded.
///
/// This is intended for use when transforming 'sizeof...(Arg)' in order to
/// avoid actually expanding the pack where possible.
Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
//===--------------------------------------------------------------------===//
// C++ Template Argument Deduction (C++ [temp.deduct])
//===--------------------------------------------------------------------===//
/// Adjust the type \p ArgFunctionType to match the calling convention,
/// noreturn, and optionally the exception specification of \p FunctionType.
/// Deduction often wants to ignore these properties when matching function
/// types.
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
bool AdjustExceptionSpec = false);
/// Describes the result of template argument deduction.
///
/// The TemplateDeductionResult enumeration describes the result of
/// template argument deduction, as returned from
/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
/// structure provides additional information about the results of
/// template argument deduction, e.g., the deduced template argument
/// list (if successful) or the specific template parameters or
/// deduced arguments that were involved in the failure.
enum TemplateDeductionResult {
/// Template argument deduction was successful.
TDK_Success = 0,
/// The declaration was invalid; do nothing.
TDK_Invalid,
/// Template argument deduction exceeded the maximum template
/// instantiation depth (which has already been diagnosed).
TDK_InstantiationDepth,
/// Template argument deduction did not deduce a value
/// for every template parameter.
TDK_Incomplete,
/// Template argument deduction did not deduce a value for every
/// expansion of an expanded template parameter pack.
TDK_IncompletePack,
/// Template argument deduction produced inconsistent
/// deduced values for the given template parameter.
TDK_Inconsistent,
/// Template argument deduction failed due to inconsistent
/// cv-qualifiers on a template parameter type that would
/// otherwise be deduced, e.g., we tried to deduce T in "const T"
/// but were given a non-const "X".
TDK_Underqualified,
/// Substitution of the deduced template argument values
/// resulted in an error.
TDK_SubstitutionFailure,
/// After substituting deduced template arguments, a dependent
/// parameter type did not match the corresponding argument.
TDK_DeducedMismatch,
/// After substituting deduced template arguments, an element of
/// a dependent parameter type did not match the corresponding element
/// of the corresponding argument (when deducing from an initializer list).
TDK_DeducedMismatchNested,
/// A non-depnedent component of the parameter did not match the
/// corresponding component of the argument.
TDK_NonDeducedMismatch,
/// When performing template argument deduction for a function
/// template, there were too many call arguments.
TDK_TooManyArguments,
/// When performing template argument deduction for a function
/// template, there were too few call arguments.
TDK_TooFewArguments,
/// The explicitly-specified template arguments were not valid
/// template arguments for the given template.
TDK_InvalidExplicitArguments,
/// Checking non-dependent argument conversions failed.
TDK_NonDependentConversionFailure,
/// Deduction failed; that's all we know.
TDK_MiscellaneousDeductionFailure,
/// CUDA Target attributes do not match.
TDK_CUDATargetMismatch
};
TemplateDeductionResult
DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult SubstituteExplicitTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo &ExplicitTemplateArgs,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
sema::TemplateDeductionInfo &Info);
/// brief A function argument from which we performed template argument
// deduction for a call.
struct OriginalCallArg {
OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
unsigned ArgIdx, QualType OriginalArgType)
: OriginalParamType(OriginalParamType),
DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
OriginalArgType(OriginalArgType) {}
QualType OriginalParamType;
bool DecomposedParam;
unsigned ArgIdx;
QualType OriginalArgType;
};
TemplateDeductionResult FinishTemplateArgumentDeduction(
FunctionTemplateDecl *FunctionTemplate,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
bool PartialOverloading = false,
llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
TemplateDeductionResult DeduceTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
bool PartialOverloading,
llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ArgFunctionType,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool IsAddressOfFunction = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
QualType ToType,
CXXConversionDecl *&Specialization,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool IsAddressOfFunction = false);
/// Substitute Replacement for \p auto in \p TypeWithAuto
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
/// Substitute Replacement for auto in TypeWithAuto
TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
QualType Replacement);
/// Completely replace the \c auto in \p TypeWithAuto by
/// \p Replacement. This does not retain any \c auto type sugar.
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
/// Result type of DeduceAutoType.
enum DeduceAutoResult {
DAR_Succeeded,
DAR_Failed,
DAR_FailedAlreadyDiagnosed
};
DeduceAutoResult
DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
Optional<unsigned> DependentDeductionDepth = None);
DeduceAutoResult
DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
Optional<unsigned> DependentDeductionDepth = None);
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
bool Diagnose = true);
/// Declare implicit deduction guides for a class template if we've
/// not already done so.
void DeclareImplicitDeductionGuides(TemplateDecl *Template,
SourceLocation Loc);
QualType DeduceTemplateSpecializationFromInitializer(
TypeSourceInfo *TInfo, const InitializedEntity &Entity,
const InitializationKind &Kind, MultiExprArg Init);
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
QualType Type, TypeSourceInfo *TSI,
SourceRange Range, bool DirectInit,
Expr *Init);
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
SourceLocation ReturnLoc,
Expr *&RetExpr, AutoType *AT);
FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
FunctionTemplateDecl *FT2,
SourceLocation Loc,
TemplatePartialOrderingContext TPOC,
unsigned NumCallArguments1,
unsigned NumCallArguments2);
UnresolvedSetIterator
getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
TemplateSpecCandidateSet &FailedCandidates,
SourceLocation Loc,
const PartialDiagnostic &NoneDiag,
const PartialDiagnostic &AmbigDiag,
const PartialDiagnostic &CandidateDiag,
bool Complain = true, QualType TargetType = QualType());
ClassTemplatePartialSpecializationDecl *
getMoreSpecializedPartialSpecialization(
ClassTemplatePartialSpecializationDecl *PS1,
ClassTemplatePartialSpecializationDecl *PS2,
SourceLocation Loc);
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
sema::TemplateDeductionInfo &Info);
VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
VarTemplatePartialSpecializationDecl *PS1,
VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
sema::TemplateDeductionInfo &Info);
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
bool OnlyDeduced,
unsigned Depth,
llvm::SmallBitVector &Used);
void MarkDeducedTemplateParameters(
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced) {
return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
}
static void MarkDeducedTemplateParameters(ASTContext &Ctx,
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced);
//===--------------------------------------------------------------------===//
// C++ Template Instantiation
//
MultiLevelTemplateArgumentList
getTemplateInstantiationArgs(NamedDecl *D,
const TemplateArgumentList *Innermost = nullptr,
bool RelativeToPrimary = false,
const FunctionDecl *Pattern = nullptr);
/// A context in which code is being synthesized (where a source location
/// alone is not sufficient to identify the context). This covers template
/// instantiation and various forms of implicitly-generated functions.
struct CodeSynthesisContext {
/// The kind of template instantiation we are performing
enum SynthesisKind {
/// We are instantiating a template declaration. The entity is
/// the declaration we're instantiating (e.g., a CXXRecordDecl).
TemplateInstantiation,
/// We are instantiating a default argument for a template
/// parameter. The Entity is the template parameter whose argument is
/// being instantiated, the Template is the template, and the
/// TemplateArgs/NumTemplateArguments provide the template arguments as
/// specified.
DefaultTemplateArgumentInstantiation,
/// We are instantiating a default argument for a function.
/// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
/// provides the template arguments as specified.
DefaultFunctionArgumentInstantiation,
/// We are substituting explicit template arguments provided for
/// a function template. The entity is a FunctionTemplateDecl.
ExplicitTemplateArgumentSubstitution,
/// We are substituting template argument determined as part of
/// template argument deduction for either a class template
/// partial specialization or a function template. The
/// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
/// a TemplateDecl.
DeducedTemplateArgumentSubstitution,
/// We are substituting prior template arguments into a new
/// template parameter. The template parameter itself is either a
/// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
PriorTemplateArgumentSubstitution,
/// We are checking the validity of a default template argument that
/// has been used when naming a template-id.
DefaultTemplateArgumentChecking,
/// We are computing the exception specification for a defaulted special
/// member function.
ExceptionSpecEvaluation,
/// We are instantiating the exception specification for a function
/// template which was deferred until it was needed.
ExceptionSpecInstantiation,
/// We are declaring an implicit special member function.
DeclaringSpecialMember,
/// We are defining a synthesized function (such as a defaulted special
/// member).
DefiningSynthesizedFunction,
/// Added for Template instantiation observation.
/// Memoization means we are _not_ instantiating a template because
/// it is already instantiated (but we entered a context where we
/// would have had to if it was not already instantiated).
Memoization
} Kind;
/// Was the enclosing context a non-instantiation SFINAE context?
bool SavedInNonInstantiationSFINAEContext;
/// The point of instantiation or synthesis within the source code.
SourceLocation PointOfInstantiation;
/// The entity that is being synthesized.
Decl *Entity;
/// The template (or partial specialization) in which we are
/// performing the instantiation, for substitutions of prior template
/// arguments.
NamedDecl *Template;
/// The list of template arguments we are substituting, if they
/// are not part of the entity.
const TemplateArgument *TemplateArgs;
// FIXME: Wrap this union around more members, or perhaps store the
// kind-specific members in the RAII object owning the context.
union {
/// The number of template arguments in TemplateArgs.
unsigned NumTemplateArgs;
/// The special member being declared or defined.
CXXSpecialMember SpecialMember;
};
ArrayRef<TemplateArgument> template_arguments() const {
assert(Kind != DeclaringSpecialMember);
return {TemplateArgs, NumTemplateArgs};
}
/// The template deduction info object associated with the
/// substitution or checking of explicit or deduced template arguments.
sema::TemplateDeductionInfo *DeductionInfo;
/// The source range that covers the construct that cause
/// the instantiation, e.g., the template-id that causes a class
/// template instantiation.
SourceRange InstantiationRange;
CodeSynthesisContext()
: Kind(TemplateInstantiation),
SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
DeductionInfo(nullptr) {}
/// Determines whether this template is an actual instantiation
/// that should be counted toward the maximum instantiation depth.
bool isInstantiationRecord() const;
};
/// List of active code synthesis contexts.
///
/// This vector is treated as a stack. As synthesis of one entity requires
/// synthesis of another, additional contexts are pushed onto the stack.
SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
/// Specializations whose definitions are currently being instantiated.
llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
/// Non-dependent types used in templates that have already been instantiated
/// by some template instantiation.
llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
/// Extra modules inspected when performing a lookup during a template
/// instantiation. Computed lazily.
SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
/// Cache of additional modules that should be used for name lookup
/// within the current template instantiation. Computed lazily; use
/// getLookupModules() to get a complete set.
llvm::DenseSet<Module*> LookupModulesCache;
/// Get the set of additional modules that should be checked during
/// name lookup. A module and its imports become visible when instanting a
/// template defined within it.
llvm::DenseSet<Module*> &getLookupModules();
/// Map from the most recent declaration of a namespace to the most
/// recent visible declaration of that namespace.
llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
/// Whether we are in a SFINAE context that is not associated with
/// template instantiation.
///
/// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
/// of a template instantiation or template argument deduction.
bool InNonInstantiationSFINAEContext;
/// The number of \p CodeSynthesisContexts that are not template
/// instantiations and, therefore, should not be counted as part of the
/// instantiation depth.
///
/// When the instantiation depth reaches the user-configurable limit
/// \p LangOptions::InstantiationDepth we will abort instantiation.
// FIXME: Should we have a similar limit for other forms of synthesis?
unsigned NonInstantiationEntries;
/// The depth of the context stack at the point when the most recent
/// error or warning was produced.
///
/// This value is used to suppress printing of redundant context stacks
/// when there are multiple errors or warnings in the same instantiation.
// FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
unsigned LastEmittedCodeSynthesisContextDepth = 0;
/// The template instantiation callbacks to trace or track
/// instantiations (objects can be chained).
///
/// This callbacks is used to print, trace or track template
/// instantiations as they are being constructed.
std::vector<std::unique_ptr<TemplateInstantiationCallback>>
TemplateInstCallbacks;
/// The current index into pack expansion arguments that will be
/// used for substitution of parameter packs.
///
/// The pack expansion index will be -1 to indicate that parameter packs
/// should be instantiated as themselves. Otherwise, the index specifies
/// which argument within the parameter pack will be used for substitution.
int ArgumentPackSubstitutionIndex;
/// RAII object used to change the argument pack substitution index
/// within a \c Sema object.
///
/// See \c ArgumentPackSubstitutionIndex for more information.
class ArgumentPackSubstitutionIndexRAII {
Sema &Self;
int OldSubstitutionIndex;
public:
ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
: Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
}
~ArgumentPackSubstitutionIndexRAII() {
Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
}
};
friend class ArgumentPackSubstitutionRAII;
/// For each declaration that involved template argument deduction, the
/// set of diagnostics that were suppressed during that template argument
/// deduction.
///
/// FIXME: Serialize this structure to the AST file.
typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
SuppressedDiagnosticsMap;
SuppressedDiagnosticsMap SuppressedDiagnostics;
/// A stack object to be created when performing template
/// instantiation.
///
/// Construction of an object of type \c InstantiatingTemplate
/// pushes the current instantiation onto the stack of active
/// instantiations. If the size of this stack exceeds the maximum
/// number of recursive template instantiations, construction
/// produces an error and evaluates true.
///
/// Destruction of this object will pop the named instantiation off
/// the stack.
struct InstantiatingTemplate {
/// Note that we are instantiating a class template,
/// function template, variable template, alias template,
/// or a member thereof.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Decl *Entity,
SourceRange InstantiationRange = SourceRange());
struct ExceptionSpecification {};
/// Note that we are instantiating an exception specification
/// of a function template.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionDecl *Entity, ExceptionSpecification,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating a default argument in a
/// template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateParameter Param, TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// Note that we are substituting either explicitly-specified or
/// deduced template arguments during function template argument deduction.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionTemplateDecl *FunctionTemplate,
ArrayRef<TemplateArgument> TemplateArgs,
CodeSynthesisContext::SynthesisKind Kind,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a class template declaration.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a class template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ClassTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a variable template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
VarTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating a default argument for a function
/// parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ParmVarDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// Note that we are substituting prior template arguments into a
/// non-type parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
NonTypeTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// Note that we are substituting prior template arguments into a
/// template template parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
TemplateTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// Note that we are checking the default template argument
/// against the template parameter for a given template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
NamedDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// Note that we have finished instantiating this template.
void Clear();
~InstantiatingTemplate() { Clear(); }
/// Determines whether we have exceeded the maximum
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
/// Determine whether we are already instantiating this
/// specialization in some surrounding active instantiation.
bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
private:
Sema &SemaRef;
bool Invalid;
bool AlreadyInstantiating;
bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
SourceRange InstantiationRange);
InstantiatingTemplate(
Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
Decl *Entity, NamedDecl *Template = nullptr,
ArrayRef<TemplateArgument> TemplateArgs = None,
sema::TemplateDeductionInfo *DeductionInfo = nullptr);
InstantiatingTemplate(const InstantiatingTemplate&) = delete;
InstantiatingTemplate&
operator=(const InstantiatingTemplate&) = delete;
};
void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
void popCodeSynthesisContext();
/// Determine whether we are currently performing template instantiation.
bool inTemplateInstantiation() const {
return CodeSynthesisContexts.size() > NonInstantiationEntries;
}
void PrintContextStack() {
if (!CodeSynthesisContexts.empty() &&
CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
PrintInstantiationStack();
LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
}
if (PragmaAttributeCurrentTargetDecl)
PrintPragmaAttributeInstantiationPoint();
}
void PrintInstantiationStack();
void PrintPragmaAttributeInstantiationPoint();
/// Determines whether we are currently in a context where
/// template argument substitution failures are not considered
/// errors.
///
/// \returns An empty \c Optional if we're not in a SFINAE context.
/// Otherwise, contains a pointer that, if non-NULL, contains the nearest
/// template-deduction context object, which can be used to capture
/// diagnostics that will be suppressed.
Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
/// Determines whether we are currently in a context that
/// is not evaluated as per C++ [expr] p5.
bool isUnevaluatedContext() const {
assert(!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context");
return ExprEvalContexts.back().isUnevaluated();
}
/// RAII class used to determine whether SFINAE has
/// trapped any errors that occur during template argument
/// deduction.
class SFINAETrap {
Sema &SemaRef;
unsigned PrevSFINAEErrors;
bool PrevInNonInstantiationSFINAEContext;
bool PrevAccessCheckingSFINAE;
bool PrevLastDiagnosticIgnored;
public:
explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
: SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
PrevInNonInstantiationSFINAEContext(
SemaRef.InNonInstantiationSFINAEContext),
PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
PrevLastDiagnosticIgnored(
SemaRef.getDiagnostics().isLastDiagnosticIgnored())
{
if (!SemaRef.isSFINAEContext())
SemaRef.InNonInstantiationSFINAEContext = true;
SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
}
~SFINAETrap() {
SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
SemaRef.InNonInstantiationSFINAEContext
= PrevInNonInstantiationSFINAEContext;
SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
SemaRef.getDiagnostics().setLastDiagnosticIgnored(
PrevLastDiagnosticIgnored);
}
/// Determine whether any SFINAE errors have been trapped.
bool hasErrorOccurred() const {
return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
}
};
/// RAII class used to indicate that we are performing provisional
/// semantic analysis to determine the validity of a construct, so
/// typo-correction and diagnostics in the immediate context (not within
/// implicitly-instantiated templates) should be suppressed.
class TentativeAnalysisScope {
Sema &SemaRef;
// FIXME: Using a SFINAETrap for this is a hack.
SFINAETrap Trap;
bool PrevDisableTypoCorrection;
public:
explicit TentativeAnalysisScope(Sema &SemaRef)
: SemaRef(SemaRef), Trap(SemaRef, true),
PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
SemaRef.DisableTypoCorrection = true;
}
~TentativeAnalysisScope() {
SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
}
};
/// The current instantiation scope used to store local
/// variables.
LocalInstantiationScope *CurrentInstantiationScope;
/// Tracks whether we are in a context where typo correction is
/// disabled.
bool DisableTypoCorrection;
/// The number of typos corrected by CorrectTypo.
unsigned TyposCorrected;
typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
/// A cache containing identifiers for which typo correction failed and
/// their locations, so that repeated attempts to correct an identifier in a
/// given location are ignored if typo correction already failed for it.
IdentifierSourceLocations TypoCorrectionFailures;
/// Worker object for performing CFG-based warnings.
sema::AnalysisBasedWarnings AnalysisWarnings;
threadSafety::BeforeSet *ThreadSafetyDeclCache;
/// An entity for which implicit template instantiation is required.
///
/// The source location associated with the declaration is the first place in
/// the source code where the declaration was "used". It is not necessarily
/// the point of instantiation (which will be either before or after the
/// namespace-scope declaration that triggered this implicit instantiation),
/// However, it is the location that diagnostics should generally refer to,
/// because users will need to know what code triggered the instantiation.
typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
/// The queue of implicit template instantiations that are required
/// but have not yet been performed.
std::deque<PendingImplicitInstantiation> PendingInstantiations;
/// Queue of implicit template instantiations that cannot be performed
/// eagerly.
SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
class GlobalEagerInstantiationScope {
public:
GlobalEagerInstantiationScope(Sema &S, bool Enabled)
: S(S), Enabled(Enabled) {
if (!Enabled) return;
SavedPendingInstantiations.swap(S.PendingInstantiations);
SavedVTableUses.swap(S.VTableUses);
}
void perform() {
if (Enabled) {
S.DefineUsedVTables();
S.PerformPendingInstantiations();
}
}
~GlobalEagerInstantiationScope() {
if (!Enabled) return;
// Restore the set of pending vtables.
assert(S.VTableUses.empty() &&
"VTableUses should be empty before it is discarded.");
S.VTableUses.swap(SavedVTableUses);
// Restore the set of pending implicit instantiations.
assert(S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded.");
S.PendingInstantiations.swap(SavedPendingInstantiations);
}
private:
Sema &S;
SmallVector<VTableUse, 16> SavedVTableUses;
std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
bool Enabled;
};
/// The queue of implicit template instantiations that are required
/// and must be performed within the current local scope.
///
/// This queue is only used for member functions of local classes in
/// templates, which must be instantiated in the same scope as their
/// enclosing function, so that they can reference function-local
/// types, static variables, enumerators, etc.
std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
class LocalEagerInstantiationScope {
public:
LocalEagerInstantiationScope(Sema &S) : S(S) {
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
~LocalEagerInstantiationScope() {
assert(S.PendingLocalImplicitInstantiations.empty() &&
"there shouldn't be any pending local implicit instantiations");
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
private:
Sema &S;
std::deque<PendingImplicitInstantiation>
SavedPendingLocalImplicitInstantiations;
};
/// A helper class for building up ExtParameterInfos.
class ExtParameterInfoBuilder {
SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
bool HasInteresting = false;
public:
/// Set the ExtParameterInfo for the parameter at the given index,
///
void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
assert(Infos.size() <= index);
Infos.resize(index);
Infos.push_back(info);
if (!HasInteresting)
HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
}
/// Return a pointer (suitable for setting in an ExtProtoInfo) to the
/// ExtParameterInfo array we've built up.
const FunctionProtoType::ExtParameterInfo *
getPointerOrNull(unsigned numParams) {
if (!HasInteresting) return nullptr;
Infos.resize(numParams);
return Infos.data();
}
};
void PerformPendingInstantiations(bool LocalOnly = false);
TypeSourceInfo *SubstType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity,
bool AllowDeducedTST = false);
QualType SubstType(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstType(TypeLoc TL,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc,
DeclarationName Entity,
CXXRecordDecl *ThisContext,
Qualifiers ThisTypeQuals);
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
const MultiLevelTemplateArgumentList &Args);
bool SubstExceptionSpec(SourceLocation Loc,
FunctionProtoType::ExceptionSpecInfo &ESI,
SmallVectorImpl<QualType> &ExceptionStorage,
const MultiLevelTemplateArgumentList &Args);
ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
int indexAdjustment,
Optional<unsigned> NumExpansions,
bool ExpectParameterPack);
bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<QualType> &ParamTypes,
SmallVectorImpl<ParmVarDecl *> *OutParams,
ExtParameterInfoBuilder &ParamInfos);
ExprResult SubstExpr(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Substitute the given template arguments into a list of
/// expressions, expanding pack expansions if required.
///
/// \param Exprs The list of expressions to substitute into.
///
/// \param IsCall Whether this is some form of call, in which case
/// default arguments will be dropped.
///
/// \param TemplateArgs The set of template arguments to substitute.
///
/// \param Outputs Will receive all of the substituted arguments.
///
/// \returns true if an error occurred, false otherwise.
bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<Expr *> &Outputs);
StmtResult SubstStmt(Stmt *S,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateParameterList *
SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
Decl *SubstDecl(Decl *D, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
ExprResult SubstInitializer(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool CXXDirectInit);
bool
SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool
InstantiateClass(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK,
bool Complain = true);
bool InstantiateEnum(SourceLocation PointOfInstantiation,
EnumDecl *Instantiation, EnumDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
bool InstantiateInClassInitializer(
SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
struct LateInstantiatedAttribute {
const Attr *TmplAttr;
LocalInstantiationScope *Scope;
Decl *NewDecl;
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
Decl *D)
: TmplAttr(A), Scope(S), NewDecl(D)
{ }
};
typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
void
InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
bool usesPartialOrExplicitSpecialization(
SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
bool
InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK,
bool Complain = true);
void InstantiateClassMembers(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
void InstantiateClassTemplateSpecializationMembers(
SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK);
NestedNameSpecifierLoc
SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
const MultiLevelTemplateArgumentList &TemplateArgs);
DeclarationNameInfo
SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateName
SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
SourceLocation Loc,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
TemplateArgumentListInfo &Result,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
FunctionDecl *Function);
FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
const TemplateArgumentList *Args,
SourceLocation Loc);
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
FunctionDecl *Function,
bool Recursive = false,
bool DefinitionRequired = false,
bool AtEndOfTU = false);
VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
VarTemplateDecl *VarTemplate, VarDecl *FromVar,
const TemplateArgumentList &TemplateArgList,
const TemplateArgumentListInfo &TemplateArgsInfo,
SmallVectorImpl<TemplateArgument> &Converted,
SourceLocation PointOfInstantiation, void *InsertPos,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *StartingScope = nullptr);
VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
const MultiLevelTemplateArgumentList &TemplateArgs);
void
BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs,
LateInstantiatedAttrVec *LateAttrs,
DeclContext *Owner,
LocalInstantiationScope *StartingScope,
bool InstantiatingVarTemplate = false,
VarTemplateSpecializationDecl *PrevVTSD = nullptr);
void InstantiateVariableInitializer(
VarDecl *Var, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
VarDecl *Var, bool Recursive = false,
bool DefinitionRequired = false,
bool AtEndOfTU = false);
void InstantiateMemInitializers(CXXConstructorDecl *New,
const CXXConstructorDecl *Tmpl,
const MultiLevelTemplateArgumentList &TemplateArgs);
NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool FindingInstantiatedContext = false);
DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
const MultiLevelTemplateArgumentList &TemplateArgs);
// Objective-C declarations.
enum ObjCContainerKind {
OCK_None = -1,
OCK_Interface = 0,
OCK_Protocol,
OCK_Category,
OCK_ClassExtension,
OCK_Implementation,
OCK_CategoryImplementation
};
ObjCContainerKind getObjCContainerKind() const;
DeclResult actOnObjCTypeParam(Scope *S,
ObjCTypeParamVariance variance,
SourceLocation varianceLoc,
unsigned index,
IdentifierInfo *paramName,
SourceLocation paramLoc,
SourceLocation colonLoc,
ParsedType typeBound);
ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
ArrayRef<Decl *> typeParams,
SourceLocation rAngleLoc);
void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
Decl *ActOnStartClassInterface(
Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
IdentifierInfo *SuperName, SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList);
void ActOnSuperClassOfClassInterface(Scope *S,
SourceLocation AtInterfaceLoc,
ObjCInterfaceDecl *IDecl,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperName,
SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs,
SourceRange SuperTypeArgsRange);
void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
SmallVectorImpl<SourceLocation> &ProtocolLocs,
IdentifierInfo *SuperName,
SourceLocation SuperLoc);
Decl *ActOnCompatibilityAlias(
SourceLocation AtCompatibilityAliasLoc,
IdentifierInfo *AliasName, SourceLocation AliasLocation,
IdentifierInfo *ClassName, SourceLocation ClassLocation);
bool CheckForwardProtocolDeclarationForCircularDependency(
IdentifierInfo *PName,
SourceLocation &PLoc, SourceLocation PrevLoc,
const ObjCList<ObjCProtocolDecl> &PList);
Decl *ActOnStartProtocolInterface(
SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
Decl *ActOnStartCategoryInterface(
SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperClassname,
SourceLocation SuperClassLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *CatName,
SourceLocation CatLoc,
const ParsedAttributesView &AttrList);
DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
ArrayRef<Decl *> Decls);
DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
IdentifierInfo **IdentList,
SourceLocation *IdentLocs,
ArrayRef<ObjCTypeParamList *> TypeParamLists,
unsigned NumElts);
DeclGroupPtrTy
ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
ArrayRef<IdentifierLocPair> IdentList,
const ParsedAttributesView &attrList);
void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
ArrayRef<IdentifierLocPair> ProtocolId,
SmallVectorImpl<Decl *> &Protocols);
void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
SourceLocation ProtocolLoc,
IdentifierInfo *TypeArgId,
SourceLocation TypeArgLoc,
bool SelectProtocolFirst = false);
/// Given a list of identifiers (and their locations), resolve the
/// names to either Objective-C protocol qualifiers or type
/// arguments, as appropriate.
void actOnObjCTypeArgsOrProtocolQualifiers(
Scope *S,
ParsedType baseType,
SourceLocation lAngleLoc,
ArrayRef<IdentifierInfo *> identifiers,
ArrayRef<SourceLocation> identifierLocs,
SourceLocation rAngleLoc,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SourceLocation &protocolRAngleLoc,
bool warnOnIncompleteProtocols);
/// Build a an Objective-C protocol-qualified 'id' type where no
/// base type was specified.
TypeResult actOnObjCProtocolQualifierType(
SourceLocation lAngleLoc,
ArrayRef<Decl *> protocols,
ArrayRef<SourceLocation> protocolLocs,
SourceLocation rAngleLoc);
/// Build a specialized and/or protocol-qualified Objective-C type.
TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
Scope *S,
SourceLocation Loc,
ParsedType BaseType,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<ParsedType> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<Decl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc);
/// Build an Objective-C type parameter type.
QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Build an Objective-C object pointer type.
QualType BuildObjCObjectType(QualType BaseType,
SourceLocation Loc,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<TypeSourceInfo *> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Ensure attributes are consistent with type.
/// \param [in, out] Attributes The attributes to check; they will
/// be modified to be consistent with \p PropertyTy.
void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
SourceLocation Loc,
unsigned &Attributes,
bool propertyInPrimaryClass);
/// Process the specified property declaration and create decls for the
/// setters and getters as needed.
/// \param property The property declaration being processed
void ProcessPropertyDecl(ObjCPropertyDecl *property);
void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
ObjCPropertyDecl *SuperProperty,
const IdentifierInfo *Name,
bool OverridingProtocolProperty);
void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
ObjCInterfaceDecl *ID);
Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
ArrayRef<Decl *> allMethods = None,
ArrayRef<DeclGroupPtrTy> allTUVars = None);
Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD, ObjCDeclSpec &ODS,
Selector GetterSel, Selector SetterSel,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
Decl *ActOnPropertyImplDecl(Scope *S,
SourceLocation AtLoc,
SourceLocation PropertyLoc,
bool ImplKind,
IdentifierInfo *PropertyId,
IdentifierInfo *PropertyIvar,
SourceLocation PropertyIvarLoc,
ObjCPropertyQueryKind QueryKind);
enum ObjCSpecialMethodKind {
OSMK_None,
OSMK_Alloc,
OSMK_New,
OSMK_Copy,
OSMK_RetainingInit,
OSMK_NonRetainingInit
};
struct ObjCArgInfo {
IdentifierInfo *Name;
SourceLocation NameLoc;
// The Type is null if no type was specified, and the DeclSpec is invalid
// in this case.
ParsedType Type;
ObjCDeclSpec DeclSpec;
/// ArgAttrs - Attribute list for this argument.
ParsedAttributesView ArgAttrs;
};
Decl *ActOnMethodDeclaration(
Scope *S,
SourceLocation BeginLoc, // location of the + or -.
SourceLocation EndLoc, // location of the ; or {.
tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
// optional arguments. The number of types/arguments is obtained
// from the Sel.getNumArgs().
ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
unsigned CNumArgs, // c-style args
const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
bool isVariadic, bool MethodDefinition);
ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
const ObjCObjectPointerType *OPT,
bool IsInstance);
ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
bool IsInstance);
bool CheckARCMethodDecl(ObjCMethodDecl *method);
bool inferObjCARCLifetime(ValueDecl *decl);
ExprResult
HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Expr *BaseExpr,
SourceLocation OpLoc,
DeclarationName MemberName,
SourceLocation MemberLoc,
SourceLocation SuperLoc, QualType SuperType,
bool Super);
ExprResult
ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
IdentifierInfo &propertyName,
SourceLocation receiverNameLoc,
SourceLocation propertyNameLoc);
ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
/// Describes the kind of message expression indicated by a message
/// send that starts with an identifier.
enum ObjCMessageKind {
/// The message is sent to 'super'.
ObjCSuperMessage,
/// The message is an instance message.
ObjCInstanceMessage,
/// The message is a class message, and the identifier is a type
/// name.
ObjCClassMessage
};
ObjCMessageKind getObjCMessageKind(Scope *S,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsSuper,
bool HasTrailingDot,
ParsedType &ReceiverType);
ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildClassMessageImplicit(QualType ReceiverType,
bool isSuperReceiver,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnClassMessage(Scope *S,
ParsedType Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildInstanceMessage(Expr *Receiver,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
QualType ReceiverType,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnInstanceMessage(Scope *S,
Expr *Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
TypeSourceInfo *TSInfo,
Expr *SubExpr);
ExprResult ActOnObjCBridgedCast(Scope *S,
SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
ParsedType Type,
SourceLocation RParenLoc,
Expr *SubExpr);
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
CastKind &Kind);
bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
QualType DestType, QualType SrcType,
ObjCInterfaceDecl *&RelatedClass,
ObjCMethodDecl *&ClassMethod,
ObjCMethodDecl *&InstanceMethod,
TypedefNameDecl *&TDNDecl,
bool CfToNs, bool Diagnose = true);
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
QualType DestType, QualType SrcType,
Expr *&SrcExpr, bool Diagnose = true);
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
bool Diagnose = true);
bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
/// Check whether the given new method is a valid override of the
/// given overridden method, and set any properties that should be inherited.
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
const ObjCMethodDecl *Overridden);
/// Describes the compatibility of a result type with its method.
enum ResultTypeCompatibilityKind {
RTC_Compatible,
RTC_Incompatible,
RTC_Unknown
};
void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
ObjCInterfaceDecl *CurrentClass,
ResultTypeCompatibilityKind RTC);
enum PragmaOptionsAlignKind {
POAK_Native, // #pragma options align=native
POAK_Natural, // #pragma options align=natural
POAK_Packed, // #pragma options align=packed
POAK_Power, // #pragma options align=power
POAK_Mac68k, // #pragma options align=mac68k
POAK_Reset // #pragma options align=reset
};
/// ActOnPragmaClangSection - Called on well formed \#pragma clang section
void ActOnPragmaClangSection(SourceLocation PragmaLoc,
PragmaClangSectionAction Action,
PragmaClangSectionKind SecKind, StringRef SecName);
/// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
SourceLocation PragmaLoc);
/// ActOnPragmaPack - Called on well formed \#pragma pack(...).
void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
StringRef SlotLabel, Expr *Alignment);
enum class PragmaPackDiagnoseKind {
NonDefaultStateAtInclude,
ChangedStateAtExit
};
void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
SourceLocation IncludeLoc);
void DiagnoseUnterminatedPragmaPack();
/// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
/// ActOnPragmaMSComment - Called on well formed
/// \#pragma comment(kind, "arg").
void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
StringRef Arg);
/// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
/// pointers_to_members(representation method[, general purpose
/// representation]).
void ActOnPragmaMSPointersToMembers(
LangOptions::PragmaMSPointersToMembersKind Kind,
SourceLocation PragmaLoc);
/// Called on well formed \#pragma vtordisp().
void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
SourceLocation PragmaLoc,
MSVtorDispAttr::Mode Value);
enum PragmaSectionKind {
PSK_DataSeg,
PSK_BSSSeg,
PSK_ConstSeg,
PSK_CodeSeg,
};
bool UnifySection(StringRef SectionName,
int SectionFlags,
DeclaratorDecl *TheDecl);
bool UnifySection(StringRef SectionName,
int SectionFlags,
SourceLocation PragmaSectionLocation);
/// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
StringLiteral *SegmentName,
llvm::StringRef PragmaName);
/// Called on well formed \#pragma section().
void ActOnPragmaMSSection(SourceLocation PragmaLocation,
int SectionFlags, StringLiteral *SegmentName);
/// Called on well-formed \#pragma init_seg().
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
StringLiteral *SegmentName);
/// Called on #pragma clang __debug dump II
void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
/// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
StringRef Value);
/// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
void ActOnPragmaUnused(const Token &Identifier,
Scope *curScope,
SourceLocation PragmaLoc);
/// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
void ActOnPragmaVisibility(const IdentifierInfo* VisType,
SourceLocation PragmaLoc);
NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
SourceLocation Loc);
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
/// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
void ActOnPragmaWeakID(IdentifierInfo* WeakName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc);
/// ActOnPragmaRedefineExtname - Called on well formed
/// \#pragma redefine_extname oldname newname.
void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaFPContract - Called on well formed
/// \#pragma {STDC,OPENCL} FP_CONTRACT and
/// \#pragma clang fp contract
void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
/// ActOnPragmaFenvAccess - Called on well formed
/// \#pragma STDC FENV_ACCESS
void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC);
/// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
/// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
void AddAlignmentAttributesForRecord(RecordDecl *RD);
/// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
void AddMsStructLayoutForRecord(RecordDecl *RD);
/// FreePackedContext - Deallocate and null out PackContext.
void FreePackedContext();
/// PushNamespaceVisibilityAttr - Note that we've entered a
/// namespace with a visibility attribute.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
SourceLocation Loc);
/// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
/// add an appropriate visibility attribute.
void AddPushedVisibilityAttribute(Decl *RD);
/// PopPragmaVisibility - Pop the top element of the visibility stack; used
/// for '\#pragma GCC visibility' and visibility attributes on namespaces.
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
/// FreeVisContext - Deallocate and null out VisContext.
void FreeVisContext();
/// AddCFAuditedAttribute - Check whether we're currently within
/// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
/// the appropriate attribute.
void AddCFAuditedAttribute(Decl *D);
void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
SourceLocation PragmaLoc,
attr::ParsedSubjectMatchRuleSet Rules);
void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
const IdentifierInfo *Namespace);
/// Called on well-formed '\#pragma clang attribute pop'.
void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
const IdentifierInfo *Namespace);
/// Adds the attributes that have been specified using the
/// '\#pragma clang attribute push' directives to the given declaration.
void AddPragmaAttributes(Scope *S, Decl *D);
void DiagnoseUnterminatedPragmaAttribute();
/// Called on well formed \#pragma clang optimize.
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
/// Get the location for the currently active "\#pragma clang optimize
/// off". If this location is invalid, then the state of the pragma is "on".
SourceLocation getOptimizeOffPragmaLocation() const {
return OptimizeOffPragmaLocation;
}
/// Only called on function definitions; if there is a pragma in scope
/// with the effect of a range-based optnone, consider marking the function
/// with attribute optnone.
void AddRangeBasedOptnone(FunctionDecl *FD);
/// Adds the 'optnone' attribute to the function declaration if there
/// are no conflicts; Loc represents the location causing the 'optnone'
/// attribute to be added (usually because of a pragma).
void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
template <typename AttrType>
bool checkRangedIntegralArgument(Expr *E, const AttrType *TmpAttr,
ExprResult &Result);
template <typename AttrType>
void AddOneConstantValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
unsigned SpellingListIndex);
template <typename AttrType>
void AddOneConstantPowerTwoValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
unsigned SpellingListIndex);
/// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
unsigned SpellingListIndex, bool IsPackExpansion);
void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
unsigned SpellingListIndex, bool IsPackExpansion);
/// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
/// declaration.
void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
unsigned SpellingListIndex);
/// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
/// declaration.
void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
unsigned SpellingListIndex);
/// AddAlignValueAttr - Adds an align_value attribute to a particular
/// declaration.
void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
unsigned SpellingListIndex);
/// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
/// declaration.
void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
Expr *MinBlocks, unsigned SpellingListIndex);
/// AddModeAttr - Adds a mode attribute to a particular declaration.
void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
unsigned SpellingListIndex, bool InInstantiation = false);
void AddParameterABIAttr(SourceRange AttrRange, Decl *D,
ParameterABI ABI, unsigned SpellingListIndex);
enum class RetainOwnershipKind {NS, CF, OS};
void AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex,
RetainOwnershipKind K, bool IsTemplateInstantiation);
/// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
/// attribute to a particular declaration.
void addAMDGPUFlatWorkGroupSizeAttr(SourceRange AttrRange, Decl *D, Expr *Min,
Expr *Max, unsigned SpellingListIndex);
/// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
/// particular declaration.
void addAMDGPUWavesPerEUAttr(SourceRange AttrRange, Decl *D, Expr *Min,
Expr *Max, unsigned SpellingListIndex);
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
//===--------------------------------------------------------------------===//
// C++ Coroutines TS
//
bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
StringRef Keyword);
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
bool IsImplicit = false);
ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
UnresolvedLookupExpr* Lookup);
ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
bool IsImplicit = false);
StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
bool buildCoroutineParameterMoves(SourceLocation Loc);
VarDecl *buildCoroutinePromise(SourceLocation Loc);
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
SourceLocation FuncLoc);
//===--------------------------------------------------------------------===//
// OpenCL extensions.
//
private:
std::string CurrOpenCLExtension;
/// Extensions required by an OpenCL type.
llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
/// Extensions required by an OpenCL declaration.
llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
public:
llvm::StringRef getCurrentOpenCLExtension() const {
return CurrOpenCLExtension;
}
/// Check if a function declaration \p FD associates with any
/// extensions present in OpenCLDeclExtMap and if so return the
/// extension(s) name(s).
std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
/// Check if a function type \p FT associates with any
/// extensions present in OpenCLTypeExtMap and if so return the
/// extension(s) name(s).
std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
/// Find an extension in an appropriate extension map and return its name
template<typename T, typename MapT>
std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
void setCurrentOpenCLExtension(llvm::StringRef Ext) {
CurrOpenCLExtension = Ext;
}
/// Set OpenCL extensions for a type which can only be used when these
/// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
/// \param Exts A space separated list of OpenCL extensions.
void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
/// Set OpenCL extensions for a declaration which can only be
/// used when these OpenCL extensions are enabled. If \p Exts is empty, do
/// nothing.
/// \param Exts A space separated list of OpenCL extensions.
void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
/// Set current OpenCL extensions for a type which can only be used
/// when these OpenCL extensions are enabled. If current OpenCL extension is
/// empty, do nothing.
void setCurrentOpenCLExtensionForType(QualType T);
/// Set current OpenCL extensions for a declaration which
/// can only be used when these OpenCL extensions are enabled. If current
/// OpenCL extension is empty, do nothing.
void setCurrentOpenCLExtensionForDecl(Decl *FD);
bool isOpenCLDisabledDecl(Decl *FD);
/// Check if type \p T corresponding to declaration specifier \p DS
/// is disabled due to required OpenCL extensions being disabled. If so,
/// emit diagnostics.
/// \return true if type is disabled.
bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
/// Check if declaration \p D used by expression \p E
/// is disabled due to required OpenCL extensions being disabled. If so,
/// emit diagnostics.
/// \return true if type is disabled.
bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
//===--------------------------------------------------------------------===//
// OpenMP directives and clauses.
//
private:
void *VarDataSharingAttributesStack;
/// Number of nested '#pragma omp declare target' directives.
unsigned DeclareTargetNestingLevel = 0;
/// Initialization of data-sharing attributes stack.
void InitDataSharingAttributesStack();
void DestroyDataSharingAttributesStack();
ExprResult
VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
bool StrictlyPositive = true);
/// Returns OpenMP nesting level for current directive.
unsigned getOpenMPNestingLevel() const;
/// Adjusts the function scopes index for the target-based regions.
void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
unsigned Level) const;
/// Push new OpenMP function region for non-capturing function.
void pushOpenMPFunctionRegion();
/// Pop OpenMP function region for non-capturing function.
void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
/// Check whether we're allowed to call Callee from the current function.
void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
/// Check if the expression is allowed to be used in expressions for the
/// OpenMP devices.
void checkOpenMPDeviceExpr(const Expr *E);
/// Checks if a type or a declaration is disabled due to the owning extension
/// being disabled, and emits diagnostic messages if it is disabled.
/// \param D type or declaration to be checked.
/// \param DiagLoc source location for the diagnostic message.
/// \param DiagInfo information to be emitted for the diagnostic message.
/// \param SrcRange source range of the declaration.
/// \param Map maps type or declaration to the extensions.
/// \param Selector selects diagnostic message: 0 for type and 1 for
/// declaration.
/// \return true if the type or declaration is disabled.
template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
MapT &Map, unsigned Selector = 0,
SourceRange SrcRange = SourceRange());
public:
/// Function tries to capture lambda's captured variables in the OpenMP region
/// before the original lambda is captured.
void tryCaptureOpenMPLambdas(ValueDecl *V);
/// Return true if the provided declaration \a VD should be captured by
/// reference.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const;
/// Check if the specified variable is used in one of the private
/// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
/// constructs.
VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
unsigned StopAt = 0);
ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
ExprObjectKind OK, SourceLocation Loc);
/// If the current region is a loop-based region, mark the start of the loop
/// construct.
void startOpenMPLoop();
/// Check if the specified variable is used in 'private' clause.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const;
/// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
/// for \p FD based on DSA for the provided corresponding captured declaration
/// \p D.
void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
/// Check if the specified variable is captured by 'target' directive.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const;
ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
Expr *Op);
/// Called on start of new data sharing attribute block.
void StartOpenMPDSABlock(OpenMPDirectiveKind K,
const DeclarationNameInfo &DirName, Scope *CurScope,
SourceLocation Loc);
/// Start analysis of clauses.
void StartOpenMPClause(OpenMPClauseKind K);
/// End analysis of clauses.
void EndOpenMPClause();
/// Called on end of data sharing attribute block.
void EndOpenMPDSABlock(Stmt *CurDirective);
/// Check if the current region is an OpenMP loop region and if it is,
/// mark loop control variable, used in \p Init for loop initialization, as
/// private by default.
/// \param Init First part of the for loop.
void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
// OpenMP directives and clauses.
/// Called on correct id-expression from the '#pragma omp
/// threadprivate'.
ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id,
OpenMPDirectiveKind Kind);
/// Called on well-formed '#pragma omp threadprivate'.
DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// Called on well-formed '#pragma omp allocate'.
DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
ArrayRef<Expr *> VarList,
ArrayRef<OMPClause *> Clauses,
DeclContext *Owner = nullptr);
/// Called on well-formed '#pragma omp requires'.
DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
ArrayRef<OMPClause *> ClauseList);
/// Check restrictions on Requires directive
OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
ArrayRef<OMPClause *> Clauses);
/// Check if the specified type is allowed to be used in 'omp declare
/// reduction' construct.
QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
TypeResult ParsedType);
/// Called on start of '#pragma omp declare reduction'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
Scope *S, DeclContext *DC, DeclarationName Name,
ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
/// Initialize declare reduction construct initializer.
void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
/// Finish current declare reduction construct initializer.
void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
/// Initialize declare reduction construct initializer.
/// \return omp_priv variable.
VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
/// Finish current declare reduction construct initializer.
void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
VarDecl *OmpPrivParm);
/// Called at the end of '#pragma omp declare reduction'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
/// Check variable declaration in 'omp declare mapper' construct.
TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
/// Check if the specified type is allowed to be used in 'omp declare
/// mapper' construct.
QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
TypeResult ParsedType);
/// Called on start of '#pragma omp declare mapper'.
OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
Decl *PrevDeclInScope = nullptr);
/// Build the mapper variable of '#pragma omp declare mapper'.
void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
Scope *S, QualType MapperType,
SourceLocation StartLoc,
DeclarationName VN);
/// Called at the end of '#pragma omp declare mapper'.
DeclGroupPtrTy
ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
ArrayRef<OMPClause *> ClauseList);
/// Called on the start of target region i.e. '#pragma omp declare target'.
bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
/// Called at the end of target region i.e. '#pragme omp end declare target'.
void ActOnFinishOpenMPDeclareTargetDirective();
/// Called on correct id-expression from the '#pragma omp declare target'.
void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id,
OMPDeclareTargetDeclAttr::MapTypeTy MT,
NamedDeclSetType &SameDirectiveDecls);
/// Check declaration inside target region.
void
checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
SourceLocation IdLoc = SourceLocation());
/// Return true inside OpenMP declare target region.
bool isInOpenMPDeclareTargetContext() const {
return DeclareTargetNestingLevel > 0;
}
/// Return true inside OpenMP target region.
bool isInOpenMPTargetExecutionDirective() const;
/// Return the number of captured regions created for an OpenMP directive.
static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
/// Initialization of captured region for OpenMP region.
void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
/// End of OpenMP region.
///
/// \param S Statement associated with the current OpenMP region.
/// \param Clauses List of clauses for the current OpenMP region.
///
/// \returns Statement for finished OpenMP region.
StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
StmtResult ActOnOpenMPExecutableDirective(
OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
using VarsWithInheritedDSAType =
llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
/// Called on well-formed '\#pragma omp simd' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp for' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp for simd' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp sections' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp section' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp single' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp master' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp critical' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel for' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel sections' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp task' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskyield'.
StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp barrier'.
StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskwait'.
StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskgroup'.
StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp flush'.
StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp ordered' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp atomic' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target data' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target enter data' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp target exit data' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp target parallel' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target parallel for' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp cancellation point'.
StmtResult
ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// Called on well-formed '\#pragma omp cancel'.
StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// Called on well-formed '\#pragma omp taskloop' after parsing of the
/// associated statement.
StmtResult
ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp taskloop simd' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target update'.
StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp distribute parallel for' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute parallel for simd'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target simd' after parsing of
/// the associated statement.
StmtResult
ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTeamsDistributeDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute parallel for simd'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute parallel for'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target teams distribute' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute parallel for'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute parallel for
/// simd' after parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Checks correctness of linear modifiers.
bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
SourceLocation LinLoc);
/// Checks that the specified declaration matches requirements for the linear
/// decls.
bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
OpenMPLinearClauseKind LinKind, QualType Type);
/// Called on well-formed '\#pragma omp declare simd' after parsing of
/// the associated method/function.
DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'allocator' clause.
OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'if' clause.
OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation NameModifierLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// Called on well-formed 'final' clause.
OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'num_threads' clause.
OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'safelen' clause.
OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'simdlen' clause.
OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'collapse' clause.
OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'ordered' clause.
OMPClause *
ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
SourceLocation LParenLoc = SourceLocation(),
Expr *NumForLoops = nullptr);
/// Called on well-formed 'grainsize' clause.
OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'num_tasks' clause.
OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'hint' clause.
OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
unsigned Argument,
SourceLocation ArgumentLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'default' clause.
OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'proc_bind' clause.
OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSingleExprWithArgClause(
OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
SourceLocation StartLoc, SourceLocation LParenLoc,
ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
SourceLocation EndLoc);
/// Called on well-formed 'schedule' clause.
OMPClause *ActOnOpenMPScheduleClause(
OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'nowait' clause.
OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'untied' clause.
OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'mergeable' clause.
OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'read' clause.
OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'write' clause.
OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'update' clause.
OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'capture' clause.
OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'seq_cst' clause.
OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'threads' clause.
OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'simd' clause.
OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'nogroup' clause.
OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'unified_address' clause.
OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'unified_address' clause.
OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'reverse_offload' clause.
OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'dynamic_allocators' clause.
OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'atomic_default_mem_order' clause.
OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
OMPClause *ActOnOpenMPVarListClause(
OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
CXXScopeSpec &ReductionOrMapperIdScopeSpec,
DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
OpenMPLinearClauseKind LinKind,
ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
bool IsMapTypeImplicit, SourceLocation DepLinMapLoc);
/// Called on well-formed 'allocate' clause.
OMPClause *
ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
SourceLocation StartLoc, SourceLocation ColonLoc,
SourceLocation LParenLoc, SourceLocation EndLoc);
/// Called on well-formed 'private' clause.
OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'firstprivate' clause.
OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'lastprivate' clause.
OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'shared' clause.
OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'reduction' clause.
OMPClause *ActOnOpenMPReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'task_reduction' clause.
OMPClause *ActOnOpenMPTaskReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'in_reduction' clause.
OMPClause *ActOnOpenMPInReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'linear' clause.
OMPClause *
ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
SourceLocation StartLoc, SourceLocation LParenLoc,
OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
SourceLocation ColonLoc, SourceLocation EndLoc);
/// Called on well-formed 'aligned' clause.
OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
Expr *Alignment,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// Called on well-formed 'copyin' clause.
OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'copyprivate' clause.
OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'flush' pseudo clause.
OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'depend' clause.
OMPClause *
ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'device' clause.
OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'map' clause.
OMPClause *
ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
ArrayRef<SourceLocation> MapTypeModifiersLoc,
CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId,
OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
SourceLocation MapLoc, SourceLocation ColonLoc,
ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'num_teams' clause.
OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'thread_limit' clause.
OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'priority' clause.
OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'dist_schedule' clause.
OMPClause *ActOnOpenMPDistScheduleClause(
OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
SourceLocation CommaLoc, SourceLocation EndLoc);
/// Called on well-formed 'defaultmap' clause.
OMPClause *ActOnOpenMPDefaultmapClause(
OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
SourceLocation KindLoc, SourceLocation EndLoc);
/// Called on well-formed 'to' clause.
OMPClause *
ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId,
const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'from' clause.
OMPClause *ActOnOpenMPFromClause(
ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'use_device_ptr' clause.
OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
const OMPVarListLocTy &Locs);
/// Called on well-formed 'is_device_ptr' clause.
OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
const OMPVarListLocTy &Locs);
/// The kind of conversion being performed.
enum CheckedConversionKind {
/// An implicit conversion.
CCK_ImplicitConversion,
/// A C-style cast.
CCK_CStyleCast,
/// A functional-style cast.
CCK_FunctionalCast,
/// A cast other than a C-style cast.
CCK_OtherCast,
/// A conversion for an operand of a builtin overloaded operator.
CCK_ForBuiltinOverloadedOp
};
static bool isCast(CheckedConversionKind CCK) {
return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
CCK == CCK_OtherCast;
}
/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
/// cast. If there is already an implicit cast, merge into the existing one.
/// If isLvalue, the result of the cast is an lvalue.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
ExprValueKind VK = VK_RValue,
const CXXCastPath *BasePath = nullptr,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
/// to the conversion from scalar type ScalarTy to the Boolean type.
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
/// IgnoredValueConversions - Given that an expression's result is
/// syntactically ignored, perform any conversions that are
/// required.
ExprResult IgnoredValueConversions(Expr *E);
// UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
// functions and arrays to their respective pointers (C99 6.3.2.1).
ExprResult UsualUnaryConversions(Expr *E);
/// CallExprUnaryConversions - a special case of an unary conversion
/// performed on a function designator of a call expression.
ExprResult CallExprUnaryConversions(Expr *E);
// DefaultFunctionArrayConversion - converts functions and arrays
// to their respective pointers (C99 6.3.2.1).
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
// DefaultFunctionArrayLvalueConversion - converts functions and
// arrays to their respective pointers and performs the
// lvalue-to-rvalue conversion.
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
bool Diagnose = true);
// DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
// the operand. This is DefaultFunctionArrayLvalueConversion,
// except that it assumes the operand isn't of function or array
// type.
ExprResult DefaultLvalueConversion(Expr *E);
// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
// do not have a prototype. Integer promotions are performed on each
// argument, and arguments that have type float are promoted to double.
ExprResult DefaultArgumentPromotion(Expr *E);
/// If \p E is a prvalue denoting an unmaterialized temporary, materialize
/// it as an xvalue. In C++98, the result will still be a prvalue, because
/// we don't have xvalues there.
ExprResult TemporaryMaterializationConversion(Expr *E);
// Used for emitting the right warning by DefaultVariadicArgumentPromotion
enum VariadicCallType {
VariadicFunction,
VariadicBlock,
VariadicMethod,
VariadicConstructor,
VariadicDoesNotApply
};
VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
const FunctionProtoType *Proto,
Expr *Fn);
// Used for determining in which context a type is allowed to be passed to a
// vararg function.
enum VarArgKind {
VAK_Valid,
VAK_ValidInCXX11,
VAK_Undefined,
VAK_MSVCUndefined,
VAK_Invalid
};
// Determines which VarArgKind fits an expression.
VarArgKind isValidVarArgType(const QualType &Ty);
/// Check to see if the given expression is a valid argument to a variadic
/// function, issuing a diagnostic if not.
void checkVariadicArgument(const Expr *E, VariadicCallType CT);
/// Check to see if a given expression could have '.c_str()' called on it.
bool hasCStrMethod(const Expr *E);
/// GatherArgumentsForCall - Collector argument expressions for various
/// form of call prototypes.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
const FunctionProtoType *Proto,
unsigned FirstParam, ArrayRef<Expr *> Args,
SmallVectorImpl<Expr *> &AllArgs,
VariadicCallType CallType = VariadicDoesNotApply,
bool AllowExplicit = false,
bool IsListInitialization = false);
// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
// will create a runtime trap if the resulting type is not a POD type.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
FunctionDecl *FDecl);
// UsualArithmeticConversions - performs the UsualUnaryConversions on it's
// operands and then handles various conversions that are common to binary
// operators (C99 6.3.1.8). If both operands aren't arithmetic, this
// routine returns the first non-arithmetic type found. The client is
// responsible for emitting appropriate error diagnostics.
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
bool IsCompAssign = false);
/// AssignConvertType - All of the 'assignment' semantic checks return this
/// enum to indicate whether the assignment was allowed. These checks are
/// done for simple assignments, as well as initialization, return from
/// function, argument passing, etc. The query is phrased in terms of a
/// source and destination type.
enum AssignConvertType {
/// Compatible - the types are compatible according to the standard.
Compatible,
/// PointerToInt - The assignment converts a pointer to an int, which we
/// accept as an extension.
PointerToInt,
/// IntToPointer - The assignment converts an int to a pointer, which we
/// accept as an extension.
IntToPointer,
/// FunctionVoidPointer - The assignment is between a function pointer and
/// void*, which the standard doesn't allow, but we accept as an extension.
FunctionVoidPointer,
/// IncompatiblePointer - The assignment is between two pointers types that
/// are not compatible, but we accept them as an extension.
IncompatiblePointer,
/// IncompatiblePointerSign - The assignment is between two pointers types
/// which point to integers which have a different sign, but are otherwise
/// identical. This is a subset of the above, but broken out because it's by
/// far the most common case of incompatible pointers.
IncompatiblePointerSign,
/// CompatiblePointerDiscardsQualifiers - The assignment discards
/// c/v/r qualifiers, which we accept as an extension.
CompatiblePointerDiscardsQualifiers,
/// IncompatiblePointerDiscardsQualifiers - The assignment
/// discards qualifiers that we don't permit to be discarded,
/// like address spaces.
IncompatiblePointerDiscardsQualifiers,
/// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
/// changes address spaces in nested pointer types which is not allowed.
/// For instance, converting __private int ** to __generic int ** is
/// illegal even though __private could be converted to __generic.
IncompatibleNestedPointerAddressSpaceMismatch,
/// IncompatibleNestedPointerQualifiers - The assignment is between two
/// nested pointer types, and the qualifiers other than the first two
/// levels differ e.g. char ** -> const char **, but we accept them as an
/// extension.
IncompatibleNestedPointerQualifiers,
/// IncompatibleVectors - The assignment is between two vector types that
/// have the same size, which we accept as an extension.
IncompatibleVectors,
/// IntToBlockPointer - The assignment converts an int to a block
/// pointer. We disallow this.
IntToBlockPointer,
/// IncompatibleBlockPointer - The assignment is between two block
/// pointers types that are not compatible.
IncompatibleBlockPointer,
/// IncompatibleObjCQualifiedId - The assignment is between a qualified
/// id type and something else (that is incompatible with it). For example,
/// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
IncompatibleObjCQualifiedId,
/// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
/// object with __weak qualifier.
IncompatibleObjCWeakRef,
/// Incompatible - We reject this conversion outright, it is invalid to
/// represent it in the AST.
Incompatible
};
/// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
/// assignment conversion type specified by ConvTy. This returns true if the
/// conversion was invalid or false if the conversion was accepted.
bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
SourceLocation Loc,
QualType DstType, QualType SrcType,
Expr *SrcExpr, AssignmentAction Action,
bool *Complained = nullptr);
/// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
/// enum. If AllowMask is true, then we also allow the complement of a valid
/// value, to be used as a mask.
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
bool AllowMask) const;
/// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
/// integer not in the range of enum values.
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
Expr *SrcExpr);
/// CheckAssignmentConstraints - Perform type checking for assignment,
/// argument passing, variable initialization, and function return values.
/// C99 6.5.16.
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
QualType LHSType,
QualType RHSType);
/// Check assignment constraints and optionally prepare for a conversion of
/// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
/// is true.
AssignConvertType CheckAssignmentConstraints(QualType LHSType,
ExprResult &RHS,
CastKind &Kind,
bool ConvertRHS = true);
/// Check assignment constraints for an assignment of RHS to LHSType.
///
/// \param LHSType The destination type for the assignment.
/// \param RHS The source expression for the assignment.
/// \param Diagnose If \c true, diagnostics may be produced when checking
/// for assignability. If a diagnostic is produced, \p RHS will be
/// set to ExprError(). Note that this function may still return
/// without producing a diagnostic, even for an invalid assignment.
/// \param DiagnoseCFAudited If \c true, the target is a function parameter
/// in an audited Core Foundation API and does not need to be checked
/// for ARC retain issues.
/// \param ConvertRHS If \c true, \p RHS will be updated to model the
/// conversions necessary to perform the assignment. If \c false,
/// \p Diagnose must also be \c false.
AssignConvertType CheckSingleAssignmentConstraints(
QualType LHSType, ExprResult &RHS, bool Diagnose = true,
bool DiagnoseCFAudited = false, bool ConvertRHS = true);
// If the lhs type is a transparent union, check whether we
// can initialize the transparent union with the given expression.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
ExprResult &RHS);
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit = false);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit,
ImplicitConversionSequence& ICS);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const ImplicitConversionSequence& ICS,
AssignmentAction Action,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const StandardConversionSequence& SCS,
AssignmentAction Action,
CheckedConversionKind CCK);
ExprResult PerformQualificationConversion(
Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
CheckedConversionKind CCK = CCK_ImplicitConversion);
/// the following "Check" methods will return a valid/converted QualType
/// or a null QualType (indicating an error diagnostic was issued).
/// type checking binary operators (subroutines of CreateBuiltinBinOp).
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType CheckPointerToMemberOperands( // C++ 5.5
ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
SourceLocation OpLoc, bool isIndirect);
QualType CheckMultiplyDivideOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
bool IsDivide);
QualType CheckRemainderOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
bool IsCompAssign = false);
QualType CheckAdditionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
QualType CheckSubtractionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
QualType* CompLHSTy = nullptr);
QualType CheckShiftOperands( // C99 6.5.7
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc, bool IsCompAssign = false);
QualType CheckCompareOperands( // C99 6.5.8/9
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckBitwiseOperands( // C99 6.5.[10...12]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckLogicalOperands( // C99 6.5.[13,14]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
// CheckAssignmentOperands is used for both simple and compound assignment.
// For simple assignment, pass both expressions and a null converted type.
// For compound assignment, pass both expressions and the converted type.
QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opcode, Expr *Op);
ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opcode,
Expr *LHS, Expr *RHS);
ExprResult checkPseudoObjectRValue(Expr *E);
Expr *recreateSyntacticForm(PseudoObjectExpr *E);
QualType CheckConditionalOperands( // C99 6.5.15
ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
QualType CXXCheckConditionalOperands( // C++ 5.16
ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
bool ConvertArgs = true);
QualType FindCompositePointerType(SourceLocation Loc,
ExprResult &E1, ExprResult &E2,
bool ConvertArgs = true) {
Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
QualType Composite =
FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
E1 = E1Tmp;
E2 = E2Tmp;
return Composite;
}
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
SourceLocation QuestionLoc);
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
SourceLocation QuestionLoc);
void DiagnoseAlwaysNonNullPointer(Expr *E,
Expr::NullPointerConstantKind NullType,
bool IsEqual, SourceRange Range);
/// type checking for vector binary operators.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign,
bool AllowBothBool, bool AllowBoolConversion);
QualType GetSignedVectorType(QualType V);
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc);
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
bool isLaxVectorConversion(QualType srcType, QualType destType);
/// type checking declaration initializers (C99 6.7.8)
bool CheckForConstantInitializer(Expr *e, QualType t);
// type checking C++ declaration initializers (C++ [dcl.init]).
/// ReferenceCompareResult - Expresses the result of comparing two
/// types (cv1 T1 and cv2 T2) to determine their compatibility for the
/// purposes of initialization by reference (C++ [dcl.init.ref]p4).
enum ReferenceCompareResult {
/// Ref_Incompatible - The two types are incompatible, so direct
/// reference binding is not possible.
Ref_Incompatible = 0,
/// Ref_Related - The two types are reference-related, which means
/// that their unqualified forms (T1 and T2) are either the same
/// or T1 is a base class of T2.
Ref_Related,
/// Ref_Compatible - The two types are reference-compatible.
Ref_Compatible
};
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
QualType T1, QualType T2,
bool &DerivedToBase,
bool &ObjCConversion,
bool &ObjCLifetimeConversion);
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
Expr *CastExpr, CastKind &CastKind,
ExprValueKind &VK, CXXCastPath &Path);
/// Force an expression with unknown-type to an expression of the
/// given type.
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
/// Type-check an expression that's being passed to an
/// __unknown_anytype parameter.
ExprResult checkUnknownAnyArg(SourceLocation callLoc,
Expr *result, QualType ¶mType);
// CheckVectorCast - check type constraints for vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size.
// returns true if the cast is invalid
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
CastKind &Kind);
/// Prepare `SplattedExpr` for a vector splat operation, adding
/// implicit casts if necessary.
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
// CheckExtVectorCast - check type constraints for extended vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size,
// or vectors and the element type of that vector.
// returns the cast expr
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
CastKind &Kind);
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
SourceLocation LParenLoc,
Expr *CastExpr,
SourceLocation RParenLoc);
enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
/// Checks for invalid conversions and casts between
/// retainable pointers and other pointer kinds for ARC and Weak.
ARCConversionResult CheckObjCConversion(SourceRange castRange,
QualType castType, Expr *&op,
CheckedConversionKind CCK,
bool Diagnose = true,
bool DiagnoseCFAudited = false,
BinaryOperatorKind Opc = BO_PtrMemD
);
Expr *stripARCUnbridgedCast(Expr *e);
void diagnoseARCUnbridgedCast(Expr *e);
bool CheckObjCARCUnavailableWeakConversion(QualType castType,
QualType ExprType);
/// checkRetainCycles - Check whether an Objective-C message send
/// might create an obvious retain cycle.
void checkRetainCycles(ObjCMessageExpr *msg);
void checkRetainCycles(Expr *receiver, Expr *argument);
void checkRetainCycles(VarDecl *Var, Expr *Init);
/// checkUnsafeAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained type.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
/// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained expression.
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
/// CheckMessageArgumentTypes - Check types in an Obj-C message send.
/// \param Method - May be null.
/// \param [out] ReturnType - The return type of the send.
/// \return true iff there were any incompatible types.
bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
MultiExprArg Args, Selector Sel,
ArrayRef<SourceLocation> SelectorLocs,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage, SourceLocation lbrac,
SourceLocation rbrac, SourceRange RecRange,
QualType &ReturnType, ExprValueKind &VK);
/// Determine the result of a message send expression based on
/// the type of the receiver, the method expected to receive the message,
/// and the form of the message send.
QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage);
/// If the given expression involves a message send to a method
/// with a related result type, emit a note describing what happened.
void EmitRelatedResultTypeNote(const Expr *E);
/// Given that we had incompatible pointer types in a return
/// statement, check whether we're in a method with a related result
/// type, and if so, emit a note describing what happened.
void EmitRelatedResultTypeNoteForReturn(QualType destType);
class ConditionResult {
Decl *ConditionVar;
FullExprArg Condition;
bool Invalid;
bool HasKnownValue;
bool KnownValue;
friend class Sema;
ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
bool IsConstexpr)
: ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
HasKnownValue(IsConstexpr && Condition.get() &&
!Condition.get()->isValueDependent()),
KnownValue(HasKnownValue &&
!!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
explicit ConditionResult(bool Invalid)
: ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
HasKnownValue(false), KnownValue(false) {}
public:
ConditionResult() : ConditionResult(false) {}
bool isInvalid() const { return Invalid; }
std::pair<VarDecl *, Expr *> get() const {
return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
Condition.get());
}
llvm::Optional<bool> getKnownValue() const {
if (!HasKnownValue)
return None;
return KnownValue;
}
};
static ConditionResult ConditionError() { return ConditionResult(true); }
enum class ConditionKind {
Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
Switch ///< An integral condition for a 'switch' statement.
};
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
Expr *SubExpr, ConditionKind CK);
ConditionResult ActOnConditionVariable(Decl *ConditionVar,
SourceLocation StmtLoc,
ConditionKind CK);
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
ExprResult CheckConditionVariable(VarDecl *ConditionVar,
SourceLocation StmtLoc,
ConditionKind CK);
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
/// CheckBooleanCondition - Diagnose problems involving the use of
/// the given expression as a boolean condition (e.g. in an if
/// statement). Also performs the standard function and array
/// decays, possibly changing the input variable.
///
/// \param Loc - A location associated with the condition, e.g. the
/// 'if' keyword.
/// \return true iff there were any errors
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
bool IsConstexpr = false);
/// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
/// found in an explicit(bool) specifier.
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
/// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
/// Returns true if the explicit specifier is now resolved.
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
/// DiagnoseAssignmentAsCondition - Given that an expression is
/// being used as a boolean condition, warn if it's an assignment.
void DiagnoseAssignmentAsCondition(Expr *E);
/// Redundant parentheses over an equality comparison can indicate
/// that the user intended an assignment used as condition.
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
/// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
/// the specified width and sign. If an overflow occurs, detect it and emit
/// the specified diagnostic.
void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
unsigned NewWidth, bool NewSign,
SourceLocation Loc, unsigned DiagID);
/// Checks that the Objective-C declaration is declared in the global scope.
/// Emits an error and marks the declaration as invalid if it's not declared
/// in the global scope.
bool CheckObjCDeclScope(Decl *D);
/// Abstract base class used for diagnosing integer constant
/// expression violations.
class VerifyICEDiagnoser {
public:
bool Suppress;
VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
virtual ~VerifyICEDiagnoser() { }
};
/// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
/// and reports the appropriate diagnostics. Returns false on success.
/// Can optionally return the value of the expression.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
VerifyICEDiagnoser &Diagnoser,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
unsigned DiagID,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E,
llvm::APSInt *Result = nullptr);
/// VerifyBitField - verifies that a bit field expression is an ICE and has
/// the correct width, and that the field type is valid.
/// Returns false on success.
/// Can optionally return whether the bit-field is of width 0
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
QualType FieldTy, bool IsMsStruct,
Expr *BitWidth, bool *ZeroWidth = nullptr);
private:
unsigned ForceCUDAHostDeviceDepth = 0;
public:
/// Increments our count of the number of times we've seen a pragma forcing
/// functions to be __host__ __device__. So long as this count is greater
/// than zero, all functions encountered will be __host__ __device__.
void PushForceCUDAHostDevice();
/// Decrements our count of the number of times we've seen a pragma forcing
/// functions to be __host__ __device__. Returns false if the count is 0
/// before incrementing, so you can emit an error.
bool PopForceCUDAHostDevice();
/// Diagnostics that are emitted only if we discover that the given function
/// must be codegen'ed. Because handling these correctly adds overhead to
/// compilation, this is currently only enabled for CUDA compilations.
llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
std::vector<PartialDiagnosticAt>>
DeviceDeferredDiags;
/// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
/// key in a hashtable, both the FD and location are hashed.
struct FunctionDeclAndLoc {
CanonicalDeclPtr<FunctionDecl> FD;
SourceLocation Loc;
};
/// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
/// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
/// same deferred diag twice.
llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
/// An inverse call graph, mapping known-emitted functions to one of their
/// known-emitted callers (plus the location of the call).
///
/// Functions that we can tell a priori must be emitted aren't added to this
/// map.
llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
/* Caller = */ FunctionDeclAndLoc>
DeviceKnownEmittedFns;
/// A partial call graph maintained during CUDA/OpenMP device code compilation
/// to support deferred diagnostics.
///
/// Functions are only added here if, at the time they're considered, they are
/// not known-emitted. As soon as we discover that a function is
/// known-emitted, we remove it and everything it transitively calls from this
/// set and add those functions to DeviceKnownEmittedFns.
llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
/* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
SourceLocation>>
DeviceCallGraph;
/// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
/// deferred.
///
/// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
/// which are not allowed to appear inside __device__ functions and are
/// allowed to appear in __host__ __device__ functions only if the host+device
/// function is never codegen'ed.
///
/// To handle this, we use the notion of "deferred diagnostics", where we
/// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
///
/// This class lets you emit either a regular diagnostic, a deferred
/// diagnostic, or no diagnostic at all, according to an argument you pass to
/// its constructor, thus simplifying the process of creating these "maybe
/// deferred" diagnostics.
class DeviceDiagBuilder {
public:
enum Kind {
/// Emit no diagnostics.
K_Nop,
/// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
K_Immediate,
/// Emit the diagnostic immediately, and, if it's a warning or error, also
/// emit a call stack showing how this function can be reached by an a
/// priori known-emitted function.
K_ImmediateWithCallStack,
/// Create a deferred diagnostic, which is emitted only if the function
/// it's attached to is codegen'ed. Also emit a call stack as with
/// K_ImmediateWithCallStack.
K_Deferred
};
DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
FunctionDecl *Fn, Sema &S);
DeviceDiagBuilder(DeviceDiagBuilder &&D);
DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
~DeviceDiagBuilder();
/// Convertible to bool: True if we immediately emitted an error, false if
/// we didn't emit an error or we created a deferred error.
///
/// Example usage:
///
/// if (DeviceDiagBuilder(...) << foo << bar)
/// return ExprError();
///
/// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
/// want to use these instead of creating a DeviceDiagBuilder yourself.
operator bool() const { return ImmediateDiag.hasValue(); }
template <typename T>
friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
const T &Value) {
if (Diag.ImmediateDiag.hasValue())
*Diag.ImmediateDiag << Value;
else if (Diag.PartialDiagId.hasValue())
Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
<< Value;
return Diag;
}
private:
Sema &S;
SourceLocation Loc;
unsigned DiagID;
FunctionDecl *Fn;
bool ShowCallStack;
// Invariant: At most one of these Optionals has a value.
// FIXME: Switch these to a Variant once that exists.
llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
llvm::Optional<unsigned> PartialDiagId;
};
/// Indicate that this function (and thus everything it transtively calls)
/// will be codegen'ed, and emit any deferred diagnostics on this function and
/// its (transitive) callees.
void markKnownEmitted(
Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
SourceLocation OrigLoc,
const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
/// is "used as device code".
///
/// - If CurContext is a __host__ function, does not emit any diagnostics.
/// - If CurContext is a __device__ or __global__ function, emits the
/// diagnostics immediately.
/// - If CurContext is a __host__ __device__ function and we are compiling for
/// the device, creates a diagnostic which is emitted if and when we realize
/// that the function will be codegen'ed.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in CUDA device code.
/// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
/// return ExprError();
/// // Otherwise, continue parsing as normal.
DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
/// is "used as host code".
///
/// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current
/// context is "used as device code".
///
/// - If CurContext is a `declare target` function or it is known that the
/// function is emitted for the device, emits the diagnostics immediately.
/// - If CurContext is a non-`declare target` function and we are compiling
/// for the device, creates a diagnostic which is emitted if and when we
/// realize that the function will be codegen'ed.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in NVPTX device code.
/// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
/// return ExprError();
/// // Otherwise, continue parsing as normal.
DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
enum CUDAFunctionTarget {
CFT_Device,
CFT_Global,
CFT_Host,
CFT_HostDevice,
CFT_InvalidTarget
};
/// Determines whether the given function is a CUDA device/host/kernel/etc.
/// function.
///
/// Use this rather than examining the function's attributes yourself -- you
/// will get it wrong. Returns CFT_Host if D is null.
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
bool IgnoreImplicitHDAttr = false);
CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
/// Gets the CUDA target for the current context.
CUDAFunctionTarget CurrentCUDATarget() {
return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
}
// CUDA function call preference. Must be ordered numerically from
// worst to best.
enum CUDAFunctionPreference {
CFP_Never, // Invalid caller/callee combination.
CFP_WrongSide, // Calls from host-device to host or device
// function that do not match current compilation
// mode.
CFP_HostDevice, // Any calls to host/device functions.
CFP_SameSide, // Calls from host-device to host or device
// function matching current compilation mode.
CFP_Native, // host-to-host or device-to-device calls.
};
/// Identifies relative preference of a given Caller/Callee
/// combination, based on their host/device attributes.
/// \param Caller function which needs address of \p Callee.
/// nullptr in case of global context.
/// \param Callee target function
///
/// \returns preference value for particular Caller/Callee combination.
CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
const FunctionDecl *Callee);
/// Determines whether Caller may invoke Callee, based on their CUDA
/// host/device attributes. Returns false if the call is not allowed.
///
/// Note: Will return true for CFP_WrongSide calls. These may appear in
/// semantically correct CUDA programs, but only if they're never codegen'ed.
bool IsAllowedCUDACall(const FunctionDecl *Caller,
const FunctionDecl *Callee) {
return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
}
/// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
/// depending on FD and the current compilation settings.
void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
const LookupResult &Previous);
public:
/// Check whether we're allowed to call Callee from the current context.
///
/// - If the call is never allowed in a semantically-correct program
/// (CFP_Never), emits an error and returns false.
///
/// - If the call is allowed in semantically-correct programs, but only if
/// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
/// be emitted if and when the caller is codegen'ed, and returns true.
///
/// Will only create deferred diagnostics for a given SourceLocation once,
/// so you can safely call this multiple times without generating duplicate
/// deferred errors.
///
/// - Otherwise, returns true without emitting any diagnostics.
bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
/// Set __device__ or __host__ __device__ attributes on the given lambda
/// operator() method.
///
/// CUDA lambdas declared inside __device__ or __global__ functions inherit
/// the __device__ attribute. Similarly, lambdas inside __host__ __device__
/// functions become __host__ __device__ themselves.
void CUDASetLambdaAttrs(CXXMethodDecl *Method);
/// Finds a function in \p Matches with highest calling priority
/// from \p Caller context and erases all functions with lower
/// calling priority.
void EraseUnwantedCUDAMatches(
const FunctionDecl *Caller,
SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
/// Given a implicit special member, infer its CUDA target from the
/// calls it needs to make to underlying base/field special members.
/// \param ClassDecl the class for which the member is being created.
/// \param CSM the kind of special member.
/// \param MemberDecl the special member itself.
/// \param ConstRHS true if this is a copy operation with a const object on
/// its RHS.
/// \param Diagnose true if this call should emit diagnostics.
/// \return true if there was an error inferring.
/// The result of this call is implicit CUDA target attribute(s) attached to
/// the member declaration.
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
CXXSpecialMember CSM,
CXXMethodDecl *MemberDecl,
bool ConstRHS,
bool Diagnose);
/// \return true if \p CD can be considered empty according to CUDA
/// (E.2.3.1 in CUDA 7.5 Programming guide).
bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
// \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
// case of error emits appropriate diagnostic and invalidates \p Var.
//
// \details CUDA allows only empty constructors as initializers for global
// variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
// __shared__ variables whether they are local or not (they all are implicitly
// static in CUDA). One exception is that CUDA allows constant initializers
// for __constant__ and __device__ variables.
void checkAllowedCUDAInitializer(VarDecl *VD);
/// Check whether NewFD is a valid overload for CUDA. Emits
/// diagnostics and invalidates NewFD if not.
void checkCUDATargetOverload(FunctionDecl *NewFD,
const LookupResult &Previous);
/// Copies target attributes from the template TD to the function FD.
void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
/// Returns the name of the launch configuration function. This is the name
/// of the function that will be called to configure kernel call, with the
/// parameters specified via <<<>>>.
std::string getCudaConfigureFuncName() const;
/// \name Code completion
//@{
/// Describes the context in which code completion occurs.
enum ParserCompletionContext {
/// Code completion occurs at top-level or namespace context.
PCC_Namespace,
/// Code completion occurs within a class, struct, or union.
PCC_Class,
/// Code completion occurs within an Objective-C interface, protocol,
/// or category.
PCC_ObjCInterface,
/// Code completion occurs within an Objective-C implementation or
/// category implementation
PCC_ObjCImplementation,
/// Code completion occurs within the list of instance variables
/// in an Objective-C interface, protocol, category, or implementation.
PCC_ObjCInstanceVariableList,
/// Code completion occurs following one or more template
/// headers.
PCC_Template,
/// Code completion occurs following one or more template
/// headers within a class.
PCC_MemberTemplate,
/// Code completion occurs within an expression.
PCC_Expression,
/// Code completion occurs within a statement, which may
/// also be an expression or a declaration.
PCC_Statement,
/// Code completion occurs at the beginning of the
/// initialization statement (or expression) in a for loop.
PCC_ForInit,
/// Code completion occurs within the condition of an if,
/// while, switch, or for statement.
PCC_Condition,
/// Code completion occurs within the body of a function on a
/// recovery path, where we do not have a specific handle on our position
/// in the grammar.
PCC_RecoveryInFunction,
/// Code completion occurs where only a type is permitted.
PCC_Type,
/// Code completion occurs in a parenthesized expression, which
/// might also be a type cast.
PCC_ParenthesizedExpression,
/// Code completion occurs within a sequence of declaration
/// specifiers within a function, method, or block.
PCC_LocalDeclarationSpecifiers
};
void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
void CodeCompleteOrdinaryName(Scope *S,
ParserCompletionContext CompletionContext);
void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
bool AllowNonIdentifiers,
bool AllowNestedNameSpecifiers);
struct CodeCompleteExpressionData;
void CodeCompleteExpression(Scope *S,
const CodeCompleteExpressionData &Data);
void CodeCompleteExpression(Scope *S, QualType PreferredType,
bool IsParenthesized = false);
void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
SourceLocation OpLoc, bool IsArrow,
bool IsBaseExprStatement,
QualType PreferredType);
void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
QualType PreferredType);
void CodeCompleteTag(Scope *S, unsigned TagSpec);
void CodeCompleteTypeQualifiers(DeclSpec &DS);
void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
const VirtSpecifiers *VS = nullptr);
void CodeCompleteBracketDeclarator(Scope *S);
void CodeCompleteCase(Scope *S);
/// Reports signatures for a call to CodeCompleteConsumer and returns the
/// preferred type for the current argument. Returned type can be null.
QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
SourceLocation OpenParLoc);
QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
SourceLocation Loc,
ArrayRef<Expr *> Args,
SourceLocation OpenParLoc);
QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
CXXScopeSpec SS,
ParsedType TemplateTypeTy,
ArrayRef<Expr *> ArgExprs,
IdentifierInfo *II,
SourceLocation OpenParLoc);
void CodeCompleteInitializer(Scope *S, Decl *D);
void CodeCompleteAfterIf(Scope *S);
void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
QualType BaseType, QualType PreferredType);
void CodeCompleteUsing(Scope *S);
void CodeCompleteUsingDirective(Scope *S);
void CodeCompleteNamespaceDecl(Scope *S);
void CodeCompleteNamespaceAliasDecl(Scope *S);
void CodeCompleteOperatorName(Scope *S);
void CodeCompleteConstructorInitializer(
Decl *Constructor,
ArrayRef<CXXCtorInitializer *> Initializers);
void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
bool AfterAmpersand);
void CodeCompleteObjCAtDirective(Scope *S);
void CodeCompleteObjCAtVisibility(Scope *S);
void CodeCompleteObjCAtStatement(Scope *S);
void CodeCompleteObjCAtExpression(Scope *S);
void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
void CodeCompleteObjCPropertyGetter(Scope *S);
void CodeCompleteObjCPropertySetter(Scope *S);
void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
bool IsParameter);
void CodeCompleteObjCMessageReceiver(Scope *S);
void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression);
void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
bool IsSuper = false);
void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
ObjCInterfaceDecl *Super = nullptr);
void CodeCompleteObjCForCollection(Scope *S,
DeclGroupPtrTy IterationVar);
void CodeCompleteObjCSelector(Scope *S,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCProtocolReferences(
ArrayRef<IdentifierLocPair> Protocols);
void CodeCompleteObjCProtocolDecl(Scope *S);
void CodeCompleteObjCInterfaceDecl(Scope *S);
void CodeCompleteObjCSuperclass(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationDecl(Scope *S);
void CodeCompleteObjCInterfaceCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCPropertyDefinition(Scope *S);
void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
IdentifierInfo *PropertyName);
void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
ParsedType ReturnType);
void CodeCompleteObjCMethodDeclSelector(Scope *S,
bool IsInstanceMethod,
bool AtParameterName,
ParsedType ReturnType,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
SourceLocation ClassNameLoc,
bool IsBaseExprStatement);
void CodeCompletePreprocessorDirective(bool InConditional);
void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
void CodeCompletePreprocessorMacroName(bool IsDefinition);
void CodeCompletePreprocessorExpression();
void CodeCompletePreprocessorMacroArgument(Scope *S,
IdentifierInfo *Macro,
MacroInfo *MacroInfo,
unsigned Argument);
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
void CodeCompleteNaturalLanguage();
void CodeCompleteAvailabilityPlatformName();
void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
SmallVectorImpl<CodeCompletionResult> &Results);
//@}
//===--------------------------------------------------------------------===//
// Extra semantic analysis beyond the C type system
public:
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
unsigned ByteNo) const;
private:
void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
const ArraySubscriptExpr *ASE=nullptr,
bool AllowOnePastEnd=true, bool IndexNegated=false);
void CheckArrayAccess(const Expr *E);
// Used to grab the relevant information from a FormatAttr and a
// FunctionDeclaration.
struct FormatStringInfo {
unsigned FormatIdx;
unsigned FirstDataArg;
bool HasVAListArg;
};
static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
FormatStringInfo *FSI);
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
ArrayRef<const Expr *> Args);
bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
void CheckConstructorCall(FunctionDecl *FDecl,
ArrayRef<const Expr *> Args,
const FunctionProtoType *Proto,
SourceLocation Loc);
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
const Expr *ThisArg, ArrayRef<const Expr *> Args,
bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
VariadicCallType CallType);
bool CheckObjCString(Expr *Arg);
ExprResult CheckOSLogFormatStringArg(Expr *Arg);
ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
unsigned BuiltinID, CallExpr *TheCall);
void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
unsigned MaxWidth);
bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckIntelFPGABuiltinFunctionCall(unsigned BuiltinID, CallExpr *Call);
bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
bool SemaBuiltinVSX(CallExpr *TheCall);
bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
public:
// Used by C++ template instantiation.
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
private:
bool SemaBuiltinPrefetch(CallExpr *TheCall);
bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
bool SemaBuiltinAssume(CallExpr *TheCall);
bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
bool SemaBuiltinLongjmp(CallExpr *TheCall);
bool SemaBuiltinSetjmp(CallExpr *TheCall);
ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
AtomicExpr::AtomicOp Op);
ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
bool IsDelete);
bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
llvm::APSInt &Result);
bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
int High, bool RangeIsError = true);
bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
unsigned Multiple);
bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
int ArgNum, unsigned ExpectedFieldNum,
bool AllowName);
bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
public:
enum FormatStringType {
FST_Scanf,
FST_Printf,
FST_NSString,
FST_Strftime,
FST_Strfmon,
FST_Kprintf,
FST_FreeBSDKPrintf,
FST_OSTrace,
FST_OSLog,
FST_Unknown
};
static FormatStringType GetFormatStringType(const FormatAttr *Format);
bool FormatStringHasSArg(const StringLiteral *FExpr);
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
private:
bool CheckFormatArguments(const FormatAttr *Format,
ArrayRef<const Expr *> Args,
bool IsCXXMember,
VariadicCallType CallType,
SourceLocation Loc, SourceRange Range,
llvm::SmallBitVector &CheckedVarArgs);
bool CheckFormatArguments(ArrayRef<const Expr *> Args,
bool HasVAListArg, unsigned format_idx,
unsigned firstDataArg, FormatStringType Type,
VariadicCallType CallType,
SourceLocation Loc, SourceRange range,
llvm::SmallBitVector &CheckedVarArgs);
void CheckAbsoluteValueFunction(const CallExpr *Call,
const FunctionDecl *FDecl);
void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
void CheckMemaccessArguments(const CallExpr *Call,
unsigned BId,
IdentifierInfo *FnName);
void CheckStrlcpycatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckStrncatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
SourceLocation ReturnLoc,
bool isObjCMethod = false,
const AttrVec *Attrs = nullptr,
const FunctionDecl *FD = nullptr);
public:
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
private:
void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
void CheckForIntOverflow(Expr *E);
void CheckUnsequencedOperations(Expr *E);
/// Perform semantic checks on a completed expression. This will either
/// be a full-expression or a default argument expression.
void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
bool IsConstexpr = false);
void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
Expr *Init);
/// Check if there is a field shadowing.
void CheckShadowInheritedFields(const SourceLocation &Loc,
DeclarationName FieldName,
const CXXRecordDecl *RD,
bool DeclIsField = true);
/// Check if the given expression contains 'break' or 'continue'
/// statement that produces control flow different from GCC.
void CheckBreakContinueBinding(Expr *E);
/// Check whether receiver is mutable ObjC container which
/// attempts to add itself into the container
void CheckObjCCircularContainer(ObjCMessageExpr *Message);
void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
bool DeleteWasArrayForm);
public:
/// Register a magic integral constant to be used as a type tag.
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
uint64_t MagicValue, QualType Type,
bool LayoutCompatible, bool MustBeNull);
struct TypeTagData {
TypeTagData() {}
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
Type(Type), LayoutCompatible(LayoutCompatible),
MustBeNull(MustBeNull)
{}
QualType Type;
/// If true, \c Type should be compared with other expression's types for
/// layout-compatibility.
unsigned LayoutCompatible : 1;
unsigned MustBeNull : 1;
};
/// A pair of ArgumentKind identifier and magic value. This uniquely
/// identifies the magic value.
typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
private:
/// A map from magic value to type information.
std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
TypeTagForDatatypeMagicValues;
/// Peform checks on a call of a function with argument_with_type_tag
/// or pointer_with_type_tag attributes.
void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
const ArrayRef<const Expr *> ExprArgs,
SourceLocation CallSiteLoc);
/// Check if we are taking the address of a packed field
/// as this may be a problem if the pointer value is dereferenced.
void CheckAddressOfPackedMember(Expr *rhs);
/// The parser's current scope.
///
/// The parser maintains this state here.
Scope *CurScope;
mutable IdentifierInfo *Ident_super;
mutable IdentifierInfo *Ident___float128;
/// Nullability type specifiers.
IdentifierInfo *Ident__Nonnull = nullptr;
IdentifierInfo *Ident__Nullable = nullptr;
IdentifierInfo *Ident__Null_unspecified = nullptr;
IdentifierInfo *Ident_NSError = nullptr;
/// The handler for the FileChanged preprocessor events.
///
/// Used for diagnostics that implement custom semantic analysis for #include
/// directives, like -Wpragma-pack.
sema::SemaPPCallbacks *SemaPPCallbackHandler;
protected:
friend class Parser;
friend class InitializationSequence;
friend class ASTReader;
friend class ASTDeclReader;
friend class ASTWriter;
public:
/// Retrieve the keyword associated
IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
/// The struct behind the CFErrorRef pointer.
RecordDecl *CFError = nullptr;
/// Retrieve the identifier "NSError".
IdentifierInfo *getNSErrorIdent();
/// Retrieve the parser's current scope.
///
/// This routine must only be used when it is certain that semantic analysis
/// and the parser are in precisely the same context, which is not the case
/// when, e.g., we are performing any kind of template instantiation.
/// Therefore, the only safe places to use this scope are in the parser
/// itself and in routines directly invoked from the parser and *never* from
/// template substitution or instantiation.
Scope *getCurScope() const { return CurScope; }
void incrementMSManglingNumber() const {
return CurScope->incrementMSManglingNumber();
}
IdentifierInfo *getSuperIdentifier() const;
IdentifierInfo *getFloat128Identifier() const;
Decl *getObjCDeclContext() const;
DeclContext *getCurLexicalContext() const {
return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
}
const DeclContext *getCurObjCLexicalContext() const {
const DeclContext *DC = getCurLexicalContext();
// A category implicitly has the attribute of the interface.
if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
DC = CatD->getClassInterface();
return DC;
}
/// To be used for checking whether the arguments being passed to
/// function exceeds the number of parameters expected for it.
static bool TooManyArguments(size_t NumParams, size_t NumArgs,
bool PartialOverloading = false) {
// We check whether we're just after a comma in code-completion.
if (NumArgs > 0 && PartialOverloading)
return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
return NumArgs > NumParams;
}
// Emitting members of dllexported classes is delayed until the class
// (including field initializers) is fully parsed.
SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
private:
class SavePendingParsedClassStateRAII {
public:
SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
~SavePendingParsedClassStateRAII() {
assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
"there shouldn't be any pending delayed exception spec checks");
assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
"there shouldn't be any pending delayed exception spec checks");
assert(S.DelayedDllExportClasses.empty() &&
"there shouldn't be any pending delayed DLL export classes");
swapSavedState();
}
private:
Sema &S;
decltype(DelayedOverridingExceptionSpecChecks)
SavedOverridingExceptionSpecChecks;
decltype(DelayedEquivalentExceptionSpecChecks)
SavedEquivalentExceptionSpecChecks;
decltype(DelayedDllExportClasses) SavedDllExportClasses;
void swapSavedState() {
SavedOverridingExceptionSpecChecks.swap(
S.DelayedOverridingExceptionSpecChecks);
SavedEquivalentExceptionSpecChecks.swap(
S.DelayedEquivalentExceptionSpecChecks);
SavedDllExportClasses.swap(S.DelayedDllExportClasses);
}
};
/// Helper class that collects misaligned member designations and
/// their location info for delayed diagnostics.
struct MisalignedMember {
Expr *E;
RecordDecl *RD;
ValueDecl *MD;
CharUnits Alignment;
MisalignedMember() : E(), RD(), MD(), Alignment() {}
MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
CharUnits Alignment)
: E(E), RD(RD), MD(MD), Alignment(Alignment) {}
explicit MisalignedMember(Expr *E)
: MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
bool operator==(const MisalignedMember &m) { return this->E == m.E; }
};
/// Small set of gathered accesses to potentially misaligned members
/// due to the packed attribute.
SmallVector<MisalignedMember, 4> MisalignedMembers;
/// Adds an expression to the set of gathered misaligned members.
void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
CharUnits Alignment);
public:
/// Diagnoses the current set of gathered accesses. This typically
/// happens at full expression level. The set is cleared after emitting the
/// diagnostics.
void DiagnoseMisalignedMembers();
/// This function checks if the expression is in the sef of potentially
/// misaligned members and it is converted to some pointer type T with lower
/// or equal alignment requirements. If so it removes it. This is used when
/// we do not want to diagnose such misaligned access (e.g. in conversions to
/// void*).
void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
/// This function calls Action when it determines that E designates a
/// misaligned member due to the packed attribute. This is used to emit
/// local diagnostics like in reference binding.
void RefersToMemberWithReducedAlignment(
Expr *E,
llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
Action);
/// Describes the reason a calling convention specification was ignored, used
/// for diagnostics.
enum class CallingConventionIgnoredReason {
ForThisTarget = 0,
VariadicFunction,
ConstructorDestructor,
BuiltinFunction
};
private:
// We store SYCL Kernels here and handle separately -- which is a hack.
// FIXME: It would be best to refactor this.
SmallVector<Decl*, 4> SyclDeviceDecls;
// SYCL integration header instance for current compilation unit this Sema
// is associated with.
std::unique_ptr<SYCLIntegrationHeader> SyclIntHeader;
public:
void addSyclDeviceDecl(Decl *d) { SyclDeviceDecls.push_back(d); }
SmallVectorImpl<Decl *> &syclDeviceDecls() { return SyclDeviceDecls; }
/// Lazily creates and returns SYCL integration header instance.
SYCLIntegrationHeader &getSyclIntegrationHeader() {
if (SyclIntHeader == nullptr)
SyclIntHeader = llvm::make_unique<SYCLIntegrationHeader>(
getDiagnostics(), getLangOpts().SYCLUnnamedLambda);
return *SyclIntHeader.get();
}
enum SYCLRestrictKind {
KernelGlobalVariable,
KernelRTTI,
KernelNonConstStaticDataVariable,
KernelCallVirtualFunction,
KernelUseExceptions,
KernelCallRecursiveFunction,
KernelCallFunctionPointer,
KernelAllocateStorage,
KernelUseAssembly,
KernelHavePolymorphicClass,
KernelCallVariadicFunction
};
DeviceDiagBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
void ConstructOpenCLKernel(FunctionDecl *KernelCallerFunc);
void MarkDevice(void);
bool CheckSYCLCall(SourceLocation Loc, FunctionDecl *Callee);
};
/// RAII object that enters a new expression evaluation context.
class EnterExpressionEvaluationContext {
Sema &Actions;
bool Entered = true;
public:
EnterExpressionEvaluationContext(
Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl = nullptr,
Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
Sema::ExpressionEvaluationContextRecord::EK_Other,
bool ShouldEnter = true)
: Actions(Actions), Entered(ShouldEnter) {
if (Entered)
Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
ExprContext);
}
EnterExpressionEvaluationContext(
Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
Sema::ReuseLambdaContextDecl_t,
Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
Sema::ExpressionEvaluationContextRecord::EK_Other)
: Actions(Actions) {
Actions.PushExpressionEvaluationContext(
NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
}
enum InitListTag { InitList };
EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
bool ShouldEnter = true)
: Actions(Actions), Entered(false) {
// In C++11 onwards, narrowing checks are performed on the contents of
// braced-init-lists, even when they occur within unevaluated operands.
// Therefore we still need to instantiate constexpr functions used in such
// a context.
if (ShouldEnter && Actions.isUnevaluatedContext() &&
Actions.getLangOpts().CPlusPlus11) {
Actions.PushExpressionEvaluationContext(
Sema::ExpressionEvaluationContext::UnevaluatedList);
Entered = true;
}
}
~EnterExpressionEvaluationContext() {
if (Entered)
Actions.PopExpressionEvaluationContext();
}
};
DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
sema::TemplateDeductionInfo &Info);
/// Contains a late templated function.
/// Will be parsed at the end of the translation unit, used by Sema & Parser.
struct LateParsedTemplate {
CachedTokens Toks;
/// The template function declaration to be late parsed.
Decl *D;
};
} // end namespace clang
namespace llvm {
// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
// SourceLocation.
template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
static FunctionDeclAndLoc getEmptyKey() {
return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
}
static FunctionDeclAndLoc getTombstoneKey() {
return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
}
static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
FDL.Loc.getRawEncoding());
}
static bool isEqual(const FunctionDeclAndLoc &LHS,
const FunctionDeclAndLoc &RHS) {
return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
}
};
} // namespace llvm
#endif
|
image.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% IIIII M M AAA GGGG EEEEE %
% I MM MM A A G E %
% I M M M AAAAA G GG EEE %
% I M M A A G G E %
% IIIII M M A A GGGG EEEEE %
% %
% %
% MagickCore Image Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/animate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/client.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/compress.h"
#include "MagickCore/constitute.h"
#include "MagickCore/delegate.h"
#include "MagickCore/display.h"
#include "MagickCore/draw.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/histogram.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magic.h"
#include "MagickCore/magick.h"
#include "MagickCore/magick-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/quantize.h"
#include "MagickCore/random_.h"
#include "MagickCore/resource_.h"
#include "MagickCore/segment.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/signature-private.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/timer.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/version.h"
#include "MagickCore/xwindow-private.h"
/*
Constant declaration.
*/
const char
BackgroundColor[] = "#ffffff", /* white */
BorderColor[] = "#dfdfdf", /* gray */
DefaultTileFrame[] = "15x15+3+3",
DefaultTileGeometry[] = "120x120+4+3>",
DefaultTileLabel[] = "%f\n%G\n%b",
ForegroundColor[] = "#000", /* black */
LoadImageTag[] = "Load/Image",
LoadImagesTag[] = "Load/Images",
MatteColor[] = "#bdbdbd", /* gray */
PSDensityGeometry[] = "72.0x72.0",
PSPageGeometry[] = "612x792",
SaveImageTag[] = "Save/Image",
SaveImagesTag[] = "Save/Images",
TransparentColor[] = "#00000000"; /* transparent black */
const double
DefaultResolution = 72.0;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireImage() returns a pointer to an image structure initialized to
% default values.
%
% The format of the AcquireImage method is:
%
% Image *AcquireImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: Many of the image default values are set from this
% structure. For example, filename, compression, depth, background color,
% and others.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AcquireImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
Image
*image;
MagickStatusType
flags;
/*
Allocate image structure.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
image=(Image *) AcquireCriticalMemory(sizeof(*image));
(void) memset(image,0,sizeof(*image));
/*
Initialize Image structure.
*/
(void) CopyMagickString(image->magick,"MIFF",MagickPathExtent);
image->storage_class=DirectClass;
image->depth=MAGICKCORE_QUANTUM_DEPTH;
image->colorspace=sRGBColorspace;
image->rendering_intent=PerceptualIntent;
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.red_primary.z=0.0300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.green_primary.z=0.1000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.blue_primary.z=0.7900f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
image->chromaticity.white_point.z=0.3583f;
image->interlace=NoInterlace;
image->ticks_per_second=UndefinedTicksPerSecond;
image->compose=OverCompositeOp;
(void) QueryColorCompliance(MatteColor,AllCompliance,&image->matte_color,
exception);
(void) QueryColorCompliance(BackgroundColor,AllCompliance,
&image->background_color,exception);
(void) QueryColorCompliance(BorderColor,AllCompliance,&image->border_color,
exception);
(void) QueryColorCompliance(TransparentColor,AllCompliance,
&image->transparent_color,exception);
GetTimerInfo(&image->timer);
image->cache=AcquirePixelCache(0);
image->channel_mask=DefaultChannels;
image->channel_map=AcquirePixelChannelMap();
image->blob=CloneBlobInfo((BlobInfo *) NULL);
image->timestamp=time((time_t *) NULL);
image->debug=IsEventLogging();
image->reference_count=1;
image->semaphore=AcquireSemaphoreInfo();
image->signature=MagickCoreSignature;
if (image_info == (ImageInfo *) NULL)
return(image);
/*
Transfer image info.
*/
SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue :
MagickFalse);
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,image_info->magick,MagickPathExtent);
if (image_info->size != (char *) NULL)
{
(void) ParseAbsoluteGeometry(image_info->size,&image->extract_info);
image->columns=image->extract_info.width;
image->rows=image->extract_info.height;
image->offset=image->extract_info.x;
image->extract_info.x=0;
image->extract_info.y=0;
}
if (image_info->extract != (char *) NULL)
{
RectangleInfo
geometry;
(void) memset(&geometry,0,sizeof(geometry));
flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
if (((flags & XValue) != 0) || ((flags & YValue) != 0))
{
image->extract_info=geometry;
Swap(image->columns,image->extract_info.width);
Swap(image->rows,image->extract_info.height);
}
}
image->compression=image_info->compression;
image->quality=image_info->quality;
image->endian=image_info->endian;
image->interlace=image_info->interlace;
image->units=image_info->units;
if (image_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(image_info->density,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
if (image_info->page != (char *) NULL)
{
char
*geometry;
image->page=image->extract_info;
geometry=GetPageGeometry(image_info->page);
(void) ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
}
if (image_info->depth != 0)
image->depth=image_info->depth;
image->dither=image_info->dither;
image->matte_color=image_info->matte_color;
image->background_color=image_info->background_color;
image->border_color=image_info->border_color;
image->transparent_color=image_info->transparent_color;
image->ping=image_info->ping;
image->progress_monitor=image_info->progress_monitor;
image->client_data=image_info->client_data;
if (image_info->cache != (void *) NULL)
ClonePixelCacheMethods(image->cache,image_info->cache);
/*
Set all global options that map to per-image settings.
*/
(void) SyncImageSettings(image_info,image,exception);
/*
Global options that are only set for new images.
*/
option=GetImageOption(image_info,"delay");
if (option != (const char *) NULL)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(option,&geometry_info);
if ((flags & GreaterValue) != 0)
{
if (image->delay > (size_t) floor(geometry_info.rho+0.5))
image->delay=(size_t) floor(geometry_info.rho+0.5);
}
else
if ((flags & LessValue) != 0)
{
if (image->delay < (size_t) floor(geometry_info.rho+0.5))
image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);
}
else
image->delay=(size_t) floor(geometry_info.rho+0.5);
if ((flags & SigmaValue) != 0)
image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5);
}
option=GetImageOption(image_info,"dispose");
if (option != (const char *) NULL)
image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions,
MagickFalse,option);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireImageInfo() allocates the ImageInfo structure.
%
% The format of the AcquireImageInfo method is:
%
% ImageInfo *AcquireImageInfo(void)
%
*/
MagickExport ImageInfo *AcquireImageInfo(void)
{
ImageInfo
*image_info;
image_info=(ImageInfo *) AcquireCriticalMemory(sizeof(*image_info));
GetImageInfo(image_info);
return(image_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e N e x t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireNextImage() initializes the next image in a sequence to
% default values. The next member of image points to the newly allocated
% image. If there is a memory shortage, next is assigned NULL.
%
% The format of the AcquireNextImage method is:
%
% void AcquireNextImage(const ImageInfo *image_info,Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: Many of the image default values are set from this
% structure. For example, filename, compression, depth, background color,
% and others.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport void AcquireNextImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
/*
Allocate image structure.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
image->next=AcquireImage(image_info,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return;
(void) CopyMagickString(GetNextImageInList(image)->filename,image->filename,
MagickPathExtent);
if (image_info != (ImageInfo *) NULL)
(void) CopyMagickString(GetNextImageInList(image)->filename,
image_info->filename,MagickPathExtent);
DestroyBlob(GetNextImageInList(image));
image->next->blob=ReferenceBlob(image->blob);
image->next->endian=image->endian;
image->next->scene=image->scene+1;
image->next->previous=image;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A p p e n d I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AppendImages() takes all images from the current image pointer to the end
% of the image list and appends them to each other top-to-bottom if the
% stack parameter is true, otherwise left-to-right.
%
% The current gravity setting effects how the image is justified in the
% final image.
%
% The format of the AppendImages method is:
%
% Image *AppendImages(const Image *images,const MagickBooleanType stack,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o stack: A value other than 0 stacks the images top-to-bottom.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AppendImages(const Image *images,
const MagickBooleanType stack,ExceptionInfo *exception)
{
#define AppendImageTag "Append/Image"
CacheView
*append_view;
Image
*append_image;
MagickBooleanType
homogeneous_colorspace,
status;
MagickOffsetType
n;
PixelTrait
alpha_trait;
RectangleInfo
geometry;
register const Image
*next;
size_t
depth,
height,
number_images,
width;
ssize_t
x_offset,
y,
y_offset;
/*
Compute maximum area of appended area.
*/
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
alpha_trait=images->alpha_trait;
number_images=1;
width=images->columns;
height=images->rows;
depth=images->depth;
homogeneous_colorspace=MagickTrue;
next=GetNextImageInList(images);
for ( ; next != (Image *) NULL; next=GetNextImageInList(next))
{
if (next->depth > depth)
depth=next->depth;
if (next->colorspace != images->colorspace)
homogeneous_colorspace=MagickFalse;
if (next->alpha_trait != UndefinedPixelTrait)
alpha_trait=BlendPixelTrait;
number_images++;
if (stack != MagickFalse)
{
if (next->columns > width)
width=next->columns;
height+=next->rows;
continue;
}
width+=next->columns;
if (next->rows > height)
height=next->rows;
}
/*
Append images.
*/
append_image=CloneImage(images,width,height,MagickTrue,exception);
if (append_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(append_image,DirectClass,exception) == MagickFalse)
{
append_image=DestroyImage(append_image);
return((Image *) NULL);
}
if (homogeneous_colorspace == MagickFalse)
(void) SetImageColorspace(append_image,sRGBColorspace,exception);
append_image->depth=depth;
append_image->alpha_trait=alpha_trait;
append_image->page=images->page;
(void) SetImageBackgroundColor(append_image,exception);
status=MagickTrue;
x_offset=0;
y_offset=0;
next=images;
append_view=AcquireAuthenticCacheView(append_image,exception);
for (n=0; n < (MagickOffsetType) number_images; n++)
{
CacheView
*image_view;
MagickBooleanType
proceed;
SetGeometry(append_image,&geometry);
GravityAdjustGeometry(next->columns,next->rows,next->gravity,&geometry);
if (stack != MagickFalse)
x_offset-=geometry.x;
else
y_offset-=geometry.y;
image_view=AcquireVirtualCacheView(next,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(next,next,next->rows,1)
#endif
for (y=0; y < (ssize_t) next->rows; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,next->columns,1,exception);
q=QueueCacheViewAuthenticPixels(append_view,x_offset,y+y_offset,
next->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
GetPixelInfo(next,&pixel);
for (x=0; x < (ssize_t) next->columns; x++)
{
if (GetPixelWriteMask(next,p) <= (QuantumRange/2))
{
SetPixelBackgoundColor(append_image,q);
p+=GetPixelChannels(next);
q+=GetPixelChannels(append_image);
continue;
}
GetPixelInfoPixel(next,p,&pixel);
SetPixelViaPixelInfo(append_image,&pixel,q);
p+=GetPixelChannels(next);
q+=GetPixelChannels(append_image);
}
sync=SyncCacheViewAuthenticPixels(append_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (stack == MagickFalse)
{
x_offset+=(ssize_t) next->columns;
y_offset=0;
}
else
{
x_offset=0;
y_offset+=(ssize_t) next->rows;
}
proceed=SetImageProgress(append_image,AppendImageTag,n,number_images);
if (proceed == MagickFalse)
break;
next=GetNextImageInList(next);
}
append_view=DestroyCacheView(append_view);
if (status == MagickFalse)
append_image=DestroyImage(append_image);
return(append_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C a t c h I m a g e E x c e p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CatchImageException() returns if no exceptions are found in the image
% sequence, otherwise it determines the most severe exception and reports
% it as a warning or error depending on the severity.
%
% The format of the CatchImageException method is:
%
% ExceptionType CatchImageException(Image *image)
%
% A description of each parameter follows:
%
% o image: An image sequence.
%
*/
MagickExport ExceptionType CatchImageException(Image *image)
{
ExceptionInfo
*exception;
ExceptionType
severity;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
exception=AcquireExceptionInfo();
CatchException(exception);
severity=exception->severity;
exception=DestroyExceptionInfo(exception);
return(severity);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l i p I m a g e P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClipImagePath() sets the image clip mask based any clipping path information
% if it exists.
%
% The format of the ClipImagePath method is:
%
% MagickBooleanType ClipImagePath(Image *image,const char *pathname,
% const MagickBooleanType inside,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o pathname: name of clipping path resource. If name is preceded by #, use
% clipping path numbered by name.
%
% o inside: if non-zero, later operations take effect inside clipping path.
% Otherwise later operations take effect outside clipping path.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ClipImage(Image *image,ExceptionInfo *exception)
{
return(ClipImagePath(image,"#1",MagickTrue,exception));
}
MagickExport MagickBooleanType ClipImagePath(Image *image,const char *pathname,
const MagickBooleanType inside,ExceptionInfo *exception)
{
#define ClipImagePathTag "ClipPath/Image"
char
*property;
const char
*value;
Image
*clip_mask;
ImageInfo
*image_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pathname != NULL);
property=AcquireString(pathname);
(void) FormatLocaleString(property,MagickPathExtent,"8BIM:1999,2998:%s",
pathname);
value=GetImageProperty(image,property,exception);
property=DestroyString(property);
if (value == (const char *) NULL)
{
ThrowFileException(exception,OptionError,"NoClipPathDefined",
image->filename);
return(MagickFalse);
}
image_info=AcquireImageInfo();
(void) CopyMagickString(image_info->filename,image->filename,
MagickPathExtent);
(void) ConcatenateMagickString(image_info->filename,pathname,
MagickPathExtent);
clip_mask=BlobToImage(image_info,value,strlen(value),exception);
image_info=DestroyImageInfo(image_info);
if (clip_mask == (Image *) NULL)
return(MagickFalse);
if (clip_mask->storage_class == PseudoClass)
{
(void) SyncImage(clip_mask,exception);
if (SetImageStorageClass(clip_mask,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
if (inside != MagickFalse)
(void) NegateImage(clip_mask,MagickFalse,exception);
(void) FormatLocaleString(clip_mask->magick_filename,MagickPathExtent,
"8BIM:1999,2998:%s\nPS",pathname);
(void) SetImageMask(image,WritePixelMask,clip_mask,exception);
clip_mask=DestroyImage(clip_mask);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImage() copies an image and returns the copy as a new image object.
%
% If the specified columns and rows is 0, an exact copy of the image is
% returned, otherwise the pixel data is undefined and must be initialized
% with the QueueAuthenticPixels() and SyncAuthenticPixels() methods. On
% failure, a NULL image is returned and exception describes the reason for the
% failure.
%
% The format of the CloneImage method is:
%
% Image *CloneImage(const Image *image,const size_t columns,
% const size_t rows,const MagickBooleanType orphan,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the cloned image.
%
% o rows: the number of rows in the cloned image.
%
% o detach: With a value other than 0, the cloned image is detached from
% its parent I/O stream.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CloneImage(const Image *image,const size_t columns,
const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception)
{
Image
*clone_image;
double
scale;
size_t
length;
/*
Clone the image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((image->columns == 0) || (image->rows == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"NegativeOrZeroImageSize","`%s'",image->filename);
return((Image *) NULL);
}
clone_image=(Image *) AcquireCriticalMemory(sizeof(*clone_image));
(void) memset(clone_image,0,sizeof(*clone_image));
clone_image->signature=MagickCoreSignature;
clone_image->storage_class=image->storage_class;
clone_image->number_channels=image->number_channels;
clone_image->number_meta_channels=image->number_meta_channels;
clone_image->metacontent_extent=image->metacontent_extent;
clone_image->colorspace=image->colorspace;
clone_image->read_mask=image->read_mask;
clone_image->write_mask=image->write_mask;
clone_image->alpha_trait=image->alpha_trait;
clone_image->columns=image->columns;
clone_image->rows=image->rows;
clone_image->dither=image->dither;
clone_image->image_info=CloneImageInfo(image->image_info);
(void) CloneImageProfiles(clone_image,image);
(void) CloneImageProperties(clone_image,image);
(void) CloneImageArtifacts(clone_image,image);
GetTimerInfo(&clone_image->timer);
if (image->ascii85 != (void *) NULL)
Ascii85Initialize(clone_image);
clone_image->magick_columns=image->magick_columns;
clone_image->magick_rows=image->magick_rows;
clone_image->type=image->type;
clone_image->channel_mask=image->channel_mask;
clone_image->channel_map=ClonePixelChannelMap(image->channel_map);
(void) CopyMagickString(clone_image->magick_filename,image->magick_filename,
MagickPathExtent);
(void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent);
(void) CopyMagickString(clone_image->filename,image->filename,
MagickPathExtent);
clone_image->progress_monitor=image->progress_monitor;
clone_image->client_data=image->client_data;
clone_image->reference_count=1;
clone_image->next=image->next;
clone_image->previous=image->previous;
clone_image->list=NewImageList();
if (detach == MagickFalse)
clone_image->blob=ReferenceBlob(image->blob);
else
{
clone_image->next=NewImageList();
clone_image->previous=NewImageList();
clone_image->blob=CloneBlobInfo((BlobInfo *) NULL);
}
clone_image->ping=image->ping;
clone_image->debug=IsEventLogging();
clone_image->semaphore=AcquireSemaphoreInfo();
if (image->colormap != (PixelInfo *) NULL)
{
/*
Allocate and copy the image colormap.
*/
clone_image->colors=image->colors;
length=(size_t) image->colors;
clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length+1,
sizeof(*clone_image->colormap));
if (clone_image->colormap == (PixelInfo *) NULL)
{
clone_image=DestroyImage(clone_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) memcpy(clone_image->colormap,image->colormap,length*
sizeof(*clone_image->colormap));
}
if ((columns == 0) || (rows == 0))
{
if (image->montage != (char *) NULL)
(void) CloneString(&clone_image->montage,image->montage);
if (image->directory != (char *) NULL)
(void) CloneString(&clone_image->directory,image->directory);
clone_image->cache=ReferencePixelCache(image->cache);
return(clone_image);
}
scale=1.0;
if (image->columns != 0)
scale=(double) columns/(double) image->columns;
clone_image->page.width=(size_t) floor(scale*image->page.width+0.5);
clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5);
clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5);
scale=1.0;
if (image->rows != 0)
scale=(double) rows/(double) image->rows;
clone_image->page.height=(size_t) floor(scale*image->page.height+0.5);
clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5);
clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5);
clone_image->cache=ClonePixelCache(image->cache);
if (SetImageExtent(clone_image,columns,rows,exception) == MagickFalse)
clone_image=DestroyImage(clone_image);
return(clone_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImageInfo() makes a copy of the given image info structure. If
% NULL is specified, a new image info structure is created initialized to
% default values.
%
% The format of the CloneImageInfo method is:
%
% ImageInfo *CloneImageInfo(const ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport ImageInfo *CloneImageInfo(const ImageInfo *image_info)
{
ImageInfo
*clone_info;
clone_info=AcquireImageInfo();
if (image_info == (ImageInfo *) NULL)
return(clone_info);
clone_info->compression=image_info->compression;
clone_info->temporary=image_info->temporary;
clone_info->adjoin=image_info->adjoin;
clone_info->antialias=image_info->antialias;
clone_info->scene=image_info->scene;
clone_info->number_scenes=image_info->number_scenes;
clone_info->depth=image_info->depth;
if (image_info->size != (char *) NULL)
(void) CloneString(&clone_info->size,image_info->size);
if (image_info->extract != (char *) NULL)
(void) CloneString(&clone_info->extract,image_info->extract);
if (image_info->scenes != (char *) NULL)
(void) CloneString(&clone_info->scenes,image_info->scenes);
if (image_info->page != (char *) NULL)
(void) CloneString(&clone_info->page,image_info->page);
clone_info->interlace=image_info->interlace;
clone_info->endian=image_info->endian;
clone_info->units=image_info->units;
clone_info->quality=image_info->quality;
if (image_info->sampling_factor != (char *) NULL)
(void) CloneString(&clone_info->sampling_factor,
image_info->sampling_factor);
if (image_info->server_name != (char *) NULL)
(void) CloneString(&clone_info->server_name,image_info->server_name);
if (image_info->font != (char *) NULL)
(void) CloneString(&clone_info->font,image_info->font);
if (image_info->texture != (char *) NULL)
(void) CloneString(&clone_info->texture,image_info->texture);
if (image_info->density != (char *) NULL)
(void) CloneString(&clone_info->density,image_info->density);
clone_info->pointsize=image_info->pointsize;
clone_info->fuzz=image_info->fuzz;
clone_info->matte_color=image_info->matte_color;
clone_info->background_color=image_info->background_color;
clone_info->border_color=image_info->border_color;
clone_info->transparent_color=image_info->transparent_color;
clone_info->dither=image_info->dither;
clone_info->monochrome=image_info->monochrome;
clone_info->colorspace=image_info->colorspace;
clone_info->type=image_info->type;
clone_info->orientation=image_info->orientation;
clone_info->ping=image_info->ping;
clone_info->verbose=image_info->verbose;
clone_info->progress_monitor=image_info->progress_monitor;
clone_info->client_data=image_info->client_data;
clone_info->cache=image_info->cache;
if (image_info->cache != (void *) NULL)
clone_info->cache=ReferencePixelCache(image_info->cache);
if (image_info->profile != (void *) NULL)
clone_info->profile=(void *) CloneStringInfo((StringInfo *)
image_info->profile);
SetImageInfoFile(clone_info,image_info->file);
SetImageInfoBlob(clone_info,image_info->blob,image_info->length);
clone_info->stream=image_info->stream;
clone_info->custom_stream=image_info->custom_stream;
(void) CopyMagickString(clone_info->magick,image_info->magick,
MagickPathExtent);
(void) CopyMagickString(clone_info->unique,image_info->unique,
MagickPathExtent);
(void) CopyMagickString(clone_info->filename,image_info->filename,
MagickPathExtent);
clone_info->channel=image_info->channel;
(void) CloneImageOptions(clone_info,image_info);
clone_info->debug=IsEventLogging();
clone_info->signature=image_info->signature;
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o p y I m a g e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CopyImagePixels() copies pixels from the source image as defined by the
% geometry the destination image at the specified offset.
%
% The format of the CopyImagePixels method is:
%
% MagickBooleanType CopyImagePixels(Image *image,const Image *source_image,
% const RectangleInfo *geometry,const OffsetInfo *offset,
% ExceptionInfo *exception);
%
% A description of each parameter follows:
%
% o image: the destination image.
%
% o source_image: the source image.
%
% o geometry: define the dimensions of the source pixel rectangle.
%
% o offset: define the offset in the destination image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType CopyImagePixels(Image *image,
const Image *source_image,const RectangleInfo *geometry,
const OffsetInfo *offset,ExceptionInfo *exception)
{
#define CopyImageTag "Copy/Image"
CacheView
*image_view,
*source_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(source_image != (Image *) NULL);
assert(geometry != (RectangleInfo *) NULL);
assert(offset != (OffsetInfo *) NULL);
if ((offset->x < 0) || (offset->y < 0) ||
((ssize_t) (offset->x+geometry->width) > (ssize_t) image->columns) ||
((ssize_t) (offset->y+geometry->height) > (ssize_t) image->rows))
ThrowBinaryException(OptionError,"GeometryDoesNotContainImage",
image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
/*
Copy image pixels.
*/
status=MagickTrue;
progress=0;
source_view=AcquireVirtualCacheView(source_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,source_image,geometry->height,1)
#endif
for (y=0; y < (ssize_t) geometry->height; y++)
{
MagickBooleanType
sync;
register const Quantum
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(source_view,geometry->x,y+geometry->y,
geometry->width,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,offset->x,y+offset->y,
geometry->width,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) geometry->width; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait source_traits=GetPixelChannelTraits(source_image,channel);
if ((traits == UndefinedPixelTrait) ||
((traits & UpdatePixelTrait) == 0) ||
(source_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(image,channel,p[i],q);
}
p+=GetPixelChannels(source_image);
q+=GetPixelChannels(image);
}
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 critical (MagickCore_CopyImage)
#endif
proceed=SetImageProgress(image,CopyImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImage() dereferences an image, deallocating memory associated with
% the image if the reference count becomes zero.
%
% The format of the DestroyImage method is:
%
% Image *DestroyImage(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport Image *DestroyImage(Image *image)
{
MagickBooleanType
destroy;
/*
Dereference image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
destroy=MagickFalse;
LockSemaphoreInfo(image->semaphore);
image->reference_count--;
if (image->reference_count == 0)
destroy=MagickTrue;
UnlockSemaphoreInfo(image->semaphore);
if (destroy == MagickFalse)
return((Image *) NULL);
/*
Destroy image.
*/
DestroyImagePixels(image);
image->channel_map=DestroyPixelChannelMap(image->channel_map);
if (image->montage != (char *) NULL)
image->montage=DestroyString(image->montage);
if (image->directory != (char *) NULL)
image->directory=DestroyString(image->directory);
if (image->colormap != (PixelInfo *) NULL)
image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
if (image->geometry != (char *) NULL)
image->geometry=DestroyString(image->geometry);
DestroyImageProfiles(image);
DestroyImageProperties(image);
DestroyImageArtifacts(image);
if (image->ascii85 != (Ascii85Info *) NULL)
image->ascii85=(Ascii85Info *) RelinquishMagickMemory(image->ascii85);
if (image->image_info != (ImageInfo *) NULL)
image->image_info=DestroyImageInfo(image->image_info);
DestroyBlob(image);
if (image->semaphore != (SemaphoreInfo *) NULL)
RelinquishSemaphoreInfo(&image->semaphore);
image->signature=(~MagickCoreSignature);
image=(Image *) RelinquishMagickMemory(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImageInfo() deallocates memory associated with an ImageInfo
% structure.
%
% The format of the DestroyImageInfo method is:
%
% ImageInfo *DestroyImageInfo(ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport ImageInfo *DestroyImageInfo(ImageInfo *image_info)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
if (image_info->size != (char *) NULL)
image_info->size=DestroyString(image_info->size);
if (image_info->extract != (char *) NULL)
image_info->extract=DestroyString(image_info->extract);
if (image_info->scenes != (char *) NULL)
image_info->scenes=DestroyString(image_info->scenes);
if (image_info->page != (char *) NULL)
image_info->page=DestroyString(image_info->page);
if (image_info->sampling_factor != (char *) NULL)
image_info->sampling_factor=DestroyString(
image_info->sampling_factor);
if (image_info->server_name != (char *) NULL)
image_info->server_name=DestroyString(
image_info->server_name);
if (image_info->font != (char *) NULL)
image_info->font=DestroyString(image_info->font);
if (image_info->texture != (char *) NULL)
image_info->texture=DestroyString(image_info->texture);
if (image_info->density != (char *) NULL)
image_info->density=DestroyString(image_info->density);
if (image_info->cache != (void *) NULL)
image_info->cache=DestroyPixelCache(image_info->cache);
if (image_info->profile != (StringInfo *) NULL)
image_info->profile=(void *) DestroyStringInfo((StringInfo *)
image_info->profile);
DestroyImageOptions(image_info);
image_info->signature=(~MagickCoreSignature);
image_info=(ImageInfo *) RelinquishMagickMemory(image_info);
return(image_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D i s a s s o c i a t e I m a g e S t r e a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DisassociateImageStream() disassociates the image stream. It checks if the
% blob of the specified image is referenced by other images. If the reference
% count is higher then 1 a new blob is assigned to the specified image.
%
% The format of the DisassociateImageStream method is:
%
% void DisassociateImageStream(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DisassociateImageStream(Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
DisassociateBlob(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageInfo() initializes image_info to default values.
%
% The format of the GetImageInfo method is:
%
% void GetImageInfo(ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport void GetImageInfo(ImageInfo *image_info)
{
char
*synchronize;
ExceptionInfo
*exception;
/*
File and image dimension members.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image_info != (ImageInfo *) NULL);
(void) memset(image_info,0,sizeof(*image_info));
image_info->adjoin=MagickTrue;
image_info->interlace=NoInterlace;
image_info->channel=DefaultChannels;
image_info->quality=UndefinedCompressionQuality;
image_info->antialias=MagickTrue;
image_info->dither=MagickTrue;
synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE");
if (synchronize != (const char *) NULL)
{
image_info->synchronize=IsStringTrue(synchronize);
synchronize=DestroyString(synchronize);
}
exception=AcquireExceptionInfo();
(void) QueryColorCompliance(BackgroundColor,AllCompliance,
&image_info->background_color,exception);
(void) QueryColorCompliance(BorderColor,AllCompliance,
&image_info->border_color,exception);
(void) QueryColorCompliance(MatteColor,AllCompliance,&image_info->matte_color,
exception);
(void) QueryColorCompliance(TransparentColor,AllCompliance,
&image_info->transparent_color,exception);
exception=DestroyExceptionInfo(exception);
image_info->debug=IsEventLogging();
image_info->signature=MagickCoreSignature;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e I n f o F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageInfoFile() returns the image info file member.
%
% The format of the GetImageInfoFile method is:
%
% FILE *GetImageInfoFile(const ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport FILE *GetImageInfoFile(const ImageInfo *image_info)
{
return(image_info->file);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageMask() returns the mask associated with the image.
%
% The format of the GetImageMask method is:
%
% Image *GetImageMask(const Image *image,const PixelMask type,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: the mask type, ReadPixelMask or WritePixelMask.
%
*/
MagickExport Image *GetImageMask(const Image *image,const PixelMask type,
ExceptionInfo *exception)
{
CacheView
*mask_view,
*image_view;
Image
*mask_image;
MagickBooleanType
status;
ssize_t
y;
/*
Get image mask.
*/
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
mask_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (mask_image == (Image *) NULL)
return((Image *) NULL);
status=MagickTrue;
mask_image->alpha_trait=UndefinedPixelTrait;
(void) SetImageColorspace(mask_image,GRAYColorspace,exception);
mask_image->read_mask=MagickFalse;
image_view=AcquireVirtualCacheView(image,exception);
mask_view=AcquireAuthenticCacheView(mask_image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mask_view,0,y,mask_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
switch (type)
{
case WritePixelMask:
{
SetPixelGray(mask_image,GetPixelWriteMask(image,p),q);
break;
}
default:
{
SetPixelGray(mask_image,GetPixelReadMask(image,p),q);
break;
}
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(mask_image);
}
if (SyncCacheViewAuthenticPixels(mask_view,exception) == MagickFalse)
status=MagickFalse;
}
mask_view=DestroyCacheView(mask_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
mask_image=DestroyImage(mask_image);
return(mask_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e R e f e r e n c e C o u n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageReferenceCount() returns the image reference count.
%
% The format of the GetReferenceCount method is:
%
% ssize_t GetImageReferenceCount(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport ssize_t GetImageReferenceCount(Image *image)
{
ssize_t
reference_count;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
LockSemaphoreInfo(image->semaphore);
reference_count=image->reference_count;
UnlockSemaphoreInfo(image->semaphore);
return(reference_count);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e V i r t u a l P i x e l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageVirtualPixelMethod() gets the "virtual pixels" method for the
% image. A virtual pixel is any pixel access that is outside the boundaries
% of the image cache.
%
% The format of the GetImageVirtualPixelMethod() method is:
%
% VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
return(GetPixelCacheVirtualMethod(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n t e r p r e t I m a g e F i l e n a m e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InterpretImageFilename() interprets embedded characters in an image filename.
% The filename length is returned.
%
% The format of the InterpretImageFilename method is:
%
% size_t InterpretImageFilename(const ImageInfo *image_info,Image *image,
% const char *format,int value,char *filename,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info..
%
% o image: the image.
%
% o format: A filename describing the format to use to write the numeric
% argument. Only the first numeric format identifier is replaced.
%
% o value: Numeric value to substitute into format filename.
%
% o filename: return the formatted filename in this character buffer.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport size_t InterpretImageFilename(const ImageInfo *image_info,
Image *image,const char *format,int value,char *filename,
ExceptionInfo *exception)
{
char
*q;
int
c;
MagickBooleanType
canonical;
register const char
*p;
ssize_t
field_width,
offset;
canonical=MagickFalse;
offset=0;
(void) CopyMagickString(filename,format,MagickPathExtent);
for (p=strchr(format,'%'); p != (char *) NULL; p=strchr(p+1,'%'))
{
q=(char *) p+1;
if (*q == '%')
{
p=q+1;
continue;
}
field_width=0;
if (*q == '0')
field_width=(ssize_t) strtol(q,&q,10);
switch (*q)
{
case 'd':
case 'o':
case 'x':
{
q++;
c=(*q);
*q='\0';
(void) FormatLocaleString(filename+(p-format-offset),(size_t)
(MagickPathExtent-(p-format-offset)),p,value);
offset+=(4-field_width);
*q=c;
(void) ConcatenateMagickString(filename,q,MagickPathExtent);
canonical=MagickTrue;
if (*(q-1) != '%')
break;
p++;
break;
}
case '[':
{
char
pattern[MagickPathExtent];
const char
*option;
register char
*r;
register ssize_t
i;
ssize_t
depth;
/*
Image option.
*/
if (strchr(p,']') == (char *) NULL)
break;
depth=1;
r=q+1;
for (i=0; (i < (MagickPathExtent-1L)) && (*r != '\0'); i++)
{
if (*r == '[')
depth++;
if (*r == ']')
depth--;
if (depth <= 0)
break;
pattern[i]=(*r++);
}
pattern[i]='\0';
if (LocaleNCompare(pattern,"filename:",9) != 0)
break;
option=(const char *) NULL;
if (image != (Image *) NULL)
option=GetImageProperty(image,pattern,exception);
if ((option == (const char *) NULL) && (image != (Image *) NULL))
option=GetImageArtifact(image,pattern);
if ((option == (const char *) NULL) &&
(image_info != (ImageInfo *) NULL))
option=GetImageOption(image_info,pattern);
if (option == (const char *) NULL)
break;
q--;
c=(*q);
*q='\0';
(void) CopyMagickString(filename+(p-format-offset),option,(size_t)
(MagickPathExtent-(p-format-offset)));
offset+=strlen(pattern)-4;
*q=c;
(void) ConcatenateMagickString(filename,r+1,MagickPathExtent);
canonical=MagickTrue;
if (*(q-1) != '%')
break;
p++;
break;
}
default:
break;
}
}
for (q=filename; *q != '\0'; q++)
if ((*q == '%') && (*(q+1) == '%'))
{
(void) CopyMagickString(q,q+1,(size_t) (MagickPathExtent-(q-filename)));
canonical=MagickTrue;
}
if (canonical == MagickFalse)
(void) CopyMagickString(filename,format,MagickPathExtent);
return(strlen(filename));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s H i g h D y n a m i c R a n g e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsHighDynamicRangeImage() returns MagickTrue if any pixel component is
% non-integer or exceeds the bounds of the quantum depth (e.g. for Q16
% 0..65535.
%
% The format of the IsHighDynamicRangeImage method is:
%
% MagickBooleanType IsHighDynamicRangeImage(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType IsHighDynamicRangeImage(const Image *image,
ExceptionInfo *exception)
{
#if !defined(MAGICKCORE_HDRI_SUPPORT)
(void) image;
(void) exception;
return(MagickFalse);
#else
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelWriteMask(image,p) <= (QuantumRange/2))
{
p+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
pixel;
PixelTrait
traits;
traits=GetPixelChannelTraits(image,(PixelChannel) i);
if (traits == UndefinedPixelTrait)
continue;
pixel=(double) p[i];
if ((pixel < 0.0) || (pixel > QuantumRange) ||
(pixel != (double) ((QuantumAny) pixel)))
break;
}
p+=GetPixelChannels(image);
if (i < (ssize_t) GetPixelChannels(image))
status=MagickFalse;
}
if (x < (ssize_t) image->columns)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status != MagickFalse ? MagickFalse : MagickTrue);
#endif
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s I m a g e O b j e c t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsImageObject() returns MagickTrue if the image sequence contains a valid
% set of image objects.
%
% The format of the IsImageObject method is:
%
% MagickBooleanType IsImageObject(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickBooleanType IsImageObject(const Image *image)
{
register const Image
*p;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
for (p=image; p != (Image *) NULL; p=GetNextImageInList(p))
if (p->signature != MagickCoreSignature)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTaintImage() returns MagickTrue any pixel in the image has been altered
% since it was first constituted.
%
% The format of the IsTaintImage method is:
%
% MagickBooleanType IsTaintImage(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickBooleanType IsTaintImage(const Image *image)
{
char
magick[MagickPathExtent],
filename[MagickPathExtent];
register const Image
*p;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
(void) CopyMagickString(magick,image->magick,MagickPathExtent);
(void) CopyMagickString(filename,image->filename,MagickPathExtent);
for (p=image; p != (Image *) NULL; p=GetNextImageInList(p))
{
if (p->taint != MagickFalse)
return(MagickTrue);
if (LocaleCompare(p->magick,magick) != 0)
return(MagickTrue);
if (LocaleCompare(p->filename,filename) != 0)
return(MagickTrue);
}
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o d i f y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ModifyImage() ensures that there is only a single reference to the image
% to be modified, updating the provided image pointer to point to a clone of
% the original image if necessary.
%
% The format of the ModifyImage method is:
%
% MagickBooleanType ModifyImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ModifyImage(Image **image,
ExceptionInfo *exception)
{
Image
*clone_image;
assert(image != (Image **) NULL);
assert(*image != (Image *) NULL);
assert((*image)->signature == MagickCoreSignature);
if ((*image)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename);
if (GetImageReferenceCount(*image) <= 1)
return(MagickTrue);
clone_image=CloneImage(*image,0,0,MagickTrue,exception);
LockSemaphoreInfo((*image)->semaphore);
(*image)->reference_count--;
UnlockSemaphoreInfo((*image)->semaphore);
*image=clone_image;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N e w M a g i c k I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NewMagickImage() creates a blank image canvas of the specified size and
% background color.
%
% The format of the NewMagickImage method is:
%
% Image *NewMagickImage(const ImageInfo *image_info,const size_t width,
% const size_t height,const PixelInfo *background,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the image width.
%
% o height: the image height.
%
% o background: the image color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *NewMagickImage(const ImageInfo *image_info,
const size_t width,const size_t height,const PixelInfo *background,
ExceptionInfo *exception)
{
CacheView
*image_view;
Image
*image;
MagickBooleanType
status;
ssize_t
y;
assert(image_info != (const ImageInfo *) NULL);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image_info->signature == MagickCoreSignature);
assert(background != (const PixelInfo *) NULL);
image=AcquireImage(image_info,exception);
image->columns=width;
image->rows=height;
image->colorspace=background->colorspace;
image->alpha_trait=background->alpha_trait;
image->fuzz=background->fuzz;
image->depth=background->depth;
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 Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelViaPixelInfo(image,background,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e f e r e n c e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReferenceImage() increments the reference count associated with an image
% returning a pointer to the image.
%
% The format of the ReferenceImage method is:
%
% Image *ReferenceImage(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport Image *ReferenceImage(Image *image)
{
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
LockSemaphoreInfo(image->semaphore);
image->reference_count++;
UnlockSemaphoreInfo(image->semaphore);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t I m a g e P a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImagePage() resets the image page canvas and position.
%
% The format of the ResetImagePage method is:
%
% MagickBooleanType ResetImagePage(Image *image,const char *page)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o page: the relative page specification.
%
*/
MagickExport MagickBooleanType ResetImagePage(Image *image,const char *page)
{
MagickStatusType
flags;
RectangleInfo
geometry;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
flags=ParseAbsoluteGeometry(page,&geometry);
if ((flags & WidthValue) != 0)
{
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
image->page.width=geometry.width;
image->page.height=geometry.height;
}
if ((flags & AspectValue) != 0)
{
if ((flags & XValue) != 0)
image->page.x+=geometry.x;
if ((flags & YValue) != 0)
image->page.y+=geometry.y;
}
else
{
if ((flags & XValue) != 0)
{
image->page.x=geometry.x;
if ((image->page.width == 0) && (geometry.x > 0))
image->page.width=image->columns+geometry.x;
}
if ((flags & YValue) != 0)
{
image->page.y=geometry.y;
if ((image->page.height == 0) && (geometry.y > 0))
image->page.height=image->rows+geometry.y;
}
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t I m a g e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImagePixels() reset the image pixels, that is, all the pixel components
% are zereod.
%
% The format of the SetImage method is:
%
% MagickBooleanType ResetImagePixels(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ResetImagePixels(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
size_t
length;
ssize_t
y;
void
*pixels;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
pixels=AcquirePixelCachePixels(image,&length,exception);
if (pixels != (void *) NULL)
{
/*
Reset in-core image pixels.
*/
(void) memset(pixels,0,length);
return(MagickTrue);
}
/*
Reset image pixels.
*/
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 Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) memset(q,0,GetPixelChannels(image)*sizeof(Quantum));
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e A l p h a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageAlpha() sets the alpha levels of the image.
%
% The format of the SetImageAlpha method is:
%
% MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o Alpha: the level of transparency: 0 is fully transparent and QuantumRange
% is fully opaque.
%
*/
MagickExport MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
set_opaque,
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
set_opaque=(image->alpha_trait == UndefinedPixelTrait) ? MagickTrue :
MagickFalse;
image->alpha_trait=BlendPixelTrait;
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 Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelWriteMask(image,q) > (QuantumRange/2))
SetPixelAlpha(image,alpha,q);
else if (set_opaque != MagickFalse)
SetPixelAlpha(image,OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e B a c k g r o u n d C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageBackgroundColor() initializes the image pixels to the image
% background color. The background color is defined by the background_color
% member of the image structure.
%
% The format of the SetImage method is:
%
% MagickBooleanType SetImageBackgroundColor(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageBackgroundColor(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
PixelInfo
background;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if ((image->background_color.alpha != OpaqueAlpha) &&
(image->alpha_trait == UndefinedPixelTrait))
(void) SetImageAlphaChannel(image,OnAlphaChannel,exception);
ConformPixelInfo(image,&image->background_color,&background,exception);
/*
Set image background color.
*/
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelViaPixelInfo(image,&background,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C h a n n e l M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageChannelMask() sets the image channel mask from the specified channel
% mask.
%
% The format of the SetImageChannelMask method is:
%
% ChannelType SetImageChannelMask(Image *image,
% const ChannelType channel_mask)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel_mask: the channel mask.
%
*/
MagickExport ChannelType SetImageChannelMask(Image *image,
const ChannelType channel_mask)
{
return(SetPixelChannelMask(image,channel_mask));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageColor() set the entire image canvas to the specified color.
%
% The format of the SetImageColor method is:
%
% MagickBooleanType SetImageColor(Image *image,const PixelInfo *color,
% ExeptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o background: the image color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageColor(Image *image,
const PixelInfo *color,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
assert(color != (const PixelInfo *) NULL);
image->colorspace=color->colorspace;
image->alpha_trait=color->alpha_trait;
image->fuzz=color->fuzz;
image->depth=color->depth;
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 Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelViaPixelInfo(image,color,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e S t o r a g e C l a s s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageStorageClass() sets the image class: DirectClass for true color
% images or PseudoClass for colormapped images.
%
% The format of the SetImageStorageClass method is:
%
% MagickBooleanType SetImageStorageClass(Image *image,
% const ClassType storage_class,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o storage_class: The image class.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageStorageClass(Image *image,
const ClassType storage_class,ExceptionInfo *exception)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image->storage_class=storage_class;
return(SyncImagePixelCache(image,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageExtent() sets the image size (i.e. columns & rows).
%
% The format of the SetImageExtent method is:
%
% MagickBooleanType SetImageExtent(Image *image,const size_t columns,
% const size_t rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: The image width in pixels.
%
% o rows: The image height in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageExtent(Image *image,const size_t columns,
const size_t rows,ExceptionInfo *exception)
{
if ((columns == 0) || (rows == 0))
ThrowBinaryException(ImageError,"NegativeOrZeroImageSize",image->filename);
image->columns=columns;
image->rows=rows;
if ((image->depth == 0) || (image->depth > (8*sizeof(MagickSizeType))))
ThrowBinaryException(ImageError,"ImageDepthNotSupported",image->filename);
return(SyncImagePixelCache(image,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S e t I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfo() initializes the 'magick' field of the ImageInfo structure.
% It is set to a type of image format based on the prefix or suffix of the
% filename. For example, 'ps:image' returns PS indicating a Postscript image.
% JPEG is returned for this filename: 'image.jpg'. The filename prefix has
% precendence over the suffix. Use an optional index enclosed in brackets
% after a file name to specify a desired scene of a multi-resolution image
% format like Photo CD (e.g. img0001.pcd[4]). A True (non-zero) return value
% indicates success.
%
% The format of the SetImageInfo method is:
%
% MagickBooleanType SetImageInfo(ImageInfo *image_info,
% const unsigned int frames,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o frames: the number of images you intend to write.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageInfo(ImageInfo *image_info,
const unsigned int frames,ExceptionInfo *exception)
{
char
component[MagickPathExtent],
magic[MagickPathExtent],
*q;
const MagicInfo
*magic_info;
const MagickInfo
*magick_info;
ExceptionInfo
*sans_exception;
Image
*image;
MagickBooleanType
status;
register const char
*p;
ssize_t
count;
/*
Look for 'image.format' in filename.
*/
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
*component='\0';
GetPathComponent(image_info->filename,SubimagePath,component);
if (*component != '\0')
{
/*
Look for scene specification (e.g. img0001.pcd[4]).
*/
if (IsSceneGeometry(component,MagickFalse) == MagickFalse)
{
if (IsGeometry(component) != MagickFalse)
(void) CloneString(&image_info->extract,component);
}
else
{
size_t
first,
last;
(void) CloneString(&image_info->scenes,component);
image_info->scene=StringToUnsignedLong(image_info->scenes);
image_info->number_scenes=image_info->scene;
p=image_info->scenes;
for (q=(char *) image_info->scenes; *q != '\0'; p++)
{
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
first=(size_t) strtol(p,&q,10);
last=first;
while (isspace((int) ((unsigned char) *q)) != 0)
q++;
if (*q == '-')
last=(size_t) strtol(q+1,&q,10);
if (first > last)
Swap(first,last);
if (first < image_info->scene)
image_info->scene=first;
if (last > image_info->number_scenes)
image_info->number_scenes=last;
p=q;
}
image_info->number_scenes-=image_info->scene-1;
}
}
*component='\0';
if (*image_info->magick == '\0')
GetPathComponent(image_info->filename,ExtensionPath,component);
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (*component != '\0')
if ((LocaleCompare(component,"gz") == 0) ||
(LocaleCompare(component,"Z") == 0) ||
(LocaleCompare(component,"svgz") == 0) ||
(LocaleCompare(component,"wmz") == 0))
{
char
path[MagickPathExtent];
(void) CopyMagickString(path,image_info->filename,MagickPathExtent);
path[strlen(path)-strlen(component)-1]='\0';
GetPathComponent(path,ExtensionPath,component);
}
#endif
#if defined(MAGICKCORE_BZLIB_DELEGATE)
if (*component != '\0')
if (LocaleCompare(component,"bz2") == 0)
{
char
path[MagickPathExtent];
(void) CopyMagickString(path,image_info->filename,MagickPathExtent);
path[strlen(path)-strlen(component)-1]='\0';
GetPathComponent(path,ExtensionPath,component);
}
#endif
image_info->affirm=MagickFalse;
sans_exception=AcquireExceptionInfo();
if (*component != '\0')
{
MagickFormatType
format_type;
register ssize_t
i;
static const char
*format_type_formats[] =
{
"AUTOTRACE",
"BROWSE",
"DCRAW",
"EDIT",
"LAUNCH",
"MPEG:DECODE",
"MPEG:ENCODE",
"PRINT",
"PS:ALPHA",
"PS:CMYK",
"PS:COLOR",
"PS:GRAY",
"PS:MONO",
"SCAN",
"SHOW",
"WIN",
(char *) NULL
};
/*
User specified image format.
*/
(void) CopyMagickString(magic,component,MagickPathExtent);
LocaleUpper(magic);
/*
Look for explicit image formats.
*/
format_type=UndefinedFormatType;
magick_info=GetMagickInfo(magic,sans_exception);
if ((magick_info != (const MagickInfo *) NULL) &&
(magick_info->format_type != UndefinedFormatType))
format_type=magick_info->format_type;
i=0;
while ((format_type == UndefinedFormatType) &&
(format_type_formats[i] != (char *) NULL))
{
if ((*magic == *format_type_formats[i]) &&
(LocaleCompare(magic,format_type_formats[i]) == 0))
format_type=ExplicitFormatType;
i++;
}
if (format_type == UndefinedFormatType)
(void) CopyMagickString(image_info->magick,magic,MagickPathExtent);
else
if (format_type == ExplicitFormatType)
{
image_info->affirm=MagickTrue;
(void) CopyMagickString(image_info->magick,magic,MagickPathExtent);
}
if (LocaleCompare(magic,"RGB") == 0)
image_info->affirm=MagickFalse; /* maybe SGI disguised as RGB */
}
/*
Look for explicit 'format:image' in filename.
*/
*magic='\0';
GetPathComponent(image_info->filename,MagickPath,magic);
if (*magic == '\0')
{
(void) CopyMagickString(magic,image_info->magick,MagickPathExtent);
magick_info=GetMagickInfo(magic,sans_exception);
GetPathComponent(image_info->filename,CanonicalPath,component);
(void) CopyMagickString(image_info->filename,component,MagickPathExtent);
}
else
{
const DelegateInfo
*delegate_info;
/*
User specified image format.
*/
LocaleUpper(magic);
magick_info=GetMagickInfo(magic,sans_exception);
delegate_info=GetDelegateInfo(magic,"*",sans_exception);
if (delegate_info == (const DelegateInfo *) NULL)
delegate_info=GetDelegateInfo("*",magic,sans_exception);
if (((magick_info != (const MagickInfo *) NULL) ||
(delegate_info != (const DelegateInfo *) NULL)) &&
(IsMagickConflict(magic) == MagickFalse))
{
image_info->affirm=MagickTrue;
(void) CopyMagickString(image_info->magick,magic,MagickPathExtent);
GetPathComponent(image_info->filename,CanonicalPath,component);
(void) CopyMagickString(image_info->filename,component,
MagickPathExtent);
}
}
sans_exception=DestroyExceptionInfo(sans_exception);
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickEndianSupport(magick_info) == MagickFalse))
image_info->endian=UndefinedEndian;
if ((image_info->adjoin != MagickFalse) && (frames > 1))
{
/*
Test for multiple image support (e.g. image%02d.png).
*/
(void) InterpretImageFilename(image_info,(Image *) NULL,
image_info->filename,(int) image_info->scene,component,exception);
if ((LocaleCompare(component,image_info->filename) != 0) &&
(strchr(component,'%') == (char *) NULL))
image_info->adjoin=MagickFalse;
}
if ((image_info->adjoin != MagickFalse) && (frames > 0))
{
/*
Some image formats do not support multiple frames per file.
*/
magick_info=GetMagickInfo(magic,exception);
if (magick_info != (const MagickInfo *) NULL)
if (GetMagickAdjoin(magick_info) == MagickFalse)
image_info->adjoin=MagickFalse;
}
if (image_info->affirm != MagickFalse)
return(MagickTrue);
if (frames == 0)
{
unsigned char
*magick;
size_t
magick_size;
/*
Determine the image format from the first few bytes of the file.
*/
magick_size=GetMagicPatternExtent(exception);
if (magick_size == 0)
return(MagickFalse);
image=AcquireImage(image_info,exception);
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImage(image);
return(MagickFalse);
}
if ((IsBlobSeekable(image) == MagickFalse) ||
(IsBlobExempt(image) != MagickFalse))
{
/*
Copy image to seekable temporary file.
*/
*component='\0';
status=ImageToFile(image,component,exception);
(void) CloseBlob(image);
if (status == MagickFalse)
{
image=DestroyImage(image);
return(MagickFalse);
}
SetImageInfoFile(image_info,(FILE *) NULL);
(void) CopyMagickString(image->filename,component,MagickPathExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImage(image);
return(MagickFalse);
}
(void) CopyMagickString(image_info->filename,component,
MagickPathExtent);
image_info->temporary=MagickTrue;
}
magick=(unsigned char *) AcquireMagickMemory(magick_size);
if (magick == (unsigned char *) NULL)
{
(void) CloseBlob(image);
image=DestroyImage(image);
return(MagickFalse);
}
(void) memset(magick,0,magick_size);
count=ReadBlob(image,magick_size,magick);
(void) SeekBlob(image,-((MagickOffsetType) count),SEEK_CUR);
(void) CloseBlob(image);
image=DestroyImage(image);
/*
Check magic.xml configuration file.
*/
sans_exception=AcquireExceptionInfo();
magic_info=GetMagicInfo(magick,(size_t) count,sans_exception);
magick=(unsigned char *) RelinquishMagickMemory(magick);
if ((magic_info != (const MagicInfo *) NULL) &&
(GetMagicName(magic_info) != (char *) NULL))
{
/*
Try to use magick_info that was determined earlier by the extension
*/
if ((magick_info != (const MagickInfo *) NULL) &&
(GetMagickUseExtension(magick_info) != MagickFalse) &&
(LocaleCompare(magick_info->module,GetMagicName(
magic_info)) == 0))
(void) CopyMagickString(image_info->magick,magick_info->name,
MagickPathExtent);
else
{
(void) CopyMagickString(image_info->magick,GetMagicName(
magic_info),MagickPathExtent);
magick_info=GetMagickInfo(image_info->magick,sans_exception);
}
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickEndianSupport(magick_info) == MagickFalse))
image_info->endian=UndefinedEndian;
sans_exception=DestroyExceptionInfo(sans_exception);
return(MagickTrue);
}
magick_info=GetMagickInfo(image_info->magick,sans_exception);
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickEndianSupport(magick_info) == MagickFalse))
image_info->endian=UndefinedEndian;
sans_exception=DestroyExceptionInfo(sans_exception);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e I n f o B l o b %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfoBlob() sets the image info blob member.
%
% The format of the SetImageInfoBlob method is:
%
% void SetImageInfoBlob(ImageInfo *image_info,const void *blob,
% const size_t length)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o blob: the blob.
%
% o length: the blob length.
%
*/
MagickExport void SetImageInfoBlob(ImageInfo *image_info,const void *blob,
const size_t length)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
image_info->blob=(void *) blob;
image_info->length=length;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e I n f o C u s t o m S t r e a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfoCustomStream() sets the image info custom stream handlers.
%
% The format of the SetImageInfoCustomStream method is:
%
% void SetImageInfoCustomStream(ImageInfo *image_info,
% CustomStreamInfo *custom_stream)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o custom_stream: your custom stream methods.
%
*/
MagickExport void SetImageInfoCustomStream(ImageInfo *image_info,
CustomStreamInfo *custom_stream)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
image_info->custom_stream=(CustomStreamInfo *) custom_stream;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e I n f o F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfoFile() sets the image info file member.
%
% The format of the SetImageInfoFile method is:
%
% void SetImageInfoFile(ImageInfo *image_info,FILE *file)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o file: the file.
%
*/
MagickExport void SetImageInfoFile(ImageInfo *image_info,FILE *file)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
image_info->file=file;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageMask() associates a mask with the image. The mask must be the same
% dimensions as the image.
%
% The format of the SetImageMask method is:
%
% MagickBooleanType SetImageMask(Image *image,const PixelMask type,
% const Image *mask,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: the mask type, ReadPixelMask or WritePixelMask.
%
% o mask: the image mask.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageMask(Image *image,const PixelMask type,
const Image *mask,ExceptionInfo *exception)
{
CacheView
*mask_view,
*image_view;
MagickBooleanType
status;
ssize_t
y;
/*
Set image mask.
*/
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (mask == (const Image *) NULL)
{
switch (type)
{
case WritePixelMask: image->write_mask=MagickFalse; break;
default: image->read_mask=MagickFalse; break;
}
return(SyncImagePixelCache(image,exception));
}
switch (type)
{
case WritePixelMask: image->write_mask=MagickTrue; break;
default: image->read_mask=MagickTrue; break;
}
if (SyncImagePixelCache(image,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
mask_view=AcquireVirtualCacheView(mask,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(mask,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(mask_view,0,y,mask->columns,1,exception);
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
intensity;
intensity=0.0;
if ((x < (ssize_t) mask->columns) && (y < (ssize_t) mask->rows))
intensity=GetPixelIntensity(mask,p);
switch (type)
{
case WritePixelMask:
{
SetPixelWriteMask(image,ClampToQuantum(intensity),q);
break;
}
default:
{
SetPixelReadMask(image,ClampToQuantum(intensity),q);
break;
}
}
p+=GetPixelChannels(mask);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
mask_view=DestroyCacheView(mask_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e R e g i o n M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageRegionMask() associates a mask with the image as defined by the
% specified region.
%
% The format of the SetImageRegionMask method is:
%
% MagickBooleanType SetImageRegionMask(Image *image,const PixelMask type,
% const RectangleInfo *region,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: the mask type, ReadPixelMask or WritePixelMask.
%
% o geometry: the mask region.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageRegionMask(Image *image,
const PixelMask type,const RectangleInfo *region,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
/*
Set image mask as defined by the region.
*/
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (region == (const RectangleInfo *) NULL)
{
switch (type)
{
case WritePixelMask: image->write_mask=MagickFalse; break;
default: image->read_mask=MagickFalse; break;
}
return(SyncImagePixelCache(image,exception));
}
switch (type)
{
case WritePixelMask: image->write_mask=MagickTrue; break;
default: image->read_mask=MagickTrue; break;
}
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
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 Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
Quantum
pixel;
pixel=(Quantum) 0;
if (((x >= region->x) && (x < (region->x+(ssize_t) region->width))) &&
((y >= region->y) && (y < (region->y+(ssize_t) region->height))))
pixel=QuantumRange;
switch (type)
{
case WritePixelMask:
{
SetPixelWriteMask(image,pixel,q);
break;
}
default:
{
SetPixelReadMask(image,pixel,q);
break;
}
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e V i r t u a l P i x e l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageVirtualPixelMethod() sets the "virtual pixels" method for the
% image and returns the previous setting. A virtual pixel is any pixel access
% that is outside the boundaries of the image cache.
%
% The format of the SetImageVirtualPixelMethod() method is:
%
% VirtualPixelMethod SetImageVirtualPixelMethod(Image *image,
% const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: choose the type of virtual pixel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport VirtualPixelMethod SetImageVirtualPixelMethod(Image *image,
const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception)
{
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
return(SetPixelCacheVirtualMethod(image,virtual_pixel_method,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S m u s h I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SmushImages() takes all images from the current image pointer to the end
% of the image list and smushes them to each other top-to-bottom if the
% stack parameter is true, otherwise left-to-right.
%
% The current gravity setting now effects how the image is justified in the
% final image.
%
% The format of the SmushImages method is:
%
% Image *SmushImages(const Image *images,const MagickBooleanType stack,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o stack: A value other than 0 stacks the images top-to-bottom.
%
% o offset: minimum distance in pixels between images.
%
% o exception: return any errors or warnings in this structure.
%
*/
static ssize_t SmushXGap(const Image *smush_image,const Image *images,
const ssize_t offset,ExceptionInfo *exception)
{
CacheView
*left_view,
*right_view;
const Image
*left_image,
*right_image;
RectangleInfo
left_geometry,
right_geometry;
register const Quantum
*p;
register ssize_t
i,
y;
size_t
gap;
ssize_t
x;
if (images->previous == (Image *) NULL)
return(0);
right_image=images;
SetGeometry(smush_image,&right_geometry);
GravityAdjustGeometry(right_image->columns,right_image->rows,
right_image->gravity,&right_geometry);
left_image=images->previous;
SetGeometry(smush_image,&left_geometry);
GravityAdjustGeometry(left_image->columns,left_image->rows,
left_image->gravity,&left_geometry);
gap=right_image->columns;
left_view=AcquireVirtualCacheView(left_image,exception);
right_view=AcquireVirtualCacheView(right_image,exception);
for (y=0; y < (ssize_t) smush_image->rows; y++)
{
for (x=(ssize_t) left_image->columns-1; x > 0; x--)
{
p=GetCacheViewVirtualPixels(left_view,x,left_geometry.y+y,1,1,exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(left_image,p) != TransparentAlpha) ||
((left_image->columns-x-1) >= gap))
break;
}
i=(ssize_t) left_image->columns-x-1;
for (x=0; x < (ssize_t) right_image->columns; x++)
{
p=GetCacheViewVirtualPixels(right_view,x,right_geometry.y+y,1,1,
exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(right_image,p) != TransparentAlpha) ||
((x+i) >= (ssize_t) gap))
break;
}
if ((x+i) < (ssize_t) gap)
gap=(size_t) (x+i);
}
right_view=DestroyCacheView(right_view);
left_view=DestroyCacheView(left_view);
if (y < (ssize_t) smush_image->rows)
return(offset);
return((ssize_t) gap-offset);
}
static ssize_t SmushYGap(const Image *smush_image,const Image *images,
const ssize_t offset,ExceptionInfo *exception)
{
CacheView
*bottom_view,
*top_view;
const Image
*bottom_image,
*top_image;
RectangleInfo
bottom_geometry,
top_geometry;
register const Quantum
*p;
register ssize_t
i,
x;
size_t
gap;
ssize_t
y;
if (images->previous == (Image *) NULL)
return(0);
bottom_image=images;
SetGeometry(smush_image,&bottom_geometry);
GravityAdjustGeometry(bottom_image->columns,bottom_image->rows,
bottom_image->gravity,&bottom_geometry);
top_image=images->previous;
SetGeometry(smush_image,&top_geometry);
GravityAdjustGeometry(top_image->columns,top_image->rows,top_image->gravity,
&top_geometry);
gap=bottom_image->rows;
top_view=AcquireVirtualCacheView(top_image,exception);
bottom_view=AcquireVirtualCacheView(bottom_image,exception);
for (x=0; x < (ssize_t) smush_image->columns; x++)
{
for (y=(ssize_t) top_image->rows-1; y > 0; y--)
{
p=GetCacheViewVirtualPixels(top_view,top_geometry.x+x,y,1,1,exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(top_image,p) != TransparentAlpha) ||
((top_image->rows-y-1) >= gap))
break;
}
i=(ssize_t) top_image->rows-y-1;
for (y=0; y < (ssize_t) bottom_image->rows; y++)
{
p=GetCacheViewVirtualPixels(bottom_view,bottom_geometry.x+x,y,1,1,
exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(bottom_image,p) != TransparentAlpha) ||
((y+i) >= (ssize_t) gap))
break;
}
if ((y+i) < (ssize_t) gap)
gap=(size_t) (y+i);
}
bottom_view=DestroyCacheView(bottom_view);
top_view=DestroyCacheView(top_view);
if (x < (ssize_t) smush_image->columns)
return(offset);
return((ssize_t) gap-offset);
}
MagickExport Image *SmushImages(const Image *images,
const MagickBooleanType stack,const ssize_t offset,ExceptionInfo *exception)
{
#define SmushImageTag "Smush/Image"
const Image
*image;
Image
*smush_image;
MagickBooleanType
proceed,
status;
MagickOffsetType
n;
PixelTrait
alpha_trait;
RectangleInfo
geometry;
register const Image
*next;
size_t
height,
number_images,
width;
ssize_t
x_offset,
y_offset;
/*
Compute maximum area of smushed area.
*/
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=images;
alpha_trait=image->alpha_trait;
number_images=1;
width=image->columns;
height=image->rows;
next=GetNextImageInList(image);
for ( ; next != (Image *) NULL; next=GetNextImageInList(next))
{
if (next->alpha_trait != UndefinedPixelTrait)
alpha_trait=BlendPixelTrait;
number_images++;
if (stack != MagickFalse)
{
if (next->columns > width)
width=next->columns;
height+=next->rows;
if (next->previous != (Image *) NULL)
height+=offset;
continue;
}
width+=next->columns;
if (next->previous != (Image *) NULL)
width+=offset;
if (next->rows > height)
height=next->rows;
}
/*
Smush images.
*/
smush_image=CloneImage(image,width,height,MagickTrue,exception);
if (smush_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(smush_image,DirectClass,exception) == MagickFalse)
{
smush_image=DestroyImage(smush_image);
return((Image *) NULL);
}
smush_image->alpha_trait=alpha_trait;
(void) SetImageBackgroundColor(smush_image,exception);
status=MagickTrue;
x_offset=0;
y_offset=0;
for (n=0; n < (MagickOffsetType) number_images; n++)
{
SetGeometry(smush_image,&geometry);
GravityAdjustGeometry(image->columns,image->rows,image->gravity,&geometry);
if (stack != MagickFalse)
{
x_offset-=geometry.x;
y_offset-=SmushYGap(smush_image,image,offset,exception);
}
else
{
x_offset-=SmushXGap(smush_image,image,offset,exception);
y_offset-=geometry.y;
}
status=CompositeImage(smush_image,image,OverCompositeOp,MagickTrue,x_offset,
y_offset,exception);
proceed=SetImageProgress(image,SmushImageTag,n,number_images);
if (proceed == MagickFalse)
break;
if (stack == MagickFalse)
{
x_offset+=(ssize_t) image->columns;
y_offset=0;
}
else
{
x_offset=0;
y_offset+=(ssize_t) image->rows;
}
image=GetNextImageInList(image);
}
if (stack == MagickFalse)
smush_image->columns=(size_t) x_offset;
else
smush_image->rows=(size_t) y_offset;
if (status == MagickFalse)
smush_image=DestroyImage(smush_image);
return(smush_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t r i p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% StripImage() strips an image of all profiles and comments.
%
% The format of the StripImage method is:
%
% MagickBooleanType StripImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType StripImage(Image *image,ExceptionInfo *exception)
{
MagickBooleanType
status;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
(void) exception;
DestroyImageProfiles(image);
(void) DeleteImageProperty(image,"comment");
(void) DeleteImageProperty(image,"date:create");
(void) DeleteImageProperty(image,"date:modify");
status=SetImageArtifact(image,"png:exclude-chunk",
"bKGD,caNv,cHRM,eXIf,gAMA,iCCP,iTXt,pHYs,sRGB,tEXt,zCCP,zTXt,date");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S y n c I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImage() initializes the red, green, and blue intensities of each pixel
% as defined by the colormap index.
%
% The format of the SyncImage method is:
%
% MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline Quantum PushColormapIndex(Image *image,const Quantum index,
MagickBooleanType *range_exception)
{
if ((size_t) index < image->colors)
return(index);
*range_exception=MagickTrue;
return((Quantum) 0);
}
MagickExport MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
range_exception,
status,
taint;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (image->ping != MagickFalse)
return(MagickTrue);
if (image->storage_class != PseudoClass)
return(MagickFalse);
assert(image->colormap != (PixelInfo *) NULL);
range_exception=MagickFalse;
status=MagickTrue;
taint=image->taint;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(range_exception,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
index;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
index=PushColormapIndex(image,GetPixelIndex(image,q),&range_exception);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->taint=taint;
if ((image->ping == MagickFalse) && (range_exception != MagickFalse))
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"InvalidColormapIndex","`%s'",image->filename);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S y n c I m a g e S e t t i n g s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImageSettings() syncs any image_info global options into per-image
% attributes.
%
% Note: in IMv6 free form 'options' were always mapped into 'artifacts', so
% that operations and coders can find such settings. In IMv7 if a desired
% per-image artifact is not set, then it will directly look for a global
% option as a fallback, as such this copy is no longer needed, only the
% link set up.
%
% The format of the SyncImageSettings method is:
%
% MagickBooleanType SyncImageSettings(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
% MagickBooleanType SyncImagesSettings(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SyncImagesSettings(ImageInfo *image_info,
Image *images,ExceptionInfo *exception)
{
Image
*image;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
image=images;
for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
(void) SyncImageSettings(image_info,image,exception);
(void) DeleteImageOption(image_info,"page");
return(MagickTrue);
}
MagickExport MagickBooleanType SyncImageSettings(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const char
*option;
GeometryInfo
geometry_info;
MagickStatusType
flags;
ResolutionType
units;
/*
Sync image options.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
option=GetImageOption(image_info,"background");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->background_color,
exception);
option=GetImageOption(image_info,"black-point-compensation");
if (option != (const char *) NULL)
image->black_point_compensation=(MagickBooleanType) ParseCommandOption(
MagickBooleanOptions,MagickFalse,option);
option=GetImageOption(image_info,"blue-primary");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.blue_primary.x=geometry_info.rho;
image->chromaticity.blue_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.blue_primary.y=image->chromaticity.blue_primary.x;
}
option=GetImageOption(image_info,"bordercolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->border_color,
exception);
/* FUTURE: do not sync compose to per-image compose setting here */
option=GetImageOption(image_info,"compose");
if (option != (const char *) NULL)
image->compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions,
MagickFalse,option);
/* -- */
option=GetImageOption(image_info,"compress");
if (option != (const char *) NULL)
image->compression=(CompressionType) ParseCommandOption(
MagickCompressOptions,MagickFalse,option);
option=GetImageOption(image_info,"debug");
if (option != (const char *) NULL)
image->debug=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions,
MagickFalse,option);
option=GetImageOption(image_info,"density");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
option=GetImageOption(image_info,"depth");
if (option != (const char *) NULL)
image->depth=StringToUnsignedLong(option);
option=GetImageOption(image_info,"endian");
if (option != (const char *) NULL)
image->endian=(EndianType) ParseCommandOption(MagickEndianOptions,
MagickFalse,option);
option=GetImageOption(image_info,"filter");
if (option != (const char *) NULL)
image->filter=(FilterType) ParseCommandOption(MagickFilterOptions,
MagickFalse,option);
option=GetImageOption(image_info,"fuzz");
if (option != (const char *) NULL)
image->fuzz=StringToDoubleInterval(option,(double) QuantumRange+1.0);
option=GetImageOption(image_info,"gravity");
if (option != (const char *) NULL)
image->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,option);
option=GetImageOption(image_info,"green-primary");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.green_primary.x=geometry_info.rho;
image->chromaticity.green_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.green_primary.y=image->chromaticity.green_primary.x;
}
option=GetImageOption(image_info,"intent");
if (option != (const char *) NULL)
image->rendering_intent=(RenderingIntent) ParseCommandOption(
MagickIntentOptions,MagickFalse,option);
option=GetImageOption(image_info,"intensity");
if (option != (const char *) NULL)
image->intensity=(PixelIntensityMethod) ParseCommandOption(
MagickPixelIntensityOptions,MagickFalse,option);
option=GetImageOption(image_info,"interlace");
if (option != (const char *) NULL)
image->interlace=(InterlaceType) ParseCommandOption(MagickInterlaceOptions,
MagickFalse,option);
option=GetImageOption(image_info,"interpolate");
if (option != (const char *) NULL)
image->interpolate=(PixelInterpolateMethod) ParseCommandOption(
MagickInterpolateOptions,MagickFalse,option);
option=GetImageOption(image_info,"loop");
if (option != (const char *) NULL)
image->iterations=StringToUnsignedLong(option);
option=GetImageOption(image_info,"mattecolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->matte_color,
exception);
option=GetImageOption(image_info,"orient");
if (option != (const char *) NULL)
image->orientation=(OrientationType) ParseCommandOption(
MagickOrientationOptions,MagickFalse,option);
option=GetImageOption(image_info,"page");
if (option != (const char *) NULL)
{
char
*geometry;
geometry=GetPageGeometry(option);
flags=ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
}
option=GetImageOption(image_info,"quality");
if (option != (const char *) NULL)
image->quality=StringToUnsignedLong(option);
option=GetImageOption(image_info,"red-primary");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.red_primary.x=geometry_info.rho;
image->chromaticity.red_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.red_primary.y=image->chromaticity.red_primary.x;
}
if (image_info->quality != UndefinedCompressionQuality)
image->quality=image_info->quality;
option=GetImageOption(image_info,"scene");
if (option != (const char *) NULL)
image->scene=StringToUnsignedLong(option);
option=GetImageOption(image_info,"taint");
if (option != (const char *) NULL)
image->taint=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions,
MagickFalse,option);
option=GetImageOption(image_info,"tile-offset");
if (option != (const char *) NULL)
{
char
*geometry;
geometry=GetPageGeometry(option);
flags=ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
}
option=GetImageOption(image_info,"transparent-color");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->transparent_color,
exception);
option=GetImageOption(image_info,"type");
if (option != (const char *) NULL)
image->type=(ImageType) ParseCommandOption(MagickTypeOptions,MagickFalse,
option);
option=GetImageOption(image_info,"units");
units=image_info->units;
if (option != (const char *) NULL)
units=(ResolutionType) ParseCommandOption(MagickResolutionOptions,
MagickFalse,option);
if (units != UndefinedResolution)
{
if (image->units != units)
switch (image->units)
{
case PixelsPerInchResolution:
{
if (units == PixelsPerCentimeterResolution)
{
image->resolution.x/=2.54;
image->resolution.y/=2.54;
}
break;
}
case PixelsPerCentimeterResolution:
{
if (units == PixelsPerInchResolution)
{
image->resolution.x=(double) ((size_t) (100.0*2.54*
image->resolution.x+0.5))/100.0;
image->resolution.y=(double) ((size_t) (100.0*2.54*
image->resolution.y+0.5))/100.0;
}
break;
}
default:
break;
}
image->units=units;
}
option=GetImageOption(image_info,"virtual-pixel");
if (option != (const char *) NULL)
(void) SetImageVirtualPixelMethod(image,(VirtualPixelMethod)
ParseCommandOption(MagickVirtualPixelOptions,MagickFalse,option),
exception);
option=GetImageOption(image_info,"white-point");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.white_point.x=geometry_info.rho;
image->chromaticity.white_point.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.white_point.y=image->chromaticity.white_point.x;
}
/*
Pointer to allow the lookup of pre-image artifact will fallback to a global
option setting/define. This saves a lot of duplication of global options
into per-image artifacts, while ensuring only specifically set per-image
artifacts are preserved when parenthesis ends.
*/
if (image->image_info != (ImageInfo *) NULL)
image->image_info=DestroyImageInfo(image->image_info);
image->image_info=CloneImageInfo(image_info);
return(MagickTrue);
}
|
GB_sparse_masker_template.c | //------------------------------------------------------------------------------
// GB_sparse_masker_template: R = masker (C, M, Z) where R is sparse/hyper
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Computes C<M>=Z or C<!M>=Z, returning the result in R, which is sparse or
// hypersparse. The input matrix C is not modified. Effectively, this
// computes R=C and then R<M>=Z or R<!M>=Z. If the C_replace descriptor is
// enabled, then C has already been cleared, and is an empty (but non-NULL)
// matrix.
// phase1: does not compute R itself, but just counts the # of entries in each
// vector of R. Fine tasks compute the # of entries in their slice of a
// single vector of R, and the results are cumsum'd.
// phase2: computes R, using the counts computed by phase1.
// C is sparse or hypersparse. M and Z can have any sparsity structure.
// ------------------------------------------
// C <!M> = Z R
// ------------------------------------------
// sparse sparse sparse sparse
// sparse bitmap sparse sparse
// sparse full sparse sparse
// ------------------------------------------
// C <M> = Z R
// ------------------------------------------
// sparse sparse sparse sparse
// sparse sparse bitmap sparse
// sparse sparse full sparse
// sparse bitmap sparse sparse
// sparse full sparse sparse
// FUTURE:: add special cases for C==Z, C==M, and Z==M aliases
//------------------------------------------------------------------------------
// R(i,j) = Z(i,j) when Z is sparse or hypersparse
//------------------------------------------------------------------------------
#undef GB_COPY_Z
#if defined ( GB_PHASE_1_OF_2 )
#define GB_COPY_Z \
{ \
rjnz++ ; \
}
#elif defined ( GB_ISO_MASKER )
#define GB_COPY_Z \
{ \
Ri [pR] = i ; \
pR++ ; \
}
#else
#define GB_COPY_Z \
{ \
Ri [pR] = i ; \
memcpy (Rx +(pR)*rsize, Zx +(Z_iso ? 0:(pZ)*rsize), rsize) ; \
pR++ ; \
}
#endif
//------------------------------------------------------------------------------
// R(i,j) = Z(i,j) when Z is bitmap or full
//------------------------------------------------------------------------------
#undef GB_COPY_Z_BITMAP_OR_FULL
#if defined ( GB_PHASE_1_OF_2 )
#define GB_COPY_Z_BITMAP_OR_FULL \
{ \
rjnz += GBB (Zb, pZ_start + i - iZ_first) ; \
}
#elif defined ( GB_ISO_MASKER )
#define GB_COPY_Z_BITMAP_OR_FULL \
{ \
int64_t pZ = pZ_start + i - iZ_first ; \
if (GBB (Zb, pZ)) \
{ \
Ri [pR] = i ; \
pR++ ; \
} \
}
#else
#define GB_COPY_Z_BITMAP_OR_FULL \
{ \
int64_t pZ = pZ_start + i - iZ_first ; \
if (GBB (Zb, pZ)) \
{ \
Ri [pR] = i ; \
memcpy (Rx +(pR)*rsize, Zx +(Z_iso ? 0:(pZ)*rsize), rsize) ; \
pR++ ; \
} \
}
#endif
//------------------------------------------------------------------------------
// R(i,j) = C(i,j)
//------------------------------------------------------------------------------
#undef GB_COPY_C
#if defined ( GB_PHASE_1_OF_2 )
#define GB_COPY_C \
{ \
rjnz++ ; \
}
#elif defined ( GB_ISO_MASKER )
#define GB_COPY_C \
{ \
Ri [pR] = i ; \
pR++ ; \
}
#else
#define GB_COPY_C \
{ \
Ri [pR] = i ; \
memcpy (Rx +(pR)*rsize, Cx +(C_iso ? 0:(pC)*rsize), rsize) ; \
pR++ ; \
}
#endif
//------------------------------------------------------------------------------
// template for R = masker (C, M, Z) when R is sparse or hypersparse
//------------------------------------------------------------------------------
{
//--------------------------------------------------------------------------
// phase1: count entries in each C(:,j)
// phase2: compute C
//--------------------------------------------------------------------------
ASSERT (C_is_sparse || C_is_hyper) ;
#pragma omp parallel for num_threads(R_nthreads) schedule(dynamic,1)
for (taskid = 0 ; taskid < R_ntasks ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
int64_t kfirst = TaskList [taskid].kfirst ;
int64_t klast = TaskList [taskid].klast ;
bool fine_task = (klast == -1) ;
int64_t len ;
if (fine_task)
{
// a fine task operates on a slice of a single vector
klast = kfirst ;
len = TaskList [taskid].len ;
}
else
{
// a coarse task operates on one or more whole vectors
len = vlen ;
}
//----------------------------------------------------------------------
// compute all vectors in this task
//----------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//------------------------------------------------------------------
// get j, the kth vector of R
//------------------------------------------------------------------
int64_t j = GBH (Rh, k) ;
#if defined ( GB_PHASE_1_OF_2 )
int64_t rjnz = 0 ;
#else
int64_t pR, pR_end ;
if (fine_task)
{
// A fine task computes a slice of R(:,j)
pR = TaskList [taskid ].pC ;
pR_end = TaskList [taskid+1].pC ;
ASSERT (Rp [k] <= pR && pR <= pR_end && pR_end <= Rp [k+1]) ;
}
else
{
// The vectors of R are never sliced for a coarse task.
pR = Rp [k] ;
pR_end = Rp [k+1] ;
}
int64_t rjnz = pR_end - pR ;
if (rjnz == 0)
{
continue ;
}
#endif
//------------------------------------------------------------------
// get C(:,j)
//------------------------------------------------------------------
int64_t pC = -1, pC_end = -1 ;
if (fine_task)
{
// A fine task operates on Ci,Cx [pC...pC_end-1], which is
// a subset of the vector C(:,j)
pC = TaskList [taskid].pA ;
pC_end = TaskList [taskid].pA_end ;
}
else
{
// A coarse task operates on the entire vector C(:,j)
int64_t kC = (R_to_C == NULL) ? j : R_to_C [k] ;
if (kC >= 0)
{
pC = Cp [kC] ;
pC_end = Cp [kC+1] ;
}
}
int64_t cjnz = pC_end - pC ; // nnz in C(:,j) for this slice
bool cdense = (cjnz == len) && (cjnz > 0) ;
#if defined ( GB_PHASE_2_OF_2 ) || defined ( GB_DEBUG )
// get the first index in C(:,j) for this vector
int64_t iC_first = -1 ;
if (cjnz > 0) iC_first = Ci [pC] ;
#endif
#ifdef GB_DEBUG
int64_t iC_last = -1 ;
if (cjnz > 0) iC_last = Ci [pC_end-1] ;
#endif
//------------------------------------------------------------------
// get Z(:,j)
//------------------------------------------------------------------
int64_t pZ = -1, pZ_end = -1 ;
if (fine_task)
{
// A fine task operates on Zi,Zx [pZ...pZ_end-1], which is
// a subset of the vector Z(:,j)
pZ = TaskList [taskid].pB ;
pZ_end = TaskList [taskid].pB_end ;
}
else
{
// A coarse task operates on the entire vector Z(:,j)
int64_t kZ = (R_to_Z == NULL) ? j : R_to_Z [k] ;
if (kZ >= 0)
{
pZ = GBP (Zp, kZ, vlen) ;
pZ_end = GBP (Zp, kZ+1, vlen) ;
}
}
int64_t zjnz = pZ_end - pZ ; // nnz in Z(:,j) for this slice
int64_t pZ_start = pZ ;
bool zdense = (zjnz == len) && (zjnz > 0) ;
int64_t iZ_first = -1, iZ_last = -1 ;
if (zjnz > 0)
{
iZ_first = GBI (Zi, pZ, vlen) ;
iZ_last = GBI (Zi, pZ_end-1, vlen) ;
}
//------------------------------------------------------------------
// get M(:,j)
//------------------------------------------------------------------
int64_t pM = -1, pM_end = -1 ;
if (fine_task)
{
// A fine task operates on Mi,Mx [pM...pM_end-1], which is
// a subset of the vector M(:,j)
pM = TaskList [taskid].pM ;
pM_end = TaskList [taskid].pM_end ;
}
else
{
// A coarse task operates on the entire vector M (:,j)
int64_t kM = (R_to_M == NULL) ? j : R_to_M [k] ;
if (kM >= 0)
{
pM = GBP (Mp, kM, vlen) ;
pM_end = GBP (Mp, kM+1, vlen) ;
}
}
int64_t mjnz = pM_end - pM ; // nnz (M (:,j))
bool mdense = (mjnz == len) && (mjnz > 0) ;
// get the first index in M(:,j) for this vector
int64_t iM_first = -1 ;
int64_t pM_first = pM ;
if (mjnz > 0) iM_first = GBI (Mi, pM_first, vlen) ;
//------------------------------------------------------------------
// R(:,j) = masker (C (:,j), M (:,j), Z (:,j))
//------------------------------------------------------------------
if (Z_is_bitmap || Z_is_full)
{
//--------------------------------------------------------------
// Method01: Z is bitmap or full; M is sparse or hypersparse
//--------------------------------------------------------------
// ------------------------------------------
// C <M> = Z R
// ------------------------------------------
// sparse sparse bitmap sparse
// sparse sparse full sparse
// M is sparse or hypersparse, and not complemented.
// Otherwise, R is bitmap and not computed here, but in
// GB_bitmap_masker_template instead.
ASSERT (M_is_sparse || M_is_hyper) ;
ASSERT (!Mask_comp) ;
// 2-way merge of C(:,j) and M(:,j) and direct lookup of Z
while (pC < pC_end && pM < pM_end)
{
int64_t iC = Ci [pC] ;
int64_t iM = Mi [pM] ;
if (iC < iM)
{
// C(i,j) is present but M(i,j) is not
// R(i,j) = C(i,j)
int64_t i = iC ;
GB_COPY_C ;
pC++ ;
}
else if (iC > iM)
{
// M(i,j) is present but C(i,j) is not
int64_t i = iM ;
bool mij = GB_mcast (Mx, pM, msize) ;
if (mij)
{
// R(i,j) = Z(i,j)
GB_COPY_Z_BITMAP_OR_FULL ;
}
pM++ ;
}
else
{
// both C(i,j) and M(i,j) are present
int64_t i = iM ;
bool mij = GB_mcast (Mx, pM, msize) ;
if (mij)
{
// R(i,j) = Z(i,j)
GB_COPY_Z_BITMAP_OR_FULL ;
}
else
{
// R(i,j) = C(i,j)
GB_COPY_C ;
}
pC++ ;
pM++ ;
}
}
// if M(:,j) is exhausted ; continue scanning all of C(:,j)
#if defined ( GB_PHASE_1_OF_2 )
rjnz += (pC_end - pC) ;
#else
for ( ; pC < pC_end ; pC++)
{
// C(i,j) is present but M(i,j) is not
int64_t i = Ci [pC] ;
GB_COPY_C ;
}
#endif
// if C(:,j) is exhausted ; continue scanning all of M(:,j)
for ( ; pM < pM_end ; pM++)
{
// M(i,j) is present but C(i,j) is not
int64_t i = Mi [pM] ;
bool mij = GB_mcast (Mx, pM, msize) ;
if (mij)
{
// R(i,j) = Z(i,j)
GB_COPY_Z_BITMAP_OR_FULL ;
}
}
}
else if (mjnz == 0)
{
//--------------------------------------------------------------
// Z is sparse or hypersparse, M(:,j) is empty
//--------------------------------------------------------------
// ------------------------------------------
// C <!M> = Z R
// ------------------------------------------
// sparse sparse sparse sparse
// ------------------------------------------
// C <M> = Z R
// ------------------------------------------
// sparse sparse sparse sparse
// Z must be sparse or hypersparse
ASSERT (Z_is_sparse || Z_is_hyper) ;
if (!Mask_comp)
{
//----------------------------------------------------------
// Method02: M(:,j) is empty and not complemented
//----------------------------------------------------------
// R(:,j) = C(:,j), regardless of Z(:,j)
#if defined ( GB_PHASE_1_OF_2 )
rjnz = cjnz ;
#else
ASSERT (rjnz == cjnz) ;
memcpy (Ri +(pR), Ci +(pC), cjnz * sizeof (int64_t)) ;
#ifndef GB_ISO_MASKER
if (C_iso)
{
for (int64_t k = 0 ; k < cjnz ; k++)
{
memcpy (Rx +(pR+k)*rsize, Cx, rsize) ;
}
}
else
{
memcpy (Rx +(pR)*rsize, Cx +(pC)*rsize, cjnz*rsize) ;
}
#endif
#endif
}
else
{
//----------------------------------------------------------
// Method03: M(:,j) is empty and complemented
//----------------------------------------------------------
// R(:,j) = Z(:,j), regardless of C(:,j)
#if defined ( GB_PHASE_1_OF_2 )
rjnz = zjnz ;
#else
ASSERT (rjnz == zjnz) ;
memcpy (Ri +(pR), Zi +(pZ), zjnz * sizeof (int64_t)) ;
#ifndef GB_ISO_MASKER
if (Z_iso)
{
for (int64_t k = 0 ; k < zjnz ; k++)
{
memcpy (Rx +(pR+k)*rsize, Zx, rsize) ;
}
}
else
{
memcpy (Rx +(pR)*rsize, Zx +(pZ)*rsize, zjnz*rsize) ;
}
#endif
#endif
}
}
else if (cdense && zdense)
{
//--------------------------------------------------------------
// Method03: C(:,j) and Z(:,j) dense: thus R(:,j) dense
//--------------------------------------------------------------
// ------------------------------------------
// C <!M> = Z R
// ------------------------------------------
// sparse sparse sparse sparse
// sparse bitmap sparse sparse
// sparse full sparse sparse
// ------------------------------------------
// C <M> = Z R
// ------------------------------------------
// sparse sparse sparse sparse
// sparse bitmap sparse sparse
// sparse full sparse sparse
// Both C(:,j) and Z(:,j) are dense (that is, all entries
// present), but both C and Z are stored in a sparse or
// hypersparse sparsity structure. M has any sparsity.
ASSERT (Z_is_sparse || Z_is_hyper) ;
ASSERT (cjnz == zjnz) ;
ASSERT (iC_first == iZ_first) ;
ASSERT (iC_last == iZ_last ) ;
#if defined ( GB_PHASE_1_OF_2 )
rjnz = cjnz ;
#else
ASSERT (rjnz == cjnz) ;
for (int64_t p = 0 ; p < cjnz ; p++)
{
int64_t i = p + iC_first ;
Ri [pR + p] = i ;
int64_t iM = (pM < pM_end) ? GBI (Mi, pM, vlen) : INT64_MAX;
bool mij = false ;
if (i == iM)
{
mij = GBB (Mb, pM) && GB_mcast (Mx, pM, msize) ;
pM++ ;
}
if (Mask_comp) mij = !mij ;
#ifndef GB_ISO_MASKER
if (mij)
{
// R(i,j) = Z (i,j)
memcpy (Rx +(pR+p)*rsize, Zx +(Z_iso? 0:(pZ+p)*rsize),
rsize) ;
}
else
{
// R(i,j) = C (i,j)
memcpy (Rx +(pR+p)*rsize, Cx +(C_iso? 0:(pC+p)*rsize),
rsize) ;
}
#endif
}
#endif
}
else
{
//--------------------------------------------------------------
// Method04: 2-way merge of C(:,j) and Z(:,j)
//--------------------------------------------------------------
// Z is sparse or hypersparse; M has any sparsity structure
ASSERT (Z_is_sparse || Z_is_hyper) ;
//--------------------------------------------------------------
// Z is sparse or hypersparse, M has any sparsity
//--------------------------------------------------------------
// ------------------------------------------
// C <!M> = Z R
// ------------------------------------------
// sparse sparse sparse sparse
// sparse bitmap sparse sparse
// sparse full sparse sparse
// ------------------------------------------
// C <M> = Z R
// ------------------------------------------
// sparse sparse sparse sparse
// sparse bitmap sparse sparse
// sparse full sparse sparse
while (pC < pC_end && pZ < pZ_end)
{
//----------------------------------------------------------
// get the next i for R(:,j)
//----------------------------------------------------------
int64_t iC = Ci [pC] ;
int64_t iZ = Zi [pZ] ;
int64_t i = GB_IMIN (iC, iZ) ;
//----------------------------------------------------------
// get M(i,j)
//----------------------------------------------------------
bool mij = false ;
if (mdense)
{
//------------------------------------------------------
// Method04a: M(:,j) is dense
//------------------------------------------------------
// mask is dense, lookup M(i,j)
// iM_first == Mi [pM_first]
// iM_first + delta == Mi [pM_first + delta]
// let i = iM_first + delta
// let pM = pM_first + delta
// then delta = i - iM_first
pM = pM_first + (i - iM_first) ;
ASSERT (i == GBI (Mi, pM, vlen)) ;
mij = GBB (Mb, pM) && GB_mcast (Mx, pM, msize) ;
// increment pM for the wrapup phase below
pM++ ;
}
else
{
//------------------------------------------------------
// Method04b: M(:,j) is sparse
//------------------------------------------------------
// Use GB_SPLIT_BINARY_SEARCH so that pM can be used in
// the for loop with index pM in the wrapup phase.
ASSERT (M_is_sparse || M_is_hyper) ;
int64_t pright = pM_end - 1 ;
bool found ;
GB_SPLIT_BINARY_SEARCH (i, Mi, pM, pright, found) ;
if (found)
{
ASSERT (i == Mi [pM]) ;
mij = GB_mcast (Mx, pM, msize) ;
// increment pM for the wrapup phase below
pM++ ;
}
}
if (Mask_comp) mij = !mij ;
//----------------------------------------------------------
// R(i,j) = C(i,j) or Z(i,j)
//----------------------------------------------------------
if (iC < iZ)
{
// C(i,j) is present but Z(i,j) is not
if (!mij) GB_COPY_C ;
pC++ ;
}
else if (iC > iZ)
{
// Z(i,j) is present but C(i,j) is not
if (mij) GB_COPY_Z ;
pZ++ ;
}
else
{
// both C(i,j) and Z(i,j) are present
int64_t i = iC ;
if (mij)
{
GB_COPY_Z ;
}
else
{
GB_COPY_C ;
}
pC++ ;
pZ++ ;
}
}
//--------------------------------------------------------------
// Method04: wrapup: C or Z are exhausted, or initially empty
//--------------------------------------------------------------
cjnz = pC_end - pC ; // nnz (C(:,j)) remaining
zjnz = pZ_end - pZ ; // nnz (Z(:,j)) remaining
mjnz = pM_end - pM ; // nnz (M(:,j)) remaining
if (cjnz == 0)
{
//----------------------------------------------------------
// C(:,j) is empty
//----------------------------------------------------------
if (!Mask_comp)
{
//------------------------------------------------------
// mask is not complemented
//------------------------------------------------------
if (mdense)
{
//--------------------------------------------------
// Method04c: M(:,j) is dense
//--------------------------------------------------
for ( ; pZ < pZ_end ; pZ++)
{
int64_t i = Zi [pZ] ;
// mask is dense, lookup M(i,j)
pM = pM_first + (i - iM_first) ;
ASSERT (i == GBI (Mi, pM, vlen)) ;
bool mij = GBB (Mb, pM) &&
GB_mcast (Mx, pM, msize) ;
if (mij) GB_COPY_Z ;
}
}
else if (zjnz > 32 * mjnz)
{
//--------------------------------------------------
// Method04d: Z(:,j) is much denser than M(:,j)
//--------------------------------------------------
// This loop requires pM to start at the first
// entry in M(:,j) that has not yet been handled.
ASSERT (M_is_sparse || M_is_hyper) ;
for ( ; pM < pM_end ; pM++)
{
if (GB_mcast (Mx, pM, msize))
{
int64_t i = Mi [pM] ;
int64_t pright = pZ_end - 1 ;
bool found ;
GB_BINARY_SEARCH (i, Zi, pZ, pright, found);
if (found) GB_COPY_Z ;
}
}
}
else if (mjnz > 32 * zjnz)
{
//--------------------------------------------------
// Method04e: M(:,j) is much denser than Z(:,j)
//--------------------------------------------------
ASSERT (M_is_sparse || M_is_hyper) ;
for ( ; pZ < pZ_end ; pZ++)
{
int64_t i = Zi [pZ] ;
bool mij = false ;
int64_t pright = pM_end - 1 ;
bool found ;
GB_BINARY_SEARCH (i, Mi, pM, pright,found) ;
if (found) mij = GB_mcast (Mx, pM, msize) ;
if (mij) GB_COPY_Z ;
}
}
else
{
//--------------------------------------------------
// Method04f: M(:,j) and Z(:,j) about same # entries
//--------------------------------------------------
ASSERT (M_is_sparse || M_is_hyper) ;
while (pM < pM_end && pZ < pZ_end)
{
int64_t iM = Mi [pM] ;
int64_t i = Zi [pZ] ;
if (iM < i)
{
// M(i,j) exists but not Z(i,j)
pM++ ;
}
else if (i < iM)
{
// Z(i,j) exists but not M(i,j)
pZ++ ;
}
else
{
// both M(i,j) and Z(i,j) exist
if (GB_mcast (Mx, pM, msize)) GB_COPY_Z ;
pM++ ;
pZ++ ;
}
}
}
}
else
{
//------------------------------------------------------
// complemented mask, and C(:,j) empty
//------------------------------------------------------
if (mdense)
{
//--------------------------------------------------
// Method04g: M(:,j) is dense
//--------------------------------------------------
for ( ; pZ < pZ_end ; pZ++)
{
int64_t i = Zi [pZ] ;
// mask is dense, lookup M(i,j)
pM = pM_first + (i - iM_first) ;
ASSERT (i == GBI (Mi, pM, vlen)) ;
bool mij = GBB (Mb, pM) &&
GB_mcast (Mx, pM, msize) ;
if (!mij) GB_COPY_Z ; // mask is complemented
}
}
else
{
//--------------------------------------------------
// Method04h: M(:,j) is sparse
//--------------------------------------------------
ASSERT (M_is_sparse || M_is_hyper) ;
for ( ; pZ < pZ_end ; pZ++)
{
int64_t i = Zi [pZ] ;
bool mij = false ;
int64_t pright = pM_end - 1 ;
bool found ;
GB_BINARY_SEARCH (i, Mi, pM, pright, found) ;
if (found) mij = GB_mcast (Mx, pM, msize) ;
if (!mij) GB_COPY_Z ; // mask is complemented
}
}
}
}
else if (zjnz == 0)
{
//----------------------------------------------------------
// Z(:,j) is empty
//----------------------------------------------------------
if (Mask_comp)
{
//------------------------------------------------------
// mask is complemented
//------------------------------------------------------
if (mdense)
{
//--------------------------------------------------
// Method04i: M(:,j) is dense
//--------------------------------------------------
for ( ; pC < pC_end ; pC++)
{
int64_t i = Ci [pC] ;
// mask is dense, lookup M(i,j)
pM = pM_first + (i - iM_first) ;
ASSERT (i == GBI (Mi, pM, vlen)) ;
bool mij = GBB (Mb, pM) &&
GB_mcast (Mx, pM, msize) ;
if (mij) GB_COPY_C ;
}
}
else if (cjnz > 32 * mjnz)
{
//--------------------------------------------------
// Method04j: C(:,j) is much denser than M(:,j)
//--------------------------------------------------
ASSERT (M_is_sparse || M_is_hyper) ;
for ( ; pM < pM_end ; pM++)
{
if (GB_mcast (Mx, pM, msize))
{
int64_t i = Mi [pM] ;
int64_t pright = pC_end - 1 ;
bool found ;
GB_BINARY_SEARCH (i, Ci, pC, pright, found);
if (found) GB_COPY_C ;
}
}
}
else if (mjnz > 32 * cjnz)
{
//--------------------------------------------------
// Method04k: M(:,j) is much denser than C(:,j)
//--------------------------------------------------
ASSERT (M_is_sparse || M_is_hyper) ;
for ( ; pC < pC_end ; pC++)
{
int64_t i = Ci [pC] ;
bool mij = false ;
int64_t pright = pM_end - 1 ;
bool found ;
GB_BINARY_SEARCH (i, Mi, pM, pright, found);
if (found) mij = GB_mcast (Mx, pM, msize) ;
if (mij) GB_COPY_C ;
}
}
else
{
//--------------------------------------------------
// Method04l: M(:,j) and C(:,j) about same # entries
//--------------------------------------------------
ASSERT (M_is_sparse || M_is_hyper) ;
while (pM < pM_end && pC < pC_end)
{
int64_t iM = Mi [pM] ;
int64_t i = Ci [pC] ;
if (iM < i)
{
// M(i,j) exists but not C(i,j)
pM++ ;
}
else if (i < iM)
{
// C(i,j) exists but not M(i,j)
pC++ ;
}
else
{
// both M(i,j) and C(i,j) exist
if (GB_mcast (Mx, pM, msize)) GB_COPY_C ;
pM++ ;
pC++ ;
}
}
}
}
else
{
//------------------------------------------------------
// non-complemented mask, and Z(:,j) empty
//------------------------------------------------------
if (mdense)
{
//--------------------------------------------------
// Method04m: M(:,j) is dense
//--------------------------------------------------
for ( ; pC < pC_end ; pC++)
{
int64_t i = Ci [pC] ;
// mask is dense, lookup M(i,j)
pM = pM_first + (i - iM_first) ;
ASSERT (i == GBI (Mi, pM, vlen)) ;
bool mij = GBB (Mb, pM) &&
GB_mcast (Mx, pM, msize) ;
if (!mij) GB_COPY_C ;
}
}
else
{
//--------------------------------------------------
// Method04n: M(:,j) is sparse
//--------------------------------------------------
ASSERT (M_is_sparse || M_is_hyper) ;
for ( ; pC < pC_end ; pC++)
{
int64_t i = Ci [pC] ;
// M(i,j) false if not present
bool mij = false ;
int64_t pright = pM_end - 1 ;
bool found ;
GB_BINARY_SEARCH (i, Mi, pM, pright, found) ;
if (found) mij = GB_mcast (Mx, pM, msize) ;
if (!mij) GB_COPY_C ;
}
}
}
}
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pR == pR_end) ;
#endif
}
//------------------------------------------------------------------
// final count of nnz (R(:,j))
//------------------------------------------------------------------
#if defined ( GB_PHASE_1_OF_2 )
if (fine_task)
{
TaskList [taskid].pC = rjnz ;
}
else
{
Rp [k] = rjnz ;
}
#endif
}
}
}
|
floorplan.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 Application Kernel Matrix by Cray */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <sys/time.h>
#include <omp.h>
#include "../../common/BOTSCommonUtils.h"
#define ROWS 64
#define COLS 64
#define DMAX 64
#define max(a, b) ((a > b) ? a : b)
#define min(a, b) ((a < b) ? a : b)
int solution = -1, solution_seq = -1;
int cutoff_value = 5;
typedef int coor[2];
typedef char ibrd[ROWS][COLS];
typedef char (*pibrd)[COLS];
int manual_cutoff, if_cutoff, final_cutoff;
FILE * inputFile;
struct cell {
int n;
coor *alt;
int top;
int bot;
int lhs;
int rhs;
int left;
int above;
int next;
};
struct cell * gcells;
int MIN_AREA;
ibrd BEST_BOARD;
coor MIN_FOOTPRINT;
int N;
/* compute all possible locations for nw corner for cell */
static int starts(int id, int shape, coor *NWS, struct cell *cells) {
int i, n, top, bot, lhs, rhs;
int rows, cols, left, above;
/* size of cell */
rows = cells[id].alt[shape][0];
cols = cells[id].alt[shape][1];
/* the cells to the left and above */
left = cells[id].left;
above = cells[id].above;
/* if there is a vertical and horizontal dependence */
if ((left >= 0) && (above >= 0)) {
top = cells[above].bot + 1;
lhs = cells[left].rhs + 1;
bot = top + rows;
rhs = lhs + cols;
/* if footprint of cell touches the cells to the left and above */
if ((top <= cells[left].bot) && (bot >= cells[left].top) &&
(lhs <= cells[above].rhs) && (rhs >= cells[above].lhs))
{ n = 1; NWS[0][0] = top; NWS[0][1] = lhs; }
else { n = 0; }
/* if there is only a horizontal dependence */
} else if (left >= 0) {
/* highest initial row is top of cell to the left - rows */
top = max(cells[left].top - rows + 1, 0);
/* lowest initial row is bottom of cell to the left */
bot = min(cells[left].bot, ROWS);
n = bot - top + 1;
for (i = 0; i < n; i++) {
NWS[i][0] = i + top;
NWS[i][1] = cells[left].rhs + 1;
}
} else {
/* leftmost initial col is lhs of cell above - cols */
lhs = max(cells[above].lhs - cols + 1, 0);
/* rightmost initial col is rhs of cell above */
rhs = min(cells[above].rhs, COLS);
n = rhs - lhs + 1;
for (i = 0; i < n; i++) {
NWS[i][0] = cells[above].bot + 1;
NWS[i][1] = i + lhs;
} }
return (n);
}
/* lay the cell down on the board in the rectangular space defined
by the cells top, bottom, left, and right edges. If the cell can
not be layed down, return 0; else 1.
*/
static int lay_down(int id, ibrd board, struct cell *cells) {
int i, j, top, bot, lhs, rhs;
top = cells[id].top;
bot = cells[id].bot;
lhs = cells[id].lhs;
rhs = cells[id].rhs;
for (i = top; i <= bot; i++) {
for (j = lhs; j <= rhs; j++) {
if (board[i][j] == 0) board[i][j] = (char)id;
else return(0);
} }
return (1);
}
#define read_integer(file,var) \
if ( fscanf(file, "%d", &var) == EOF ) {\
fprintf(stdout," Bogus input file\n");\
exit(-1);\
}
static void read_inputs() {
int i, j, n;
read_integer(inputFile,n);
N = n;
gcells = (struct cell *) malloc((n + 1) * sizeof(struct cell));
gcells[0].n = 0;
gcells[0].alt = 0;
gcells[0].top = 0;
gcells[0].bot = 0;
gcells[0].lhs = -1;
gcells[0].rhs = -1;
gcells[0].left = 0;
gcells[0].above = 0;
gcells[0].next = 0;
for (i = 1; i < n + 1; i++) {
read_integer(inputFile, gcells[i].n);
gcells[i].alt = (coor *) malloc(gcells[i].n * sizeof(coor));
for (j = 0; j < gcells[i].n; j++) {
read_integer(inputFile, gcells[i].alt[j][0]);
read_integer(inputFile, gcells[i].alt[j][1]);
}
read_integer(inputFile, gcells[i].left);
read_integer(inputFile, gcells[i].above);
read_integer(inputFile, gcells[i].next);
}
if (!feof(inputFile)) {
read_integer(inputFile, solution_seq);
}
}
static void write_outputs() {
int i, j;
fprintf(stdout,"Minimum area = %d\n\n", MIN_AREA);
for (i = 0; i < MIN_FOOTPRINT[0]; i++) {
for (j = 0; j < MIN_FOOTPRINT[1]; j++) {
if (BEST_BOARD[i][j] == 0) {fprintf(stdout," ");}
else fprintf(stdout,"%c", 'A' + BEST_BOARD[i][j] - 1);
}
fprintf(stdout,"\n");
}
}
//manual
static int add_cell_ser (int id, coor FOOTPRINT, ibrd BOARD, struct cell *CELLS) {
int i, j, nn, nn2, area;
ibrd board;
coor footprint, NWS[DMAX];
nn2 = 0;
/* for each possible shape */
for (i = 0; i < CELLS[id].n; i++) {
/* compute all possible locations for nw corner */
nn = starts(id, i, NWS, CELLS);
nn2 += nn;
/* for all possible locations */
for (j = 0; j < nn; j++) {
struct cell *cells = CELLS;
/* extent of shape */
cells[id].top = NWS[j][0];
cells[id].bot = cells[id].top + cells[id].alt[i][0] - 1;
cells[id].lhs = NWS[j][1];
cells[id].rhs = cells[id].lhs + cells[id].alt[i][1] - 1;
memcpy(board, BOARD, sizeof(ibrd));
/* if the cell cannot be layed down, prune search */
if (! lay_down(id, board, cells)) {
//fprintf(stdout,"Chip %d, shape %d does not fit\n", id, i);
goto _end;
}
/* calculate new footprint of board and area of footprint */
footprint[0] = max(FOOTPRINT[0], cells[id].bot+1);
footprint[1] = max(FOOTPRINT[1], cells[id].rhs+1);
area = footprint[0] * footprint[1];
/* if last cell */
if (cells[id].next == 0) {
/* if area is minimum, update global values */
if (area < MIN_AREA) {
#pragma omp critical
if (area < MIN_AREA) {
MIN_AREA = area;
MIN_FOOTPRINT[0] = footprint[0];
MIN_FOOTPRINT[1] = footprint[1];
memcpy(BEST_BOARD, board, sizeof(ibrd));
//fprintf(stdout,"N %d\n", MIN_AREA);
}
}
/* if area is less than best area */
} else if (area < MIN_AREA) {
#pragma omp atomic
nn2 += add_cell_ser(cells[id].next, footprint, board,cells);
/* if area is greater than or equal to best area, prune search */
} else {
//fprintf(stdout,"T %d, %d\n", area, MIN_AREA);
}
_end:;
}
}
return nn2;
}
static int add_cell_if(int id, coor FOOTPRINT, ibrd BOARD, struct cell *CELLS,int level) {
int i, j, nn, area, nnc, nnl;
ibrd board;
coor footprint, NWS[DMAX];
nnc = nnl = 0;
/* for each possible shape */
for (i = 0; i < CELLS[id].n; i++) {
/* compute all possible locations for nw corner */
nn = starts(id, i, NWS, CELLS);
nnl += nn;
/* for all possible locations */
for (j = 0; j < nn; j++) {
#pragma omp task untied private(board, footprint,area) \
firstprivate(NWS,i,j,id,nn,level) \
shared(FOOTPRINT,BOARD,CELLS,MIN_AREA,MIN_FOOTPRINT,N,BEST_BOARD,nnc) \
if(level<cutoff_value)
{
struct cell cells[N+1];
memcpy(cells,CELLS,sizeof(struct cell)*(N+1));
/* extent of shape */
cells[id].top = NWS[j][0];
cells[id].bot = cells[id].top + cells[id].alt[i][0] - 1;
cells[id].lhs = NWS[j][1];
cells[id].rhs = cells[id].lhs + cells[id].alt[i][1] - 1;
memcpy(board, BOARD, sizeof(ibrd));
/* if the cell cannot be layed down, prune search */
if (! lay_down(id, board, cells)) {
//fprintf(stdout,"Chip %d, shape %d does not fit\n", id, i);
goto _end;
}
/* calculate new footprint of board and area of footprint */
footprint[0] = max(FOOTPRINT[0], cells[id].bot+1);
footprint[1] = max(FOOTPRINT[1], cells[id].rhs+1);
area = footprint[0] * footprint[1];
/* if last cell */
if (cells[id].next == 0) {
/* if area is minimum, update global values */
if (area < MIN_AREA) {
#pragma omp critical
if (area < MIN_AREA) {
MIN_AREA = area;
MIN_FOOTPRINT[0] = footprint[0];
MIN_FOOTPRINT[1] = footprint[1];
memcpy(BEST_BOARD, board, sizeof(ibrd));
//fprintf(stdout,"N %d\n", MIN_AREA);
}
}
/* if area is less than best area */
} else if (area < MIN_AREA) {
#pragma omp atomic
nnc += add_cell_if(cells[id].next, footprint, board,cells,level+1);
/* if area is greater than or equal to best area, prune search */
} else {
//fprintf(stdout,"T %d, %d\n", area, MIN_AREA);
}
_end:;
}
}
}
#pragma omp taskwait
return nnc+nnl;
}
static int add_cell_final(int id, coor FOOTPRINT, ibrd BOARD, struct cell *CELLS,int level) {
int i, j, nn, area, nnc, nnl;
coor footprint, NWS[DMAX];
nnc = nnl = 0;
/* for each possible shape */
for (i = 0; i < CELLS[id].n; i++) {
/* compute all possible locations for nw corner */
nn = starts(id, i, NWS, CELLS);
nnl += nn;
/* for all possible locations */
for (j = 0; j < nn; j++) {
#pragma omp task untied private(footprint,area) \
firstprivate(NWS,i,j,id,nn,level,cutoff_value) \
shared(FOOTPRINT,BOARD,CELLS,MIN_AREA,MIN_FOOTPRINT,N,BEST_BOARD,nnc) \
final(level >= cutoff_value) mergeable
{
ibrd board;
struct cell *cells;
if ( omp_in_final() && level > cutoff_value ) {
cells = CELLS;
} else {
cells = alloca(sizeof(struct cell)*(N+1));
memcpy(cells,CELLS,sizeof(struct cell)*(N+1));
}
/* extent of shape */
cells[id].top = NWS[j][0];
cells[id].bot = cells[id].top + cells[id].alt[i][0] - 1;
cells[id].lhs = NWS[j][1];
cells[id].rhs = cells[id].lhs + cells[id].alt[i][1] - 1;
memcpy(board, BOARD, sizeof(ibrd));
/* if the cell cannot be layed down, prune search */
if (! lay_down(id, board, cells)) {
//fprintf(stdout,"Chip %d, shape %d does not fit\n", id, i);
goto _end;
}
/* calculate new footprint of board and area of footprint */
footprint[0] = max(FOOTPRINT[0], cells[id].bot+1);
footprint[1] = max(FOOTPRINT[1], cells[id].rhs+1);
area = footprint[0] * footprint[1];
/* if last cell */
if (cells[id].next == 0) {
/* if area is minimum, update global values */
if (area < MIN_AREA) {
#pragma omp critical
if (area < MIN_AREA) {
MIN_AREA = area;
MIN_FOOTPRINT[0] = footprint[0];
MIN_FOOTPRINT[1] = footprint[1];
memcpy(BEST_BOARD, board, sizeof(ibrd));
//fprintf(stdout,"N %d\n", MIN_AREA);
}
}
/* if area is less than best area */
} else if (area < MIN_AREA) {
#pragma omp atomic
nnc += add_cell_final(cells[id].next, footprint, board,cells,level+1);
/* if area is greater than or equal to best area, prune search */
} else {
// fprintf(stdout,"T %d, %d\n", area, MIN_AREA);
}
_end:;
}
}
}
#pragma omp taskwait
return nnc+nnl;
}
static int add_cell_manual(int id, coor FOOTPRINT, ibrd BOARD, struct cell *CELLS,int level) {
int i, j, nn, area, nnc, nnl;
ibrd board;
coor footprint, NWS[DMAX];
nnc = nnl = 0;
/* for each possible shape */
for (i = 0; i < CELLS[id].n; i++) {
/* compute all possible locations for nw corner */
nn = starts(id, i, NWS, CELLS);
nnl += nn;
/* for all possible locations */
for (j = 0; j < nn; j++) {
#pragma omp task untied private(board, footprint,area) \
firstprivate(NWS,i,j,id,nn,level,cutoff_value) shared(nnc) \
shared(FOOTPRINT,BOARD,CELLS,MIN_AREA,MIN_FOOTPRINT,N,BEST_BOARD)
{
struct cell *cells;
cells = alloca(sizeof(struct cell)*(N+1));
memcpy(cells,CELLS,sizeof(struct cell)*(N+1));
/* extent of shape */
cells[id].top = NWS[j][0];
cells[id].bot = cells[id].top + cells[id].alt[i][0] - 1;
cells[id].lhs = NWS[j][1];
cells[id].rhs = cells[id].lhs + cells[id].alt[i][1] - 1;
memcpy(board, BOARD, sizeof(ibrd));
/* if the cell cannot be layed down, prune search */
if (! lay_down(id, board, cells)) {
//fprintf(stdout,"Chip %d, shape %d does not fit\n", id, i);
goto _end;
}
/* calculate new footprint of board and area of footprint */
footprint[0] = max(FOOTPRINT[0], cells[id].bot+1);
footprint[1] = max(FOOTPRINT[1], cells[id].rhs+1);
area = footprint[0] * footprint[1];
/* if last cell */
if (cells[id].next == 0) {
/* if area is minimum, update global values */
if (area < MIN_AREA) {
#pragma omp critical
if (area < MIN_AREA) {
MIN_AREA = area;
MIN_FOOTPRINT[0] = footprint[0];
MIN_FOOTPRINT[1] = footprint[1];
memcpy(BEST_BOARD, board, sizeof(ibrd));
//fprintf(stdout,"N %d\n", MIN_AREA);
}
}
/* if area is less than best area */
} else if (area < MIN_AREA) {
if(level+1 < cutoff_value ) {
#pragma omp atomic
nnc += add_cell_manual(cells[id].next, footprint, board,cells,level+1);
} else {
#pragma omp atomic
nnc += add_cell_ser(cells[id].next, footprint, board,cells);
}
/* if area is greater than or equal to best area, prune search */
} else {
//fprintf(stdout,"T %d, %d\n", area, MIN_AREA);
}
_end:;
}
}
}
#pragma omp taskwait
return nnc+nnl;
}
static int add_cell(int id, coor FOOTPRINT, ibrd BOARD, struct cell *CELLS) {
int i, j, nn, area, nnc,nnl;
ibrd board;
coor footprint, NWS[DMAX];
nnc = nnl = 0;
/* for each possible shape */
for (i = 0; i < CELLS[id].n; i++) {
/* compute all possible locations for nw corner */
nn = starts(id, i, NWS, CELLS);
nnl += nn;
/* for all possible locations */
for (j = 0; j < nn; j++) {
#pragma omp task untied private(board, footprint,area) \
firstprivate(NWS,i,j,id,nn) \
shared(FOOTPRINT,BOARD,CELLS,MIN_AREA,MIN_FOOTPRINT,N,BEST_BOARD,nnc)
{
struct cell cells[N+1];
memcpy(cells,CELLS,sizeof(struct cell)*(N+1));
/* extent of shape */
cells[id].top = NWS[j][0];
cells[id].bot = cells[id].top + cells[id].alt[i][0] - 1;
cells[id].lhs = NWS[j][1];
cells[id].rhs = cells[id].lhs + cells[id].alt[i][1] - 1;
memcpy(board, BOARD, sizeof(ibrd));
/* if the cell cannot be layed down, prune search */
if (! lay_down(id, board, cells)) {
//fprintf(stderr,"Chip %d, shape %d does not fit\n", id, i);
goto _end;
}
/* calculate new footprint of board and area of footprint */
footprint[0] = max(FOOTPRINT[0], cells[id].bot+1);
footprint[1] = max(FOOTPRINT[1], cells[id].rhs+1);
area = footprint[0] * footprint[1];
/* if last cell */
if (cells[id].next == 0) {
/* if area is minimum, update global values */
if (area < MIN_AREA) {
#pragma omp critical
if (area < MIN_AREA) {
MIN_AREA = area;
MIN_FOOTPRINT[0] = footprint[0];
MIN_FOOTPRINT[1] = footprint[1];
memcpy(BEST_BOARD, board, sizeof(ibrd));
//fprintf(stderr,"N %d\n", MIN_AREA);
}
}
/* if area is less than best area */
} else if (area < MIN_AREA) {
#pragma omp atomic
nnc += add_cell(cells[id].next, footprint, board,cells);
/* if area is greater than or equal to best area, prune search */
} else {
//fprintf(stderr,"T %d, %d\n", area, MIN_AREA);
}
_end:;
}
}
}
#pragma omp taskwait
return nnc+nnl;
}
static int add_cell_seq(int id, coor FOOTPRINT, ibrd BOARD, struct cell *CELLS) {
int i, j, nn, area, nnc,nnl;
ibrd board;
coor footprint, NWS[DMAX];
nnc = nnl = 0;
/* for each possible shape */
for (i = 0; i < CELLS[id].n; i++) {
/* compute all possible locations for nw corner */
nn = starts(id, i, NWS, CELLS);
nnl += nn;
/* for all possible locations */
for (j = 0; j < nn; j++) {
struct cell cells[N+1];
memcpy(cells,CELLS,sizeof(struct cell)*(N+1));
/* extent of shape */
cells[id].top = NWS[j][0];
cells[id].bot = cells[id].top + cells[id].alt[i][0] - 1;
cells[id].lhs = NWS[j][1];
cells[id].rhs = cells[id].lhs + cells[id].alt[i][1] - 1;
memcpy(board, BOARD, sizeof(ibrd));
/* if the cell cannot be layed down, prune search */
if (! lay_down(id, board, cells)) {
//fprintf(stderr,"Chip %d, shape %d does not fit\n", id, i);
goto _end;
}
/* calculate new footprint of board and area of footprint */
footprint[0] = max(FOOTPRINT[0], cells[id].bot+1);
footprint[1] = max(FOOTPRINT[1], cells[id].rhs+1);
area = footprint[0] * footprint[1];
/* if last cell */
if (cells[id].next == 0) {
/* if area is minimum, update global values */
if (area < MIN_AREA) {
if (area < MIN_AREA) {
MIN_AREA = area;
MIN_FOOTPRINT[0] = footprint[0];
MIN_FOOTPRINT[1] = footprint[1];
memcpy(BEST_BOARD, board, sizeof(ibrd));
//fprintf(stderr,"N %d\n", MIN_AREA);
}
}
/* if area is less than best area */
} else if (area < MIN_AREA) {
nnc += add_cell_seq(cells[id].next, footprint, board,cells);
/* if area is greater than or equal to best area, prune search */
} else {
//fprintf(stderr,"T %d, %d\n", area, MIN_AREA);
}
_end:;
}
}
return nnc+nnl;
}
ibrd board;
void floorplan_init (char *filename)
{
int i,j;
inputFile = fopen(filename, "r");
if(NULL == inputFile) {
fprintf(stdout,"Couldn't open %s file for reading\n", filename);
exit(1);
}
/* read input file and initialize global minimum area */
read_inputs();
MIN_AREA = ROWS * COLS;
/* initialize board is empty */
for (i = 0; i < ROWS; i++)
for (j = 0; j < COLS; j++) board[i][j] = 0;
}
void compute_floorplan_seq (void)
{
coor footprint;
/* footprint of initial board is zero */
footprint[0] = 0;
footprint[1] = 0;
fprintf(stdout,"Computing floorplan ");
add_cell_seq(1, footprint, board, gcells);
fprintf(stdout," completed!\n");
}
void compute_floorplan (void)
{
coor footprint;
/* footprint of initial board is zero */
footprint[0] = 0;
footprint[1] = 0;
fprintf(stdout,"Computing floorplan ");
if (manual_cutoff) {
#pragma omp parallel
#pragma omp single
add_cell_manual(1, footprint, board, gcells,0);
}
else if (if_cutoff) {
#pragma omp parallel
#pragma omp single
add_cell_if(1, footprint, board, gcells,0);
}
else if (final_cutoff) {
#pragma omp parallel
#pragma omp single
add_cell_final(1, footprint, board, gcells,0);
}
else {
#pragma omp parallel
#pragma omp single
add_cell(1, footprint, board, gcells);
}
fprintf(stdout," completed!\n");
}
void floorplan_end (void)
{
/* write results */
write_outputs();
}
int floorplan_verify (void)
{
if (solution != -1 && solution_seq != -1)
if (solution == solution_seq && MIN_AREA == solution) {
return 1;
}
else {
return 0;
}
else
return -1;
}
void print_usage() {
fprintf(stderr, "\n");
fprintf(stderr, "Usage: %s -[options]\n", "Floorplan");
fprintf(stderr, "\n");
fprintf(stderr, "Where options are:\n");
fprintf(stderr, " -f <file> : Cell description file (mandatory)\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 i;
char filename[100];
for (i=1; i<argc; i++) {
if (argv[i][0] == '-') {
switch (argv[i][1]) {
case 'f': /* read argument size 0 */
argv[i][1] = '*';
i++;
if (argc == i) { "Erro\n"; exit(100); }
strcpy(filename, 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;
}
}
}
floorplan_init(filename);
double t_start, t_end;
t_start = rtclock();
compute_floorplan();
t_end = rtclock();
floorplan_end();
fprintf(stdout, "Parallel Runtime: %0.6lfs\n", t_end - t_start);
floorplan_init(filename);
t_start = rtclock();
compute_floorplan_seq();
t_end = rtclock();
floorplan_end();
fprintf(stdout, "Sequential Runtime: %0.6lfs\n", t_end - t_start);
if (floorplan_verify() == 1) {
fprintf(stdout, "Result: Successful\n");
} else {
fprintf(stdout, "Result: Unsuccessful\n");
}
} |
xgboost_regrank_eval.h | #ifndef XGBOOST_REGRANK_EVAL_H
#define XGBOOST_REGRANK_EVAL_H
/*!
* \file xgboost_regrank_eval.h
* \brief evaluation metrics for regression and classification and rank
* \author Kailong Chen: chenkl198812@gmail.com, Tianqi Chen: tianqi.tchen@gmail.com
*/
#include <cmath>
#include <vector>
#include <algorithm>
#include "../utils/xgboost_utils.h"
#include "../utils/xgboost_omp.h"
#include "../utils/xgboost_random.h"
#include "xgboost_regrank_data.h"
#include "xgboost_regrank_utils.h"
namespace xgboost{
namespace regrank{
/*! \brief evaluator that evaluates the loss metrics */
struct IEvaluator{
/*!
* \brief evaluate a specific metric
* \param preds prediction
* \param info information, including label etc.
*/
virtual float Eval(const std::vector<float> &preds,
const DMatrix::Info &info) const = 0;
/*! \return name of metric */
virtual const char *Name(void) const = 0;
/*! \brief virtual destructor */
virtual ~IEvaluator(void){}
};
/*! \brief RMSE */
struct EvalRMSE : public IEvaluator{
virtual float Eval(const std::vector<float> &preds,
const DMatrix::Info &info) const {
utils::Assert( preds.size() == info.labels.size(), "label size predict size not match" );
const unsigned ndata = static_cast<unsigned>(preds.size());
float sum = 0.0, wsum = 0.0;
#pragma omp parallel for reduction(+:sum,wsum) schedule( static )
for (unsigned i = 0; i < ndata; ++i){
const float wt = info.GetWeight(i);
const float diff = info.labels[i] - preds[i];
sum += diff*diff * wt;
wsum += wt;
}
return sqrtf(sum / wsum);
}
virtual const char *Name(void) const{
return "rmse";
}
};
/*! \brief Error */
struct EvalLogLoss : public IEvaluator{
virtual float Eval(const std::vector<float> &preds,
const DMatrix::Info &info) const {
utils::Assert( preds.size() == info.labels.size(), "label size predict size not match" );
const unsigned ndata = static_cast<unsigned>(preds.size());
float sum = 0.0f, wsum = 0.0f;
#pragma omp parallel for reduction(+:sum,wsum) schedule( static )
for (unsigned i = 0; i < ndata; ++i){
const float y = info.labels[i];
const float py = preds[i];
const float wt = info.GetWeight(i);
sum -= wt * (y * std::log(py) + (1.0f - y)*std::log(1 - py));
wsum += wt;
}
return sum / wsum;
}
virtual const char *Name(void) const{
return "negllik";
}
};
/*! \brief Error */
struct EvalError : public IEvaluator{
virtual float Eval(const std::vector<float> &preds,
const DMatrix::Info &info) const {
const unsigned ndata = static_cast<unsigned>(preds.size());
float sum = 0.0f, wsum = 0.0f;
#pragma omp parallel for reduction(+:sum,wsum) schedule( static )
for (unsigned i = 0; i < ndata; ++i){
const float wt = info.GetWeight(i);
if (preds[i] > 0.5f){
if (info.labels[i] < 0.5f) sum += wt;
}
else{
if (info.labels[i] >= 0.5f) sum += wt;
}
wsum += wt;
}
return sum / wsum;
}
virtual const char *Name(void) const{
return "error";
}
};
/*! \brief AMS: also records best threshold */
struct EvalAMS : public IEvaluator{
public:
EvalAMS(const char *name){
name_ = name;
// note: ams@0 will automatically select which ratio to go
utils::Assert( sscanf(name, "ams@%f", &ratio_ ) == 1, "invalid ams format" );
}
virtual float Eval(const std::vector<float> &preds,
const DMatrix::Info &info) const {
const unsigned ndata = static_cast<unsigned>(preds.size());
utils::Assert( info.weights.size() == ndata, "we need weight to evaluate ams");
std::vector< std::pair<float, unsigned> > rec(ndata);
#pragma omp parallel for schedule( static )
for (unsigned i = 0; i < ndata; ++i){
rec[i] = std::make_pair( preds[i], i );
}
std::sort( rec.begin(), rec.end(), CmpFirst );
unsigned ntop = static_cast<unsigned>( ratio_ * ndata );
if( ntop == 0 ) ntop = ndata;
const double br = 10.0;
unsigned thresindex = 0;
double s_tp = 0.0, b_fp = 0.0, tams = 0.0;
for (unsigned i = 0; i < ndata-1 && i < ntop; ++i){
const unsigned ridx = rec[i].second;
const float wt = info.weights[ridx];
if( info.labels[ridx] > 0.5f ){
s_tp += wt;
}else{
b_fp += wt;
}
if( rec[i].first != rec[i+1].first ){
double ams = sqrtf( 2*((s_tp+b_fp+br) * log( 1.0 + s_tp/(b_fp+br) ) - s_tp) );
if( tams < ams ){
thresindex = i;
tams = ams;
}
}
}
if( ntop == ndata ){
fprintf( stderr, "\tams-ratio=%g", float(thresindex)/ndata );
return tams;
}else{
return sqrtf( 2*((s_tp+b_fp+br) * log( 1.0 + s_tp/(b_fp+br) ) - s_tp) );
}
}
virtual const char *Name(void) const{
return name_.c_str();
}
private:
std::string name_;
float ratio_;
};
/*! \brief Error for multi-class classification, need exact match */
struct EvalMatchError : public IEvaluator{
public:
virtual float Eval(const std::vector<float> &preds,
const DMatrix::Info &info) const {
const unsigned ndata = static_cast<unsigned>(preds.size());
float sum = 0.0f, wsum = 0.0f;
#pragma omp parallel for reduction(+:sum,wsum) schedule( static )
for (unsigned i = 0; i < ndata; ++i){
const float wt = info.GetWeight(i);
int label = static_cast<int>(info.labels[i]);
if (static_cast<int>(preds[i]) != label ) sum += wt;
wsum += wt;
}
return sum / wsum;
}
virtual const char *Name(void) const{
return "merror";
}
};
/*! \brief Area under curve, for both classification and rank */
struct EvalAuc : public IEvaluator{
virtual float Eval(const std::vector<float> &preds,
const DMatrix::Info &info) const {
utils::Assert( preds.size() == info.labels.size(), "label size predict size not match" );
std::vector<unsigned> tgptr(2, 0); tgptr[1] = preds.size();
const std::vector<unsigned> &gptr = info.group_ptr.size() == 0 ? tgptr : info.group_ptr;
utils::Assert(gptr.back() == preds.size(), "EvalAuc: group structure must match number of prediction");
const unsigned ngroup = static_cast<unsigned>(gptr.size() - 1);
double sum_auc = 0.0f;
#pragma omp parallel reduction(+:sum_auc)
{
// each thread takes a local rec
std::vector< std::pair<float, unsigned> > rec;
#pragma omp for schedule(static)
for (unsigned k = 0; k < ngroup; ++k){
rec.clear();
for (unsigned j = gptr[k]; j < gptr[k + 1]; ++j){
rec.push_back(std::make_pair(preds[j], j));
}
std::sort(rec.begin(), rec.end(), CmpFirst);
// calculate AUC
double sum_pospair = 0.0;
double sum_npos = 0.0, sum_nneg = 0.0, buf_pos = 0.0, buf_neg = 0.0;
for (size_t j = 0; j < rec.size(); ++j){
const float wt = info.GetWeight(rec[j].second);
const float ctr = info.labels[rec[j].second];
// keep bucketing predictions in same bucket
if (j != 0 && rec[j].first != rec[j - 1].first){
sum_pospair += buf_neg * (sum_npos + buf_pos *0.5);
sum_npos += buf_pos; sum_nneg += buf_neg;
buf_neg = buf_pos = 0.0f;
}
buf_pos += ctr * wt; buf_neg += (1.0f - ctr) * wt;
}
sum_pospair += buf_neg * (sum_npos + buf_pos *0.5);
sum_npos += buf_pos; sum_nneg += buf_neg;
//
utils::Assert(sum_npos > 0.0 && sum_nneg > 0.0, "the dataset only contains pos or neg samples");
// this is the AUC
sum_auc += sum_pospair / (sum_npos*sum_nneg);
}
}
// return average AUC over list
return static_cast<float>(sum_auc) / ngroup;
}
virtual const char *Name(void) const{
return "auc";
}
};
/*! \brief Evaluate rank list */
struct EvalRankList : public IEvaluator{
public:
virtual float Eval(const std::vector<float> &preds,
const DMatrix::Info &info) const {
utils::Assert( preds.size() == info.labels.size(), "label size predict size not match" );
const std::vector<unsigned> &gptr = info.group_ptr;
utils::Assert(gptr.size() != 0, "must specify group when constructing rank file");
utils::Assert( gptr.back() == preds.size(), "EvalRanklist: group structure must match number of prediction");
const unsigned ngroup = static_cast<unsigned>(gptr.size() - 1);
double sum_metric = 0.0f;
#pragma omp parallel reduction(+:sum_metric)
{
// each thread takes a local rec
std::vector< std::pair<float, unsigned> > rec;
#pragma omp for schedule(static)
for (unsigned k = 0; k < ngroup; ++k){
rec.clear();
for (unsigned j = gptr[k]; j < gptr[k + 1]; ++j){
rec.push_back(std::make_pair(preds[j], (int)info.labels[j]));
}
sum_metric += this->EvalMetric( rec );
}
}
return static_cast<float>(sum_metric) / ngroup;
}
virtual const char *Name(void) const{
return name_.c_str();
}
protected:
EvalRankList(const char *name){
name_ = name;
if( sscanf(name, "%*[^@]@%u", &topn_) != 1 ){
topn_ = UINT_MAX;
}
}
/*! \return evaluation metric, given the pair_sort record, (pred,label) */
virtual float EvalMetric( std::vector< std::pair<float, unsigned> > &pair_sort ) const = 0;
protected:
unsigned topn_;
std::string name_;
};
/*! \brief Precison at N, for both classification and rank */
struct EvalPrecision : public EvalRankList{
public:
EvalPrecision(const char *name):EvalRankList(name){}
protected:
virtual float EvalMetric( std::vector< std::pair<float, unsigned> > &rec ) const {
// calculate Preicsion
std::sort(rec.begin(), rec.end(), CmpFirst);
unsigned nhit = 0;
for (size_t j = 0; j < rec.size() && j < this->topn_; ++j){
nhit += (rec[j].second != 0 );
}
return static_cast<float>( nhit ) / topn_;
}
};
/*! \brief NDCG */
struct EvalNDCG : public EvalRankList{
public:
EvalNDCG(const char *name):EvalRankList(name){}
protected:
inline float CalcDCG( const std::vector< std::pair<float,unsigned> > &rec ) const {
double sumdcg = 0.0;
for( size_t i = 0; i < rec.size() && i < this->topn_; i ++ ){
const unsigned rel = rec[i].second;
if( rel != 0 ){
sumdcg += logf(2.0f) * ((1<<rel)-1) / logf( i + 2 );
}
}
return static_cast<float>(sumdcg);
}
virtual float EvalMetric( std::vector< std::pair<float, unsigned> > &rec ) const {
std::sort(rec.begin(), rec.end(), CmpSecond);
float idcg = this->CalcDCG(rec);
std::sort(rec.begin(), rec.end(), CmpFirst);
float dcg = this->CalcDCG(rec);
if( idcg == 0.0f ) return 0.0f;
else return dcg/idcg;
}
};
/*! \brief Precison at N, for both classification and rank */
struct EvalMAP : public EvalRankList{
public:
EvalMAP(const char *name):EvalRankList(name){}
protected:
virtual float EvalMetric( std::vector< std::pair<float, unsigned> > &rec ) const {
std::sort(rec.begin(), rec.end(), CmpFirst);
unsigned nhits = 0;
double sumap = 0.0;
for( size_t i = 0; i < rec.size(); ++i){
if( rec[i].second != 0 ){
nhits += 1;
if( i < this->topn_ ){
sumap += static_cast<float>(nhits) / (i+1);
}
}
}
if (nhits != 0) sumap /= nhits;
return static_cast<float>(sumap);
}
};
};
namespace regrank{
/*! \brief a set of evaluators */
struct EvalSet{
public:
inline void AddEval(const char *name){
for (size_t i = 0; i < evals_.size(); ++i){
if (!strcmp(name, evals_[i]->Name())) return;
}
if (!strcmp(name, "rmse")) evals_.push_back(new EvalRMSE());
if (!strcmp(name, "error")) evals_.push_back(new EvalError());
if (!strcmp(name, "merror")) evals_.push_back(new EvalMatchError());
if (!strcmp(name, "logloss")) evals_.push_back(new EvalLogLoss());
if (!strcmp(name, "auc")) evals_.push_back(new EvalAuc());
if (!strncmp(name, "ams@",4)) evals_.push_back(new EvalAMS(name));
if (!strncmp(name, "pre@", 4)) evals_.push_back(new EvalPrecision(name));
if (!strncmp(name, "map", 3)) evals_.push_back(new EvalMAP(name));
if (!strncmp(name, "ndcg", 3)) evals_.push_back(new EvalNDCG(name));
}
~EvalSet(){
for (size_t i = 0; i < evals_.size(); ++i){
delete evals_[i];
}
}
inline void Eval(FILE *fo, const char *evname,
const std::vector<float> &preds,
const DMatrix::Info &info) const{
for (size_t i = 0; i < evals_.size(); ++i){
float res = evals_[i]->Eval(preds, info);
fprintf(fo, "\t%s-%s:%f", evname, evals_[i]->Name(), res);
}
}
private:
std::vector<const IEvaluator*> evals_;
};
};
};
#endif
|
grid_basis.c | /*
* Author: Qiming Sun <osirpt.sun@gmail.com>
*/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "cint.h"
#include "config.h"
// 128s42p21d12f8g6h4i3j
#define NCTR_CART 128
// 72s24p14d10f8g6h5i4j
#define NCTR_SPH 72
#define NPRIMAX 64
#define BLKSIZE 96
#define EXPCUTOFF 50 // 1e-22
#define MIN(X,Y) ((X)<(Y)?(X):(Y))
#define MAX(X,Y) ((X)>(Y)?(X):(Y))
void VXCnr_ao_screen(signed char *non0table, double *coord,
int ngrids, int blksize,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int nblk = (ngrids+blksize-1) / blksize;
int ib, i, j;
int np, nc, atm_id, bas_id;
double rr, arr, maxc;
double logcoeff[NPRIMAX];
double dr[3];
double *p_exp, *pcoeff, *pcoord, *ratm;
memset(non0table, 0, sizeof(signed char) * nblk*nbas);
for (bas_id = 0; bas_id < nbas; bas_id++) {
np = bas[NPRIM_OF];
nc = bas[NCTR_OF ];
p_exp = env + bas[PTR_EXP];
pcoeff = env + bas[PTR_COEFF];
atm_id = bas[ATOM_OF];
ratm = env + atm[atm_id*ATM_SLOTS+PTR_COORD];
for (j = 0; j < np; j++) {
maxc = 0;
for (i = 0; i < nc; i++) {
maxc = MAX(maxc, fabs(pcoeff[i*np+j]));
}
logcoeff[j] = log(maxc);
}
pcoord = coord;
for (ib = 0; ib < nblk; ib++) {
for (i = 0; i < MIN(ngrids-ib*blksize, blksize); i++) {
dr[0] = pcoord[i*3+0] - ratm[0];
dr[1] = pcoord[i*3+1] - ratm[1];
dr[2] = pcoord[i*3+2] - ratm[2];
rr = dr[0]*dr[0] + dr[1]*dr[1] + dr[2]*dr[2];
for (j = 0; j < np; j++) {
arr = p_exp[j] * rr;
if (arr-logcoeff[j] < EXPCUTOFF) {
non0table[ib*nbas+bas_id] = 1;
goto next_blk;
}
}
}
next_blk:
pcoord += blksize*3;
}
bas += BAS_SLOTS;
}
}
void VXCgen_grid(double *out, double *coords, double *atm_coords,
double *radii_table, int natm, int ngrids)
{
int i, j, n;
double dx, dy, dz, dist;
double *grid_dist = malloc(sizeof(double) * natm*ngrids);
for (i = 0; i < natm; i++) {
for (n = 0; n < ngrids; n++) {
dx = coords[n*3+0] - atm_coords[i*3+0];
dy = coords[n*3+1] - atm_coords[i*3+1];
dz = coords[n*3+2] - atm_coords[i*3+2];
grid_dist[i*ngrids+n] = sqrt(dx*dx + dy*dy + dz*dz);
}
}
for (n = 0; n < natm*ngrids; n++) {
out[n] = 1;
}
#pragma omp parallel default(none) \
shared(out, grid_dist, atm_coords, radii_table, natm, ngrids) \
private(i, j, n, dx, dy, dz)
{
double *buf = malloc(sizeof(double) * natm*ngrids);
for (i = 0; i < natm*ngrids; i++) {
buf[i] = 1;
}
int ij;
double fac;
double g[ngrids];
#pragma omp for nowait schedule(static)
for (ij = 0; ij < natm*natm; ij++) {
i = ij / natm;
j = ij % natm;
if (i <= j) {
continue;
}
dx = atm_coords[i*3+0] - atm_coords[j*3+0];
dy = atm_coords[i*3+1] - atm_coords[j*3+1];
dz = atm_coords[i*3+2] - atm_coords[j*3+2];
fac = 1 / sqrt(dx*dx + dy*dy + dz*dz);
for (n = 0; n < ngrids; n++) {
g[n] = grid_dist[i*ngrids+n] - grid_dist[j*ngrids+n];
g[n] *= fac;
}
if (radii_table != NULL) {
fac = radii_table[i*natm+j];
for (n = 0; n < ngrids; n++) {
g[n] += fac * (1 - g[n]*g[n]);
}
}
for (n = 0; n < ngrids; n++) {
g[n] = (3 - g[n]*g[n]) * g[n] * .5;
}
for (n = 0; n < ngrids; n++) {
g[n] = (3 - g[n]*g[n]) * g[n] * .5;
}
for (n = 0; n < ngrids; n++) {
g[n] = (3 - g[n]*g[n]) * g[n] * .5;
g[n] *= .5;
}
for (n = 0; n < ngrids; n++) {
buf[i*ngrids+n] *= .5 - g[n];
buf[j*ngrids+n] *= .5 + g[n];
}
}
#pragma omp critical
for (i = 0; i < natm*ngrids; i++) {
out[i] *= buf[i];
}
free(buf);
}
free(grid_dist);
}
|
GB_unaryop__ainv_uint8_bool.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__ainv_uint8_bool
// op(A') function: GB_tran__ainv_uint8_bool
// C type: uint8_t
// A type: bool
// cast: uint8_t cij = (uint8_t) aij
// unaryop: cij = -aij
#define GB_ATYPE \
bool
#define GB_CTYPE \
uint8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
bool aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = -x ;
// 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_AINV || GxB_NO_UINT8 || GxB_NO_BOOL)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__ainv_uint8_bool
(
uint8_t *restrict Cx,
const bool *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__ainv_uint8_bool
(
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
|
Par-02-OnlyOmpParallel.c |
int main(int argc, char **argv) {
int a[4] = {1,2,3,4};
#pragma omp parallel
{
for (int i = 0; i < 4; ++i) {
a[i] = 3*a[i];
}
}
return 0;
}
|
own_filters.c | /*******************************************************************************
* Copyright (c) 2020, Intel Corporation
*
* 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 Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
*******************************************************************************/
////////////////////////////////////////////////////////////////////////////////////////
//
// scikit-ipp's own functions for filterring images, that uses
// Intel(R) Integrated Performance Primitives (Intel(R) IPP)
//
////////////////////////////////////////////////////////////////////////////////////////
#include "own_filters.h"
#define EXIT_FUNC exitLine: /* Label for Exit */
#define check_sts(st) if((st) != ippStsNoErr) goto exitLine
////////////////////////////////////////////////////////////////////////////////////////
//
// own_FilterBorder
//
// General border filter
//
// Note: own_FilterBorder functions on the backend for implementing
// gaussian filtering of image as is in scikit-image.
//
////////////////////////////////////////////////////////////////////////////////////////
IppStatus
own_FilterBorder(
IppDataType ippImageDataType,
IppDataType ippKernelDataType,
void * pSrc,
void * pDst,
void * pKernel,
int img_width,
int img_height,
int kernel_width,
int kernel_height,
int numChannels,
IppRoundMode roundMode,
IppiBorderType ippBorderType,
float ippBorderValue)
{
IppStatus status = ippStsNoErr;
int sizeof_src;
IppiSize roiSize = { img_width, img_height }; // Size of source and
// destination ROI in pixels
IppiSize kernelSize = { kernel_width, kernel_height };
Ipp8u * pBuffer = NULL; // Pointer to the work buffer
IppiFilterBorderSpec * pSpec = NULL; // context structure
int iTmpBufSize = 0; // Common work buffer size
int iSpecSize = 0; // Common work buffer size
int srcStep; // Steps, in bytes, through the
int dstStep;
status = get_sizeof(ippImageDataType, &sizeof_src);
check_sts(status);
srcStep = numChannels * img_width * sizeof_src;
dstStep = srcStep;
status = ippiFilterBorderGetSize(kernelSize, roiSize, ippImageDataType, ippKernelDataType,
numChannels, &iSpecSize, &iTmpBufSize);
check_sts(status);
pSpec = (IppiFilterBorderSpec *)ippsMalloc_8u(iSpecSize);
if (pSpec == NULL)
{
status = ippStsMemAllocErr;
check_sts(status);
};
pBuffer = ippsMalloc_8u(iTmpBufSize);
if (pBuffer == NULL)
{
status = ippStsMemAllocErr;
check_sts(status);
};
status = ippiFilterBorderInit(ippKernelDataType, pKernel, kernelSize, 4,
ippImageDataType, numChannels, roundMode, pSpec);
check_sts(status);
status = ippiFilterBorder(ippImageDataType, pSrc, srcStep, pDst, dstStep, roiSize,
numChannels, ippBorderType, ippBorderValue, pSpec, pBuffer);
check_sts(status);
EXIT_FUNC
ippsFree(pBuffer);
ippsFree(pSpec);
return status;
}
////////////////////////////////////////////////////////////////////////////////////////
//
// own_FilterGaussian
//
// Gaussian filter
//
// Note: own_FilterGaussian functions on the backend for implementing
// gaussian filtering of image as is in scikit-image.
//
////////////////////////////////////////////////////////////////////////////////////////
IppStatus
own_FilterGaussian(
IppDataType ippDataType,
void * pSrc,
void * pDst,
int img_width,
int img_height,
int numChannels,
float sigma_,
int kernelSize,
IppiBorderType ippBorderType,
float ippBorderValue)
{
IppStatus status = ippStsNoErr;
Ipp8u *pBuffer = NULL;
IppFilterGaussianSpec* pSpec = NULL; // context structure
int iTmpBufSize = 0, iSpecSize = 0; // Common work buffer size
int sizeof_src;
status = get_sizeof(ippDataType, &sizeof_src);
check_sts(status);
int srcStep = numChannels * img_width * sizeof_src; // Steps, in bytes, through
int dstStep = srcStep; // the source/destination
//images
IppiSize roiSize = { img_width, img_height }; // Size of source/destination
//ROI in pixels
Ipp32f sigma = (Ipp32f)sigma_;
// Pointer to the work buffer
status = ippiFilterGaussianGetBufferSize(roiSize, kernelSize, ippDataType,
numChannels, &iSpecSize, &iTmpBufSize);
check_sts(status);
pSpec = (IppFilterGaussianSpec *)ippsMalloc_8u(iSpecSize);
if (pSpec == NULL)
{
status = ippStsMemAllocErr;
check_sts(status);
}
pBuffer = (Ipp8u *)ippsMalloc_8u(iTmpBufSize);
if (pBuffer == NULL)
{
status = ippStsMemAllocErr;
check_sts(status);
}
status = ippiFilterGaussianInit(roiSize, kernelSize, sigma,
ippBorderType, ippDataType, numChannels, pSpec, pBuffer);
check_sts(status);
status = ippiFilterGaussianBorder(ippDataType, pSrc, srcStep, pDst, dstStep,
roiSize, numChannels, ippBorderValue, pSpec, pBuffer);
EXIT_FUNC
ippsFree(pBuffer);
ippsFree(pSpec);
return status;
}
////////////////////////////////////////////////////////////////////////////////////////
//
// own_FilterGaussian
//
// Median filter
//
// own_FilterGaussian uses functions on the backend for
// implementing median filtering of image as is in scikit-image.
//
////////////////////////////////////////////////////////////////////////////////////////
IppStatus
own_FilterMedian(
IppDataType ippDataType,
void * pSrc,
void * pDst,
int img_width,
int img_height,
int numChannels,
int mask_width,
int mask_height,
IppiBorderType ippBorderType,
float ippBorderValue)
{
IppStatus status = ippStsNoErr;
Ipp8u * pBuffer = NULL; // Pointer to the work buffer
int bufferSize;
int sizeof_src;
status = get_sizeof(ippDataType, &sizeof_src);
check_sts(status);
int srcStep = numChannels * img_width * sizeof_src; // Steps, in bytes, through
int dstStep = srcStep; // thesource/destination
//images
IppiSize dstRoiSize = { img_width, img_height }; // Size of source and
// destination ROI in pixels
IppiSize maskSize = { mask_width, mask_height }; // Size of source and
// destination ROI in pixels
status = ippiFilterMedianBorderGetBufferSize(dstRoiSize,
maskSize,
ippDataType,
numChannels,
&bufferSize);
check_sts(status);
pBuffer = ippsMalloc_8u(bufferSize);
if (pBuffer == NULL)
{
status = ippStsMemAllocErr;
check_sts(status);
}
status = ippiFilterMedianBorder(ippDataType, pSrc, srcStep, pDst, dstStep, dstRoiSize,
numChannels, maskSize, ippBorderType, ippBorderValue, pBuffer);
check_sts(status);
EXIT_FUNC
ippsFree(pBuffer);
return status;
}
////////////////////////////////////////////////////////////////////////////////////////
//
// own_FilterLaplace
//
// 0 -1 0
// Laplace (3x3) -1 4 -1
// 0 -1 0
// Note: own_FilterLaplace uses own_FilterBorder on the backend for implementing
// laplace filtering as is in scikit-image.
// This func doesn't use ippiFilterLaplaceBorder, because of different laplace
// kernel coeffs.
//
////////////////////////////////////////////////////////////////////////////////////////
IppStatus
own_FilterLaplace(
IppDataType ippDataType,
void * pSrc,
void * pDst,
int img_width,
int img_height,
int numChannels,
IppiBorderType ippBorderType,
float ippBorderValue)
{
IppStatus status = ippStsNoErr;
int kernel_width = 3;
int kernel_height = 3;
Ipp32f own_kernel_laplace[] = own_Laplace_KERNEL_3x3;
IppDataType ippKernelDataType = ipp32f;
IppRoundMode roundMode = ippRndNear;
status = own_FilterBorder(ippDataType,
ippKernelDataType,
pSrc,
pDst,
own_kernel_laplace,
img_width,
img_height,
kernel_width,
kernel_height,
numChannels,
roundMode,
ippBorderType,
ippBorderValue);
return status;
}
///////////////////////////////////////////////////////////////////////////////////////////
//
// own_FilterEdge
// 1 0 -1
// Prewitt_h (3x3) 1 0 -1
// 1 0 -1
//
// 1 1 1
// Prewitt_v (3x3) 0 0 0
// -1 -1 -1
//
// Sobel (3x3) TODO: description
//
// 1 0 -1
// Sobel_h (3x3) 2 0 -2
// 1 0 -1
//
// 1 2 1
// Sobel_v (3x3) 0 0 0
// -1 -2 -1
//
// Note: own_FilterEdge TODO: description
//
///////////////////////////////////////////////////////////////////////////////////////////
IppStatus
own_FilterEdge(
own_EdgeFilterKernel edgeKernel,
IppDataType ippSrcDataType,
IppDataType ippDstDataType,
void * pSrc,
void * pDst,
int img_width,
int img_height,
int numChannels)
{
IppStatus status = ippStsNoErr;
Ipp8u * pBuffer = NULL; // Pointer to the work buffer
int bufferSize;
IppiBorderType ippBorderType = ippBorderRepl;
float ippBorderValue = 0.0;
int srcStep; // Steps, in bytes, through the
int dstStep;
IppiSize roiSize = { img_width, img_height }; // Size of source and
// destination ROI in pixels
Ipp32f value;
IppiMaskSize maskSize = ippMskSize3x3;
IppNormType normType = ippNormL2; // As is in skimage.filters.prewitt
if (!( numChannels == 1 &&
ippSrcDataType == ipp32f &&
ippDstDataType == ipp32f ))
{
status = ippStsErr;
check_sts(status);
}
int sizeof_src;
status = get_sizeof(ippSrcDataType, &sizeof_src);
check_sts(status);
int sizeof_dst;
status = get_sizeof(ippDstDataType, &sizeof_dst);
check_sts(status);
// currently Intel(R) IPP supports only 1C images for filtering by prewitt kernels
srcStep = numChannels * img_width * sizeof_src;
dstStep = numChannels * img_width * sizeof_dst;
#ifdef USE_OPENMP
IppStatus * pStatus = NULL;
int max_num_threads;
int numThreads, slice, tail;
IppiSize dstTileSize, dstLastTileSize;
#ifdef MAX_NUM_THREADS
max_num_threads = MAX_NUM_THREADS;
#else
max_num_threads = omp_get_max_threads();
if(roiSize.height / max_num_threads < 2)
{
max_num_threads = 1;
}
#endif
#endif
switch (edgeKernel)
{
case own_filterSobelVert:
{
status = ippiFilterSobelVertBorderGetBufferSize(roiSize, maskSize, ippSrcDataType,
ippDstDataType, numChannels, &bufferSize);
break;
}
case own_filterSobelHoriz:
{
status = ippiFilterSobelHorizBorderGetBufferSize(roiSize, maskSize, ippSrcDataType,
ippDstDataType, numChannels, &bufferSize);
break;
}
case own_filterSobel:
{
status = ippiFilterSobelGetBufferSize(roiSize, maskSize, normType, ippSrcDataType,
ippDstDataType, numChannels, &bufferSize);
break;
}
case own_filterPrewittVert:
{
status = ippiFilterPrewittVertBorderGetBufferSize(roiSize, maskSize, ippSrcDataType,
ippDstDataType, numChannels, &bufferSize);
break;
}
case own_filterPrewittHoriz:
{
status = ippiFilterPrewittHorizBorderGetBufferSize(roiSize, maskSize, ippSrcDataType,
ippDstDataType, numChannels, &bufferSize);
break;
}
default:
{
status = ippStsErr;
}
}
check_sts(status);
pBuffer = ippsMalloc_8u(bufferSize);
if (pBuffer == NULL)
{
check_sts(status = ippStsMemAllocErr);
};
switch (edgeKernel)
{
case own_filterSobelVert:
{
status = ippiFilterSobelVertBorder(ippSrcDataType, ippDstDataType, pSrc, srcStep, pDst, dstStep,
roiSize, numChannels, maskSize, ippBorderType, ippBorderValue, pBuffer);
break;
}
case own_filterSobelHoriz:
{
status = ippiFilterSobelHorizBorder(ippSrcDataType, ippDstDataType, pSrc, srcStep, pDst, dstStep,
roiSize, numChannels, maskSize, ippBorderType, ippBorderValue, pBuffer);
break;
}
case own_filterSobel:
{
status = ippiFilterSobel(ippSrcDataType, ippDstDataType, pSrc, srcStep, pDst, dstStep, roiSize,
numChannels, maskSize, normType, ippBorderType, ippBorderValue, pBuffer);
break;
}
case own_filterPrewittVert:
{
status = ippiFilterPrewittVertBorder(ippSrcDataType, ippDstDataType, pSrc, srcStep, pDst, dstStep,
roiSize, numChannels, maskSize, ippBorderType, ippBorderValue, pBuffer);
break;
}
case own_filterPrewittHoriz:
{
status = ippiFilterPrewittHorizBorder(ippSrcDataType, ippDstDataType, pSrc, srcStep, pDst, dstStep,
roiSize, numChannels, maskSize, ippBorderType, ippBorderValue, pBuffer);
break;
}
default:
{
status = ippStsErr;
}
}
check_sts(status);
// suppose that processing only ipp32f
switch (edgeKernel)
{
case own_filterSobelVert:
{
// NOTE:
// scikit-image's Sobel filter is a wrapper on scipy.ndimage's
// `convolve` func. `convolve` uses `reflect` border mode.
// `reflect` border mode is equivalent of Intel IPP ippBorderMirrorR border type
// ippiFilterSobelVertBorder_<mode> doesn't supports this border type
value = (Ipp32f)(-4.0);
break;
}
case own_filterSobelHoriz:
{
// NOTE:
// scikit-image's Sobel filter is a wrapper on scipy.ndimage's
// `convolve` func. `convolve` uses `reflect` border mode.
// `reflect` border mode is equivalent of Intel IPP ippBorderMirrorR border type
// ippiFilterSobelHorizBorder_<mode> doesn't supports this border type
value = (Ipp32f)4.0;
break;
}
case own_filterSobel:
{
// NOTE:
// scikit-image's Sobel filter is a wrapper on scipy.ndimage's
// `convolve` func. `convolve` uses `reflect` border mode.
// `reflect` border mode is equivalent of Intel IPP ippBorderMirrorR border type
// ippiFilterSobelBorder_<mode> doesn't supports this border type
value = (Ipp32f)(4.0 * (Ipp32f)IPP_SQRT2);
break;
}
case own_filterPrewittVert:
{
// NOTE:
// scikit-image's prewitt filter is a wrapper on scipy.ndimage's
// `convolve` func. `convolve` uses `reflect` border mode.
// `reflect` border mode is equivalent of Intel IPP ippBorderMirrorR border type
// ippiFilterPrewittVertBorder_<mode> doesn't supports this border type
value = (Ipp32f)-3.0;
break;
}
case own_filterPrewittHoriz:
{
// NOTE:
// scikit-image's prewitt filter is a wrapper on scipy.ndimage's
// `convolve` func. `convolve` uses `reflect` border mode.
// `reflect` border mode is equivalent of Intel IPP ippBorderMirrorR border type
// ippiFilterPrewittHorizBorder_<mode> doesn't supports this border type
value = (Ipp32f)3.0;
break;
}
default:
{
status = ippStsErr;
}
}
#ifdef USE_OPENMP
if (max_num_threads != 1)
{
// Parallelized only by Y-direction here
#pragma omp parallel num_threads(max_num_threads)
{
#pragma omp master
{
numThreads = omp_get_num_threads();
pStatus = (IppStatus*)ippsMalloc_8u(sizeof(IppStatus) * numThreads);
if (pStatus == NULL)
{
status = ippStsMemAllocErr;
}
if(status == ippStsNoErr)
{
for (int i = 0; i < numThreads; ++i) pStatus[i] = ippStsNoErr;
slice = roiSize.height / numThreads;
tail = roiSize.height % numThreads;
dstTileSize.width = roiSize.width;
dstTileSize.height = slice;
dstLastTileSize.width = roiSize.width;
dstLastTileSize.height = slice + tail;
}
}
#pragma omp barrier
{
if (status == ippStsNoErr)
{
Ipp32u i;
void * pDstT = NULL;
i = omp_get_thread_num();
IppiPoint dstOffset = { 0, 0 };
IppiSize dstSizeT = dstTileSize;
dstSizeT.height = slice;
dstOffset.y += i * slice;
if (i == numThreads - 1) dstSizeT = dstLastTileSize;
pDstT = (void*)((Ipp8u*)pDst + dstOffset.y * (Ipp32s)dstStep);
pStatus[i] = ippiDivC_32f_C1IR(value, pDstT, dstStep, dstSizeT);
}
}
}
check_sts(status);
// Checking status for slices and tile
for (Ipp32u i = 0; i < numThreads; ++i)
{
status = pStatus[i];
check_sts(status);
}
}
else
{
#endif
status = ippiDivC_32f_C1IR(value, pDst, dstStep, roiSize);
check_sts(status);
#ifdef USE_OPENMP
}
#endif
EXIT_FUNC
#ifdef USE_OPENMP
ippsFree(pStatus);
#endif
ippsFree(pBuffer);
return status;
}
///////////////////////////////////////////////////////////////////////////////////////////
//
// own_FilterPrewitt
// Prewitt (3x3)
// computes the square root of the sum of squares of the horizontal
// and vertical Prewitt transforms.
//
// sqrt(A**2 + B**2)/sqrt(2)
//
// Note: currently supporeted only Ipp32f input/output.
//
///////////////////////////////////////////////////////////////////////////////////////////
IppStatus
own_FilterPrewitt(
own_EdgeFilterKernel edgeKernel,
IppDataType ippSrcDataType,
IppDataType ippDstDataType,
void * pSrc,
void * pDst,
int img_width,
int img_height,
int numChannels)
{
// computes the square root of the sum of squares of the horizontal
// and vertical Prewitt transforms.
// sqrt(A**2 + B**2)/sqrt(2)
IppStatus status = ippStsNoErr;
Ipp32f * pAsrcDst = NULL; // Pointer to sobel_h result
Ipp32f * pBsrcDst = NULL; // Pointer to sobel_v result
IppiSize roiSize = { img_width, img_height }; // Size of source-destination
// ROI in pixels
// currently supporeted only Ipp32f input/output
if (!(ippSrcDataType == ipp32f &&
ippSrcDataType == ipp32f &&
numChannels == 1 &&
edgeKernel == own_filterPrewitt))
{
status = ippStsErr;
check_sts(status);
}
int sizeofIppDataType = sizeof(Ipp32f);
pAsrcDst = (void *)ippsMalloc_8u((img_width * sizeofIppDataType * numChannels) * img_height);
if (pAsrcDst == NULL)
{
status = ippStsMemAllocErr;
check_sts(status);
};
status = own_FilterEdge(own_filterSobelHoriz, ippSrcDataType, ippDstDataType, pSrc, pAsrcDst,
img_width, img_height, numChannels);
check_sts(status);
pBsrcDst = (void *)ippsMalloc_8u((img_width * sizeofIppDataType * numChannels) * img_height);
if (pBsrcDst == NULL)
{
status = ippStsMemAllocErr;
check_sts(status);
};
status = own_FilterEdge(own_filterSobelVert, ippSrcDataType, ippDstDataType, pSrc, pBsrcDst,
img_width, img_height, numChannels);
check_sts(status);
int srcDstStep = sizeofIppDataType * img_width * numChannels;
status = ippiSqr_32f_C1IR(pAsrcDst, srcDstStep, roiSize);
check_sts(status);
status = ippiSqr_32f_C1IR(pBsrcDst, srcDstStep, roiSize);
check_sts(status);
status = ippiAdd_32f_C1R(pAsrcDst, srcDstStep, pBsrcDst, srcDstStep, pDst, srcDstStep, roiSize);
check_sts(status);
status = ippiSqrt_32f_C1IR(pDst, srcDstStep, roiSize);
check_sts(status);
Ipp32f sqrt2 = (Ipp32f)IPP_SQRT2;
status = ippiDivC_32f_C1IR(sqrt2, pDst, srcDstStep, roiSize);
check_sts(status);
EXIT_FUNC
ippsFree(pAsrcDst);
ippsFree(pBsrcDst);
return status;
}
IppStatus
own_mask_filter_result(
IppDataType ippDstDataType,
void * pDst,
int img_width,
int img_height,
int numChannels)
{
IppStatus status = ippStsNoErr;
// checking supported dtypes
if (!(ippDstDataType==ipp8u ||
ippDstDataType==ipp16u ||
ippDstDataType==ipp16s ||
ippDstDataType==ipp32s ||
ippDstDataType==ipp32f))
{
status = ippStsDataTypeErr;
check_sts(status);
}
IppStatus pStatus[4];
int sizeof_dst;
status = get_sizeof(ippDstDataType, &sizeof_dst);
check_sts(status);
int dstStep = numChannels * img_width * sizeof_dst;
double value = 0;
void * pTop = (void* )pDst;
void * pBottom = (void* )((Ipp8u* )pDst + dstStep * (img_height - 1));
void * pLeft = (void* )((Ipp8u* )pDst + dstStep);
void * pRight = (void* )((Ipp8u* )pLeft + numChannels * (img_width - 1) * sizeof_dst);
IppiSize horizRoiSize = {img_width, 1};
IppiSize verRoiSize = {1, (img_height - 1)};
#ifdef USE_OPENMP
int max_num_threads;
#ifdef MAX_NUM_THREADS
max_num_threads = MAX_NUM_THREADS;
#else
max_num_threads = omp_get_max_threads();
#endif
if (max_num_threads >= 4)
{
#pragma omp parallel sections
{
#pragma omp section
{
pStatus[0] = ippiSet_C1R(ippDstDataType, value, pTop, dstStep, horizRoiSize);
}
#pragma omp section
{
pStatus[1] = ippiSet_C1R(ippDstDataType, value, pBottom, dstStep, horizRoiSize);
}
#pragma omp section
{
pStatus[2] = ippiSet_C1R(ippDstDataType, value, pLeft, dstStep, verRoiSize);
}
#pragma omp section
{
pStatus[3] = ippiSet_C1R(ippDstDataType, value, pRight, dstStep, verRoiSize);
}
}
}
else
{
#endif
status = ippiSet_C1R(ippDstDataType, value, pTop, dstStep, horizRoiSize);
check_sts(status);
status = ippiSet_C1R(ippDstDataType, value, pBottom, dstStep, horizRoiSize);
check_sts(status);
status = ippiSet_C1R(ippDstDataType, value, pLeft, dstStep, verRoiSize);
check_sts(status);
status = ippiSet_C1R(ippDstDataType, value, pRight, dstStep, verRoiSize);
check_sts(status);
#ifdef USE_OPENMP
}
#endif
EXIT_FUNC
return status;
}
|
ThreadData.h | #ifndef THREAD_DATA_H
#define THREAD_DATA_H
#include <string>
#include <unordered_map>
#include <climits>
#include <regex>
#include "SecurityRules.h"
typedef std::unordered_map<std::string, uint64_t> StringOccurrence;
typedef std::unordered_map<int, uint64_t> IntOccurrence;
/**
* @brief minimal number of digits of a password, etc.
*/
struct minMax {
/**
* @brief Update minima and maxima of all general data from analysed passwords
* with the analysed passwords
* @param m: other minMaxValue to merge with
*/
void updateMinMax(const minMax &m);
bool operator==(const minMax& m) const;
uint mindigit = UINT_MAX;
uint maxdigit = 0;
uint minlower = UINT_MAX;
uint maxlower = 0;
uint minupper = UINT_MAX;
uint maxupper = 0;
uint minspecial = UINT_MAX;
uint maxspecial = 0;
};
struct ThreadData {
ThreadData operator+(const ThreadData& other) const;
void operator+=(const ThreadData& other);
bool operator==(const ThreadData& other) const;
int thread_id;
std::string filename;
uint64_t lineBegin = 0;
uint64_t lineEnd = 0;
uint64_t total_counter = 0;
uint64_t total_filter = 0;
IntOccurrence length;
StringOccurrence simplemasks;
StringOccurrence advancedmasks;
StringOccurrence charactersets;
minMax minMaxValue;
std::regex current_regex;
bool use_regex = false;
bool withcount = false;
uint limitSimplemask;
uint limitAdvancedmask;
SecurityRules sr;
};
#pragma omp declare reduction(dataSum: ThreadData : omp_out += omp_in ) initializer(omp_priv(omp_orig))
#endif // THREAD_DATA_H |
grid_basis.c | /* Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*
* Author: Qiming Sun <osirpt.sun@gmail.com>
*/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "cint.h"
#include "config.h"
#include "gto/grid_ao_drv.h"
#include "np_helper/np_helper.h"
#define MAX_THREADS 256
void VXCnr_ao_screen(unsigned char *non0table, double *coords, int ngrids,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE;
int i, j;
int np, nc, atm_id;
size_t bas_id, ib;
double rr, arr, maxc;
double logcoeff[NPRIMAX];
double dr[3];
double *p_exp, *pcoeff, *ratm;
for (bas_id = 0; bas_id < nbas; bas_id++) {
np = bas[NPRIM_OF];
nc = bas[NCTR_OF ];
p_exp = env + bas[PTR_EXP];
pcoeff = env + bas[PTR_COEFF];
atm_id = bas[ATOM_OF];
ratm = env + atm[atm_id*ATM_SLOTS+PTR_COORD];
for (j = 0; j < np; j++) {
maxc = 0;
for (i = 0; i < nc; i++) {
maxc = MAX(maxc, fabs(pcoeff[i*np+j]));
}
logcoeff[j] = log(maxc);
}
for (ib = 0; ib < nblk; ib++) {
for (i = ib*BLKSIZE; i < MIN(ngrids, (ib+1)*BLKSIZE); i++) {
dr[0] = coords[0*ngrids+i] - ratm[0];
dr[1] = coords[1*ngrids+i] - ratm[1];
dr[2] = coords[2*ngrids+i] - ratm[2];
rr = dr[0]*dr[0] + dr[1]*dr[1] + dr[2]*dr[2];
for (j = 0; j < np; j++) {
arr = p_exp[j] * rr;
if (arr-logcoeff[j] < EXPCUTOFF) {
non0table[ib*nbas+bas_id] = 1;
goto next_blk;
}
}
}
non0table[ib*nbas+bas_id] = 0;
next_blk:;
}
bas += BAS_SLOTS;
}
}
// 1k grids per block
#define GRIDS_BLOCK 512
void VXCgen_grid(double *out, double *coords, double *atm_coords,
double *radii_table, int natm, int ngrids)
{
const size_t Ngrids = ngrids;
int i, j;
double dx, dy, dz;
double *atom_dist = malloc(sizeof(double) * natm*natm);
for (i = 0; i < natm; i++) {
for (j = 0; j < i; j++) {
dx = atm_coords[i*3+0] - atm_coords[j*3+0];
dy = atm_coords[i*3+1] - atm_coords[j*3+1];
dz = atm_coords[i*3+2] - atm_coords[j*3+2];
atom_dist[i*natm+j] = 1 / sqrt(dx*dx + dy*dy + dz*dz);
}
}
#pragma omp parallel default(none) \
shared(out, coords, atm_coords, atom_dist, radii_table, natm) \
private(i, j, dx, dy, dz)
{
double *grid_dist = malloc(sizeof(double) * natm*GRIDS_BLOCK);
double *buf = malloc(sizeof(double) * natm*GRIDS_BLOCK);
double *g = malloc(sizeof(double) * GRIDS_BLOCK);
size_t ig0, n, ngs;
double fac;
#pragma omp for nowait schedule(static)
for (ig0 = 0; ig0 < Ngrids; ig0 += GRIDS_BLOCK) {
ngs = MIN(Ngrids-ig0, GRIDS_BLOCK);
for (i = 0; i < natm; i++) {
for (n = 0; n < ngs; n++) {
dx = coords[0*Ngrids+ig0+n] - atm_coords[i*3+0];
dy = coords[1*Ngrids+ig0+n] - atm_coords[i*3+1];
dz = coords[2*Ngrids+ig0+n] - atm_coords[i*3+2];
grid_dist[i*GRIDS_BLOCK+n] = sqrt(dx*dx + dy*dy + dz*dz);
buf[i*GRIDS_BLOCK+n] = 1;
} }
for (i = 0; i < natm; i++) {
for (j = 0; j < i; j++) {
fac = atom_dist[i*natm+j];
for (n = 0; n < ngs; n++) {
g[n] = (grid_dist[i*GRIDS_BLOCK+n] -
grid_dist[j*GRIDS_BLOCK+n]) * fac;
}
if (radii_table != NULL) {
fac = radii_table[i*natm+j];
for (n = 0; n < ngs; n++) {
g[n] += fac * (1 - g[n]*g[n]);
}
}
for (n = 0; n < ngs; n++) {
g[n] = (3 - g[n]*g[n]) * g[n] * .5;
}
for (n = 0; n < ngs; n++) {
g[n] = (3 - g[n]*g[n]) * g[n] * .5;
}
for (n = 0; n < ngs; n++) {
g[n] = (3 - g[n]*g[n]) * g[n] * .5;
g[n] *= .5;
}
for (n = 0; n < ngs; n++) {
buf[i*GRIDS_BLOCK+n] *= .5 - g[n];
buf[j*GRIDS_BLOCK+n] *= .5 + g[n];
}
} }
for (i = 0; i < natm; i++) {
for (n = 0; n < ngs; n++) {
out[i*Ngrids+ig0+n] = buf[i*GRIDS_BLOCK+n];
}
}
}
free(g);
free(buf);
free(grid_dist);
}
free(atom_dist);
}
|
softmax-inl.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2017 by Contributors
* \file softmax-inl.h
* \brief
*/
#ifndef MXNET_OPERATOR_NN_SOFTMAX_INL_H_
#define MXNET_OPERATOR_NN_SOFTMAX_INL_H_
#include <vector>
#include "../mxnet_op.h"
#include "../operator_common.h"
#include "../tensor/broadcast_reduce_op.h"
namespace mxnet {
namespace op {
namespace mxnet_op {
struct softmax_fwd {
template<typename DType>
MSHADOW_XINLINE static DType Map(DType a, DType b) {
return DType(expf(a)/b);
}
};
struct log_softmax_fwd {
template<typename DType>
MSHADOW_XINLINE static DType Map(DType a, DType b) {
return DType(a - logf(b));
}
};
template<typename OP, typename DType, int ndim>
inline void Softmax(Stream<cpu> *s, DType *in, DType *out,
Shape<ndim> shape, int axis, const DType temperature) {
index_t M = shape[axis];
index_t N = shape.Size()/M;
Shape<ndim> stride = calc_stride(shape);
Shape<ndim> sshape = shape;
sshape[axis] = 1;
index_t sa = stride[axis];
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(N); ++i) {
index_t base = unravel_dot(i, sshape, stride);
DType mmax = in[base];
for (index_t j = 1; j < M; ++j) {
if (mmax < in[base + j*sa]) mmax = in[base + j*sa];
}
DType sum = DType(0);
// By default temperature is 1.0, and only in reinforcement training
// users would set it to other values.
// Adding a branch here to save the CPU 'divide-by-1' computation at runtime
if (temperature == 1.0) {
for (index_t j = 0; j < M; ++j) {
sum += std::exp(in[base + j*sa] - mmax);
}
for (index_t j = 0; j < M; ++j) {
out[base + j*sa] = OP::Map(in[base + j*sa] - mmax, sum);
}
} else {
for (index_t j = 0; j < M; ++j) {
sum += std::exp((in[base + j*sa] - mmax)/temperature);
}
for (index_t j = 0; j < M; ++j) {
out[base + j*sa] = OP::Map((in[base + j*sa] - mmax)/temperature, sum);
}
}
}
}
struct softmax_bwd {
template<typename DType>
MSHADOW_XINLINE static DType Map(DType ograd, DType out, DType sum) {
return DType(out * (ograd - sum));
}
};
struct log_softmax_bwd {
template<typename DType>
MSHADOW_XINLINE static DType Map(DType ograd, DType out, DType sum) {
return DType(ograd - expf(out)*sum);
}
};
template<typename OP1, typename OP2, int Req, typename DType, int ndim>
inline void SoftmaxGrad(Stream<cpu> *s, DType *out, DType *ograd,
DType *igrad, Shape<ndim> shape, int axis,
const DType temperature) {
index_t M = shape[axis];
index_t N = shape.Size()/M;
Shape<ndim> stride = calc_stride(shape);
Shape<ndim> sshape = shape;
sshape[axis] = 1;
index_t sa = stride[axis];
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(N); ++i) {
index_t base = unravel_dot(i, sshape, stride);
DType sum = DType(0);
for (index_t j = 0; j < M; ++j) {
sum += OP1::Map(ograd[base + j*sa], out[base + j*sa]);
}
// By default temperature is 1.0, and only in reinforcement training
// users would set it to other values.
// Adding a branch here to save the CPU 'divide-by-1' computation at runtime
DType final_result;
if (temperature == 1.0) {
for (index_t j = 0; j < M; ++j) {
final_result = OP2::Map(ograd[base + j*sa], out[base + j*sa], sum);
KERNEL_ASSIGN(igrad[base + j*sa], Req, final_result);
}
} else {
for (index_t j = 0; j < M; ++j) {
final_result = OP2::Map(ograd[base + j*sa], out[base + j*sa], sum) / temperature;
KERNEL_ASSIGN(igrad[base + j*sa], Req, final_result);
}
}
}
}
#ifdef __CUDACC__
template<int x_bits, typename OP, typename DType, int ndim>
__global__ void softmax_compute_kernel(DType *in, DType *out, index_t M, int axis,
Shape<ndim> sshape, Shape<ndim> stride,
const double temperature) {
const unsigned x_size = 1 << x_bits;
__shared__ DType smem[x_size];
index_t sa = stride[axis];
index_t base = unravel_dot(blockIdx.x, sshape, stride);
index_t x = threadIdx.x;
red::maximum::SetInitValue(smem[x]);
for (index_t i = x; i < M; i += x_size) {
red::maximum::Reduce(smem[x], in[base + i*sa]);
}
__syncthreads();
cuda::Reduce1D<red::maximum, x_bits>(smem);
__syncthreads();
DType smax = smem[0];
__syncthreads();
red::sum::SetInitValue(smem[x]);
for (index_t i = x; i < M; i += x_size) {
red::sum::Reduce(smem[x], static_cast<DType>(expf((in[base + i*sa] - smax)/
static_cast<DType>(temperature))));
}
__syncthreads();
cuda::Reduce1D<red::sum, x_bits>(smem);
__syncthreads();
DType ssum = smem[0];
__syncthreads();
for (index_t i = x; i < M; i += x_size) {
out[base + i*sa] = OP::Map((in[base + i*sa] - smax)/static_cast<DType>(temperature), ssum);
}
}
template<typename OP, typename DType, int ndim>
inline void Softmax(Stream<gpu> *s, DType *in, DType *out,
Shape<ndim> shape, int axis, const double temperature) {
const int x_bits = 7;
const int x_size = 1 << x_bits;
index_t M = shape[axis];
index_t N = shape.Size()/M;
Shape<ndim> stride = calc_stride(shape);
Shape<ndim> sshape = shape;
sshape[axis] = 1;
softmax_compute_kernel<x_bits, OP, DType, ndim>
<<<N, x_size, 0, mshadow::Stream<gpu>::GetStream(s)>>>(
in, out, M, axis, sshape, stride, temperature);
MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_compute_kernel);
}
template<int x_bits, typename OP1, typename OP2, int Req, typename DType, int ndim>
__global__ void softmax_gradient_kernel(DType *out, DType *ograd, DType *igrad,
index_t M, int axis, Shape<ndim> sshape,
Shape<ndim> stride, const double temperature) {
const unsigned x_size = 1 << x_bits;
__shared__ DType smem[x_size];
index_t sa = stride[axis];
index_t base = unravel_dot(blockIdx.x, sshape, stride);
index_t x = threadIdx.x;
red::sum::SetInitValue(smem[x]);
for (index_t i = x; i < M; i += x_size) {
red::sum::Reduce(smem[x], OP1::Map(ograd[base + i*sa], out[base + i*sa]));
}
__syncthreads();
cuda::Reduce1D<red::sum, x_bits>(smem);
__syncthreads();
DType ssum = smem[0];
__syncthreads();
DType final_result;
for (index_t i = x; i < M; i += x_size) {
final_result =
OP2::Map(ograd[base + i*sa], out[base + i*sa], ssum) / static_cast<DType>(temperature);
KERNEL_ASSIGN(igrad[base + i*sa], Req, final_result);
}
}
template<typename OP1, typename OP2, int Req, typename DType, int ndim>
inline void SoftmaxGrad(Stream<gpu> *s, DType *out, DType *ograd,
DType *igrad, Shape<ndim> shape, int axis,
const double temperature) {
const int x_bits = 7;
const int x_size = 1 << x_bits;
index_t M = shape[axis];
index_t N = shape.Size()/M;
Shape<ndim> stride = calc_stride(shape);
Shape<ndim> sshape = shape;
sshape[axis] = 1;
softmax_gradient_kernel<x_bits, OP1, OP2, Req, DType, ndim>
<<<N, x_size, 0, mshadow::Stream<gpu>::GetStream(s)>>>(
out, ograd, igrad, M, axis, sshape, stride, temperature);
MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_gradient_kernel);
}
#endif
} // namespace mxnet_op
struct SoftmaxParam : public dmlc::Parameter<SoftmaxParam> {
int axis;
dmlc::optional<double> temperature;
DMLC_DECLARE_PARAMETER(SoftmaxParam) {
DMLC_DECLARE_FIELD(axis).set_default(-1)
.describe("The axis along which to compute softmax.");
DMLC_DECLARE_FIELD(temperature).set_default(dmlc::optional<double>())
.describe("Temperature parameter in softmax");
}
};
template<typename xpu, typename OP>
void SoftmaxCompute(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mxnet_op;
if (req[0] == kNullOp) return;
CHECK_NE(req[0], kAddTo);
const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed);
int axis = CheckAxis(param.axis, inputs[0].ndim());
const double temperature = param.temperature.has_value() ?
param.temperature.value() : 1.0;
TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true);
MSHADOW_REAL_TYPE_SWITCH(inputs[0].type_flag_, DType, {
if (shape.ndim() == 2) {
Softmax<OP>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(),
outputs[0].dptr<DType>(), shape.get<2>(), axis,
static_cast<DType>(temperature));
} else {
Softmax<OP>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(),
outputs[0].dptr<DType>(), shape.get<3>(), axis,
static_cast<DType>(temperature));
}
});
}
template<typename xpu, typename OP1, typename OP2>
void SoftmaxGradCompute(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mxnet_op;
if (req[0] == kNullOp) return;
const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed);
int axis = CheckAxis(param.axis, inputs[0].ndim());
const double temperature = param.temperature.has_value() ?
param.temperature.value() : 1.0;
TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true);
MSHADOW_REAL_TYPE_SWITCH(inputs[0].type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
if (shape.ndim() == 2) {
SoftmaxGrad<OP1, OP2, Req>(ctx.get_stream<xpu>(), inputs[1].dptr<DType>(),
inputs[0].dptr<DType>(), outputs[0].dptr<DType>(),
shape.get<2>(), axis, static_cast<DType>(temperature));
} else {
SoftmaxGrad<OP1, OP2, Req>(ctx.get_stream<xpu>(), inputs[1].dptr<DType>(),
inputs[0].dptr<DType>(), outputs[0].dptr<DType>(),
shape.get<3>(), axis, static_cast<DType>(temperature));
}
});
});
}
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_NN_SOFTMAX_INL_H_
|
unparser.h | /* Copyright (c) 2013, 2014 Michael Foerster,
<Michael.Foerster@com-science.de>
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 UNPARSER_H
#define UNPARSER_H
#define SPLC_GLOBAL_DEBUG_SWITCH 0
#define UNPARSE_FIRST_AS_BLOCK \
MAKE_INDENT; unparser->ofs << "{\n"; \
INC_INDENT; \
UNPARSE_FIRST; \
DEC_INDENT; \
MAKE_INDENT; unparser->ofs << "}\n"
#define UNPARSE_FIRST_AS_BLOCK_TEST(VT_TYPE) \
MAKE_INDENT; unparser->ofs << "{\n"; \
INC_INDENT; \
UNPARSE_FIRST_TEST(VT_TYPE); \
DEC_INDENT; \
MAKE_INDENT; unparser->ofs << "}"
#define FIRST (*(v->get_children().begin()))
#define SECOND (*(++v->get_children().begin()))
#define THIRD (*(++++v->get_children().begin()))
#define LAST (*(--v->get_children().end()))
#define SECOND_LAST (*(----v->get_children().end()))
#define FIRSTOF(v) (*((v)->get_children().begin()))
#define SECONDOF(v) (*(++(v)->get_children().begin()))
#define THIRDOF(v) (*(++++(v)->get_children().begin()))
#define LASTOF(v) (*(--(v)->get_children().end()))
#define SECOND_LASTOF(v) (*(----(v)->get_children().end()))
#define MPFR_FLOAT_PRECISION 200
#define MAKE_INDENT for(int _i_=0;_i_<unparser->indent;_i_++) unparser->ofs << " "
#define INC_INDENT unparser->indent+=TAB_WIDTH;
#define DEC_INDENT unparser->indent-=TAB_WIDTH;
#define UNPARSE_ALL for(list<ast_vertex*>::const_iterator it=unparser->v->get_children().begin();it!=unparser->v->get_children().end();it++) { assert(*it); unparser->v = *it; (*it)->unparse(argv); unparser->v=v; }
#define UNPARSE_FIRST assert(unparser->v->get_children().size()>0); assert(FIRST); unparser->v = FIRST; FIRST->unparse(argv); unparser->v=v
#define UNPARSE_SECOND assert(unparser->v->get_children().size()>1); assert(SECOND); unparser->v = SECOND; SECOND->unparse(argv); unparser->v=v
#define UNPARSE_THIRD assert(unparser->v->get_children().size()>2); assert(THIRD); unparser->v = THIRD; THIRD->unparse(argv); unparser->v=v
#define UNPARSE_FIRST_TEST(VT_TYPE) if(FIRST->get_type()==VT_TYPE) { unparser->v = FIRST; FIRST->unparse(argv); unparser->v=v; }
#define UNPARSE_SECOND_TEST(VT_TYPE) if(SECOND->get_type()==VT_TYPE) { unparser->v = SECOND; SECOND->unparse(argv); unparser->v=v; }
#define UNPARSE_THIRD_TEST(VT_TYPE) if(THIRD->get_type()==VT_TYPE) { unparser->v = THIRD; THIRD->unparse(argv); unparser->v=v; }
#define DEFINE_UNPARSER Unparser* unparser=(Unparser*)argv; ast_vertex* v =unparser->v; assert(v)
#define TL_TRANSF "\\tl"
#define ADJ_TRANSF_F "\\adjf"
#define ADJ_TRANSF_R "\\adjr"
#define REDIRECT_UNPARSING(ORIGINAL,TL,PASSIVE,AUGMENTED_FORWARD,REVERSE) \
switch(unparser->current_mode) { \
case unparse_original: \
ORIGINAL(argv); \
break; \
case unparse_tangent_linear: \
TL(argv); \
break; \
case unparse_passive: \
PASSIVE(argv); \
break; \
case unparse_augmented_forward: \
AUGMENTED_FORWARD(argv); \
break; \
case unparse_reverse: \
REVERSE(argv); \
break; \
default: cerr << "error: The type " << (unparser->current_mode) << " is unknown." << endl;assert(0); \
}
#define OMP_GET_WTIME_START \
if( option_papi || option_time ) { \
MAKE_INDENT; unparser->ofs << "start=omp_get_wtime();\n"; \
}
#define OMP_GET_WTIME_END \
if( option_papi || option_time ) { \
MAKE_INDENT; unparser->ofs << "end=omp_get_wtime();\n"; \
MAKE_INDENT; unparser->ofs << "elapsed_time=end-start;\n"; \
MAKE_INDENT; unparser->ofs << "fprintf(stderr, \"parallel region took : %18.2F sec\\n\", elapsed_time);\n"; \
}
#define PAPI_SHARED_VARIABLES \
if(option_papi) { \
MAKE_INDENT; unparser->ofs << "int p = omp_get_max_threads() ;\n"; \
MAKE_INDENT; unparser->ofs << "const int number_of_events = 2;\n"; \
MAKE_INDENT; unparser->ofs << "int* EventSets = new int [p];\n"; \
MAKE_INDENT; unparser->ofs << "for(i=0;i<p;i++) {EventSets[i] = PAPI_NULL;\n"; \
MAKE_INDENT; unparser->ofs << "long long **values = new long long* [p];\n"; \
MAKE_INDENT; unparser->ofs << "long long fp_ops=0;\n"; \
MAKE_INDENT; unparser->ofs << "long long mflops=0;\n"; \
MAKE_INDENT; unparser->ofs << "long long max_cyc=0;\n"; \
MAKE_INDENT; unparser->ofs << "long long elapsed_cyc;\n"; \
MAKE_INDENT; unparser->ofs << "double elapsed_time=0;\n"; \
MAKE_INDENT; unparser->ofs << "int mhz=-1;\n"; \
MAKE_INDENT; unparser->ofs << "\n"; \
MAKE_INDENT; unparser->ofs << "int global_retval = PAPI_library_init( PAPI_VER_CURRENT ); assert(global_retval == PAPI_VER_CURRENT );\n"; \
MAKE_INDENT; unparser->ofs << "assert( omp_get_nested()==0 ); // In the non-nested case we can use omp_get_thread_num to identify threads uniquely.\n"; \
MAKE_INDENT; unparser->ofs << "global_retval = PAPI_thread_init( ( unsigned long (*)( void ) ) ( omp_get_thread_num ) ); assert(global_retval==PAPI_OK);\n"; \
}
#define PAPI_HEADER \
if(option_papi) { \
MAKE_INDENT; unparser->ofs << "int PAPI_tid=omp_get_thread_num();\n"; \
MAKE_INDENT; unparser->ofs << "int PAPI_retval;\n"; \
MAKE_INDENT; unparser->ofs << "\n"; \
MAKE_INDENT; unparser->ofs << "PAPI_retval = PAPI_create_eventset( &EventSets[PAPI_tid] ); assert(PAPI_retval==PAPI_OK);\n"; \
MAKE_INDENT; unparser->ofs << "PAPI_values[PAPI_tid] = new long long [number_of_events]; assert(PAPI_values[PAPI_tid]);\n"; \
MAKE_INDENT; unparser->ofs << "assert( PAPI_query_event( PAPI_FP_OPS ) == PAPI_OK );\n"; \
MAKE_INDENT; unparser->ofs << "PAPI_retval = PAPI_add_named_event( EventSets[PAPI_tid], (char*)\"PAPI_FP_OPS\" ); assert(PAPI_retval==PAPI_OK);\n"; \
MAKE_INDENT; unparser->ofs << "assert( PAPI_query_event( PAPI_TOT_CYC ) == PAPI_OK );\n"; \
MAKE_INDENT; unparser->ofs << "PAPI_retval = PAPI_add_named_event( EventSets[PAPI_tid], (char*)\"PAPI_TOT_CYC\" ); assert(PAPI_retval==PAPI_OK);\n"; \
MAKE_INDENT; unparser->ofs << "\n"; \
MAKE_INDENT; unparser->ofs << "#pragma omp master\n"; \
MAKE_INDENT; unparser->ofs << "{\n"; \
INC_INDENT; \
MAKE_INDENT; unparser->ofs << "PAPI_retval = PAPI_start( EventSets[PAPI_tid] ); assert(PAPI_retval==PAPI_OK);\n"; \
MAKE_INDENT; unparser->ofs << "PAPI_elapsed_cyc = PAPI_get_real_cyc();\n"; \
MAKE_INDENT; unparser->ofs << "usleep(1e6);\n"; \
MAKE_INDENT; unparser->ofs << "PAPI_elapsed_cyc = PAPI_get_real_cyc() - PAPI_elapsed_cyc;\n"; \
MAKE_INDENT; unparser->ofs << "PAPI_mhz = PAPI_elapsed_cyc / 1e6; assert(PAPI_mhz>1000); \n"; \
MAKE_INDENT; unparser->ofs << "PAPI_retval = PAPI_stop( EventSets[PAPI_tid], PAPI_values[PAPI_tid] ); assert(PAPI_retval==PAPI_OK);\n"; \
MAKE_INDENT; unparser->ofs << "PAPI_retval = PAPI_reset( EventSets[PAPI_tid] ); assert(PAPI_retval==PAPI_OK);\n"; \
DEC_INDENT; \
MAKE_INDENT; unparser->ofs << "}\n"; \
MAKE_INDENT; unparser->ofs << "\n"; \
MAKE_INDENT; unparser->ofs << "PAPI_retval = PAPI_start( EventSets[PAPI_tid] ); assert(PAPI_retval==PAPI_OK);\n"; \
}
#define PAPI_FOOTER \
if(option_papi) { \
MAKE_INDENT; unparser->ofs << "\n"; \
MAKE_INDENT; unparser->ofs << "PAPI_retval = PAPI_stop( EventSets[PAPI_tid], PAPI_values[PAPI_tid] ); assert(PAPI_retval==PAPI_OK);\n"; \
}
#define PAPI_PRINT_MFLOPS \
if(option_papi) { \
MAKE_INDENT; unparser->ofs << "fp_ops=0;max_cyc=0;\n"; \
/*MAKE_INDENT; unparser->ofs << "cerr << setprecision(2);\n"; */\
MAKE_INDENT; unparser->ofs << "cerr << \"MHz : \" << setw(17) << PAPI_mhz << endl;\n"; \
MAKE_INDENT; unparser->ofs << "for(i=0;i<p;i++) { \n"; \
MAKE_INDENT; unparser->ofs << "\tfp_ops+=PAPI_values[i][0];\n"; \
MAKE_INDENT; unparser->ofs << "\tif(PAPI_values[i][1]>max_cyc) max_cyc=PAPI_values[i][1];\n"; \
MAKE_INDENT; unparser->ofs << "\tcerr << \"Thread \" << setw(3) << i << \": FP_OPS : \" << setw(17) << PAPI_values[i][0] << \" (\"<< setw(10) <<PAPI_values[i][0]/1e6<<\"*10^6) TOT_CYC : \" << setw(17) << PAPI_values[i][1] << \" (\"<< setw(10) <<PAPI_values[i][1]/1e6<<\"*10^6)\" << endl;\n"; \
MAKE_INDENT; unparser->ofs << "}\n"; \
MAKE_INDENT; unparser->ofs << "cerr << \"overall FP_OPS : \" << setw(17) << fp_ops << \" (\"<< setw(10) <<fp_ops/1e9<<\"*10^9) max of TOT_CYC : \" << setw(17) << max_cyc << \" (\"<< setw(10) <<max_cyc/1e9<<\"*10^9)\" << endl;\n"; \
MAKE_INDENT; unparser->ofs << "if(PAPI_mhz>0 && max_cyc/PAPI_mhz>0) mflops=fp_ops/(max_cyc/PAPI_mhz); else mflops=0;\n"; \
MAKE_INDENT; unparser->ofs << "cerr << \"MFLOPS : \" << setw(17) << mflops << endl;\n"; \
MAKE_INDENT; unparser->ofs << "fprintf(stderr, \"\\n\\n\");\n"; \
MAKE_INDENT; unparser->ofs << "for(i=0;i<p;i++) { global_PAPI_retval=PAPI_cleanup_eventset(EventSets[i]); assert(global_PAPI_retval==PAPI_OK); PAPI_destroy_eventset(&EventSets[i]); assert(global_PAPI_retval==PAPI_OK); }\n"; \
}
enum unparse_modes {
unparse_none=10000,
unparse_original,
unparse_tangent_linear,
unparse_adjoint,
unparse_passive,
unparse_augmented_forward,
unparse_reverse
};
extern bool option_long_double;
extern bool option_mpfr;
extern bool option_suppress_global_region;
extern bool option_papi;
extern bool option_time;
extern bool option_prg_analysis;
extern bool option_mem_statistic;
extern bool option_suppress_atomic;
class ast_vertex;
class Unparser {
public:
unparse_modes current_mode;
ast_vertex* v;
ostringstream oss;
ofstream ofs;
list<string> code;
int indent;
bool suppress_linefeed;
std::string float_type;
Unparser() : current_mode(unparse_none), indent(0), suppress_linefeed(false), float_type("double")
{
if(option_long_double)
float_type="long double";
else if(option_mpfr)
float_type="mpfr_t";
}
};
extern std::string src_filename;
// UNPARSER
extern enum unparse_modes current_mode;
void unparser_spl_code(void* argv);
void unparser_global_declarations(void* argv);
void unparser_spl_STACKf(void* argv);
void unparser_spl_STACKi(void* argv);
void unparser_spl_STACKc(void* argv);
void unparser_spl_STACKfpush(void* argv);
void unparser_spl_STACKipush(void* argv);
void unparser_spl_STACKcpush(void* argv);
void unparser_spl_STACKcempty(void* argv);
void unparser_spl_STACKfpop(void* argv);
void unparser_spl_STACKipop(void* argv);
void unparser_spl_STACKcpop(void* argv);
void unparser_spl_int_assign(void* argv);
void unparser_spl_float_assign(void* argv);
void unparser_spl_float_plus_assign(void* argv);
void unparser_spl_cond_if(void* argv);
void unparser_spl_cond_while(void* argv);
void unparser_spl_identifier(void* argv);
void unparser_spl_array_index(void* argv);
void unparser_spl_expr_in_brackets(void* argv);
void unparser_spl_expr_negative(void* argv);
void unparser_spl_float_const(void* argv);
void unparser_spl_float_sin(void* argv);
void unparser_spl_float_cos(void* argv);
void unparser_spl_float_exp(void* argv);
void unparser_spl_float_mul(void* argv);
void unparser_spl_float_div(void* argv);
void unparser_spl_float_add(void* argv);
void unparser_spl_float_sub(void* argv);
void unparser_spl_STACKftop(void* argv);
void unparser_spl_int_add(void* argv);
void unparser_spl_int_sub(void* argv);
void unparser_spl_int_mul(void* argv);
void unparser_spl_int_div(void* argv);
void unparser_spl_int_mudolo(void* argv);
void unparser_spl_int_const(void* argv);
void unparser_spl_STACKitop(void* argv);
void unparser_spl_STACKctop(void* argv);
void unparser_spl_boolean_or(void* argv);
void unparser_spl_boolean_and(void* argv);
void unparser_spl_eq(void* argv);
void unparser_spl_neq(void* argv);
void unparser_spl_leq(void* argv);
void unparser_spl_geq(void* argv);
void unparser_spl_lower(void* argv);
void unparser_spl_greater(void* argv);
void unparser_spl_not(void* argv);
void unparser_PARALLEL_REGION(void* argv);
void unparser_PARALLEL_FOR_REGION(void* argv);
void unparser_SEQ_DECLARATIONS(void* argv);
void unparser_INT_DECLARATION(void* argv);
void unparser_UINT_DECLARATION(void* argv);
void unparser_FLOAT_DECLARATION(void* argv);
void unparser_INT_POINTER_DECLARATION(void* argv);
void unparser_FLOAT_POINTER_DECLARATION(void* argv);
void unparser_STACKc_DECLARATION(void* argv);
void unparser_STACKi_DECLARATION(void* argv);
void unparser_STACKf_DECLARATION(void* argv);
void unparser_S(void* argv);
void unparser_omp_ATOMIC(void* argv) ;
void unparser_spl_omp_threadprivate(void* argv) ;
void unparser_spl_omp_for(void* argv) ;
void unparser_clauses(void* argv);
void unparser_FOR_LOOP_HEADER(void* argv);
void unparser_FOR_LOOP_HEADER_INIT(void* argv);
void unparser_FOR_LOOP_HEADER_VAR_DEF(void* argv);
void unparser_FOR_LOOP_HEADER_TEST(void* argv);
void unparser_FOR_LOOP_HEADER_UPDATE(void* argv);
void unparser_clauses(void* argv);
void unparser_list_of_vars(void* argv);
void unparser_cfg_entry(void* argv);
void unparser_cfg_exit(void* argv);
void unparser_OMP_RUNTIME_ROUTINE(void* argv);
void unparser_barrier(void* argv);
void unparser_master(void* argv);
void unparser_critical(void* argv);
void unparser_ad_exclusive_read_failure(void* argv);
void unparser_dummy(void* argv);
void unparser_assert(void* argv);
void unparser_before_reverse_mode_hook(void* argv);
#endif
|
prand.c | //------------------------------------------------------------------------------
// GraphBLAS/Demo/Source/prand: parallel random number generator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// A simple thread-safe parallel pseudo-random nuumber generator.
#include "GraphBLAS.h"
#undef GB_PUBLIC
#define GB_LIBRARY
#include "graphblas_demos.h"
//------------------------------------------------------------------------------
// prand macros
//------------------------------------------------------------------------------
// Generate the next seed, and extract a random 15-bit value from a seed.
#define PRAND_RECURENCE(seed) ((seed) * 1103515245 + 12345)
#define PRAND_15_MAX 32767
#define PRAND_15(seed) (((seed)/65536) % (PRAND_15_MAX + 1))
//------------------------------------------------------------------------------
// global types and operators
//------------------------------------------------------------------------------
// These can be shared by all threads in a user application, and thus are
// safely declared as global objects.
GrB_Type prand_type = NULL ;
GrB_UnaryOp prand_next_op = NULL ;
GrB_UnaryOp prand_iget_op = NULL ;
GrB_UnaryOp prand_xget_op = NULL ;
GrB_BinaryOp prand_dup_op = NULL ;
//------------------------------------------------------------------------------
// prand_next_op: unary operator to construct the next seed
//------------------------------------------------------------------------------
// z = f(x), where x is the old seed and z is the new seed.
GB_PUBLIC
void prand_next_f (prand_t *z, const prand_t *x)
{
for (int k = 0 ; k < 5 ; k++)
{
z->seed [k] = PRAND_RECURENCE (x->seed [k]) ;
}
}
//------------------------------------------------------------------------------
// prand_iget: unary operator to construct get a random integer from the seed
//------------------------------------------------------------------------------
// z = f(x), where x is a random seed, and z is an unsigned 64-bit
// pseudo-random number constructed from the seed.
GB_PUBLIC
void prand_iget_f (uint64_t *z, const prand_t *x)
{
uint64_t i = 0 ;
for (int k = 0 ; k < 5 ; k++)
{
i = PRAND_15_MAX * i + PRAND_15 (x->seed [k]) ;
}
(*z) = i ;
}
//------------------------------------------------------------------------------
// prand_xget: unary operator to construct get a random double from the seed
//------------------------------------------------------------------------------
// z = f(x), where x is a random seed, and z is a double precision
// pseudo-random number constructed from the seed, in the range 0 to 1.
GB_PUBLIC
void prand_xget_f (double *z, prand_t *x)
{
uint64_t i ;
prand_iget_f (&i, x) ;
(*z) = ((double) i) / ((double) UINT64_MAX) ;
}
//------------------------------------------------------------------------------
// prand_dup: binary operator to build a vector
//------------------------------------------------------------------------------
// This is required by GrB_Vector_build, but is never called since no
// duplicates are created. This is the SECOND operator for the prand_type.
#if defined ( __INTEL_COMPILER )
// disable icc warnings
// 869: unused parameters
#pragma warning (disable: 869 )
#elif defined ( __GNUC__ )
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
GB_PUBLIC
void prand_dup_f (prand_t *z, /* unused: */ const prand_t *x, const prand_t *y)
{
(*z) = (*y) ;
}
//------------------------------------------------------------------------------
// prand_init: create the random seed type and its operators
//------------------------------------------------------------------------------
#define PRAND_FREE_ALL \
{ \
GrB_Type_free (&prand_type) ; \
GrB_UnaryOp_free (&prand_next_op) ; \
GrB_UnaryOp_free (&prand_iget_op) ; \
GrB_UnaryOp_free (&prand_xget_op) ; \
GrB_BinaryOp_free (&prand_dup_op) ; \
}
#undef OK
#define OK(method) \
{ \
GrB_Info info = method ; \
if (info != GrB_SUCCESS) \
{ \
PRAND_FREE_ALL ; \
printf ("GraphBLAS error:\n%s\n", GrB_error ( )) ; \
return (info) ; \
} \
}
GB_PUBLIC
GrB_Info prand_init ( )
{
prand_type = NULL ;
prand_next_op = NULL ;
prand_iget_op = NULL ;
prand_xget_op = NULL ;
prand_dup_op = NULL ;
OK (GrB_Type_new (&prand_type, sizeof (prand_t))) ;
OK (GrB_UnaryOp_new (&prand_next_op, (GxB_unary_function) prand_next_f,
prand_type, prand_type)) ;
OK (GrB_UnaryOp_new (&prand_iget_op, (GxB_unary_function) prand_iget_f,
GrB_UINT64, prand_type)) ;
OK (GrB_UnaryOp_new (&prand_xget_op, (GxB_unary_function) prand_xget_f,
GrB_FP64, prand_type)) ;
OK (GrB_BinaryOp_new (&prand_dup_op, (GxB_binary_function) prand_dup_f,
prand_type, prand_type, prand_type)) ;
return (GrB_SUCCESS) ;
}
//------------------------------------------------------------------------------
// prand_finalize: free the random seed type and its operators
//------------------------------------------------------------------------------
GB_PUBLIC
GrB_Info prand_finalize ( )
{
PRAND_FREE_ALL ;
return (GrB_SUCCESS) ;
}
//------------------------------------------------------------------------------
// prand_next: get the next random numbers
//------------------------------------------------------------------------------
GB_PUBLIC
GrB_Info prand_next
(
GrB_Vector Seed
)
{
return (GrB_Vector_apply (Seed, NULL, NULL, prand_next_op, Seed, NULL)) ;
}
//------------------------------------------------------------------------------
// prand_seed: create a vector of random seeds
//------------------------------------------------------------------------------
// Returns a vector of random seed values.
#define PRAND_FREE_WORK \
{ \
free (I) ; \
free (X) ; \
}
#undef PRAND_FREE_ALL
#define PRAND_FREE_ALL \
{ \
PRAND_FREE_WORK ; \
GrB_Vector_free (Seed) ; \
}
GB_PUBLIC
GrB_Info prand_seed
(
GrB_Vector *Seed, // vector of random number seeds
int64_t seed, // scalar input seed
GrB_Index n, // size of Seed to create
int nthreads // # of threads to use (OpenMP default if <= 0)
)
{
GrB_Index *I = NULL ;
prand_t *X = NULL ;
// allocate the Seed vector
OK (GrB_Vector_new (Seed, prand_type, n)) ;
// allocate the I and X arrays
I = malloc ((n+1) * sizeof (GrB_Index)) ;
X = malloc ((n+1) * sizeof (prand_t)) ;
if (I == NULL || X == NULL)
{
PRAND_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
// determine # of threads to use
int nthreads_max = 1 ;
#ifdef _OPENMP
nthreads_max = omp_get_max_threads ( ) ;
#endif
if (nthreads <= 0 || nthreads > nthreads_max)
{
nthreads = nthreads_max ;
}
// construct the tuples for the initial seeds
int64_t i, len = (int64_t) n ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (i = 0 ; i < len ; i++)
{
I [i] = i ;
for (int k = 0 ; k < 5 ; k++)
{
X [i].seed [k] = (100000000*(seed) + 10*i + k + 1) ;
}
}
// build the Seed vector
OK (GrB_Vector_build_UDT (*Seed, I, X, n, prand_dup_op)) ;
// free workspace
PRAND_FREE_WORK ;
// advance to the first set of random numbers
OK (prand_next (*Seed)) ;
return (GrB_SUCCESS) ;
}
//------------------------------------------------------------------------------
// prand_print: print the Seed vector
//------------------------------------------------------------------------------
// This is meant for testing, not production use.
#undef PRAND_FREE_ALL
#define PRAND_FREE_ALL ;
GB_PUBLIC
GrB_Info prand_print
(
GrB_Vector Seed,
int pr // 0: print nothing, 1: print some, 2: print all
)
{
if (pr > 0)
{
GrB_Index n ;
OK (GrB_Vector_nvals (&n, Seed)) ;
printf ("\nSeed: length %g\n", (double) n) ;
prand_t x ;
for (int k = 0 ; k < 5 ; k++) x.seed [k] = -1 ;
for (int64_t i = 0 ; i < (int64_t) n ; i++)
{
if (GrB_Vector_extractElement_UDT (&x, Seed, i) == GrB_SUCCESS)
{
printf ("%g: ", (double) i) ;
for (int k = 0 ; k < 5 ; k++)
{
printf (" %.18g", (double) (x.seed [k])) ;
}
printf ("\n") ;
}
if (pr == 1 && i > 10) break ;
}
}
return (GrB_SUCCESS) ;
}
//------------------------------------------------------------------------------
// prand_iget: return a vector of random uint64 integers
//------------------------------------------------------------------------------
GB_PUBLIC
GrB_Info prand_iget
(
GrB_Vector X,
GrB_Vector Seed
)
{
OK (GrB_Vector_apply (X, NULL, NULL, prand_iget_op, Seed, NULL)) ;
return (prand_next (Seed)) ;
}
//------------------------------------------------------------------------------
// prand_xget: return a vector of random doubles, in range 0 to 1 inclusive
//------------------------------------------------------------------------------
GB_PUBLIC
GrB_Info prand_xget
(
GrB_Vector X,
GrB_Vector Seed
)
{
OK (GrB_Vector_apply (X, NULL, NULL, prand_xget_op, Seed, NULL)) ;
return (prand_next (Seed)) ;
}
|
KernelCaller.h | /*
* kernelCaller.h
*
* Created on: Oct 2, 2019
* Author: carol
*/
#ifndef KERNELCALLER_H_
#define KERNELCALLER_H_
#include "nondmr_kernels.h"
#include "dmr_kernels.h"
#include "types.h"
#include "block_threshold.h"
#include <iomanip> // std::setprecision
#include <sstream> // std::stringstream
#include <iostream> // std::cout
#include <algorithm> // std::max_element
template<const uint32_t COUNT, typename half_t, typename real_t>
struct KernelCaller {
const uint32_t threshold_;
//DMR
VectorOfDeviceVector<FOUR_VECTOR<half_t>> d_fv_gpu_ht;
std::vector<std::vector<FOUR_VECTOR<half_t>>>fv_cpu_ht;
virtual ~KernelCaller() = default; //{}
virtual void set_half_t_vectors(uint32_t nstreams, uint32_t element_per_stream) {}
virtual void sync_half_t() {}
virtual void clear_half_t() {}
virtual uint32_t get_max_threshold(std::vector<std::vector<FOUR_VECTOR<real_t>>>& fv_cpu_rt) {return 0;};
KernelCaller(const uint32_t threshold = 0) : threshold_(threshold) {}
virtual void kernel_call(dim3& blocks, dim3& threads, CudaStream& stream,
par_str<real_t>& par_cpu, dim_str& dim_cpu, box_str* d_box_gpu,
FOUR_VECTOR<real_t>* d_rv_gpu, real_t* d_qv_gpu,
FOUR_VECTOR<real_t>* d_fv_gpu, const uint32_t stream_idx) = 0;
virtual bool cmp(std::vector<FOUR_VECTOR<real_t>>& fv_cpu_rt, std::vector<FOUR_VECTOR<real_t>>& fv_cpu_GOLD,
rad::Log& log, uint32_t streamIdx, bool verbose, uint32_t i, uint32_t& host_errors) {
auto val_gold = fv_cpu_GOLD[i];
auto val_output = fv_cpu_rt[i];
if (val_gold != val_output) {
#pragma omp critical
{
host_errors++;
std::stringstream error_detail;
error_detail << std::scientific << std::setprecision(20);
error_detail << "stream: " << streamIdx;
error_detail << ", p: [" << i << "]";
error_detail << ", v_r: " << val_output.v << ", v_e: " << val_gold.v;
error_detail << ", x_r: " << val_output.x << ", x_e: " << val_gold.x;
error_detail << ", y_r: " << val_output.y << ", y_e: " << val_gold.y;
error_detail << ", z_r: " << val_output.z << ", z_e: " << val_gold.z;
if (verbose && (host_errors < 10)) {
std::cout << error_detail.str() << std::endl;
}
log.log_error_detail(error_detail.str());
}
}
return false;
}
// Returns true if no errors are found. False if otherwise.
// Set votedOutput pointer to retrieve the voted matrix
bool check_output_errors(bool verbose, uint32_t streamIdx,
std::vector<FOUR_VECTOR<real_t>>& fv_cpu_rt,
std::vector<FOUR_VECTOR<real_t>>& fv_cpu_GOLD,
rad::Log& log) {
uint32_t host_errors = 0;
uint32_t memory_errors = 0;
this->sync_half_t();
#pragma omp parallel for shared(host_errors, memory_errors)
for (uint32_t i = 0; i < fv_cpu_GOLD.size(); i++) {
auto is_dmr_diff = this->cmp(fv_cpu_rt, fv_cpu_GOLD, log, streamIdx, verbose, i, host_errors);
#pragma omp critical
{
memory_errors += is_dmr_diff;
}
}
if (host_errors != 0) {
std::cout << "#";
std::string error_detail;
error_detail = "errors: " + std::to_string(host_errors);
//log as info to not count as error detail
log.log_info_detail(error_detail);
}
//TODO: Check how to get dmr errors properly
auto dmr_errors = 0;//get_dmr_error();
if (dmr_errors != 0) {
std::string error_detail = "detected_dmr_errors: " + std::to_string(dmr_errors);
if (verbose) {
std::cout << error_detail << std::endl;
}
log.log_info_detail(error_detail);
// log.update_infos();
}
if(memory_errors != 0) {
std::string error_detail = "dmr1_equals_dmr2_detected: " + std::to_string(dmr_errors);
if (verbose) {
std::cout << error_detail << std::endl;
}
log.log_info_detail(error_detail);
log.update_infos();
}
// the error update is done inside the class <-- IS NOT EFFICIENT
log.update_errors();
return (host_errors == 0);
}
};
template<const uint32_t COUNT, typename half_t, typename real_t>
struct DMRMixedKernelCaller: public KernelCaller<COUNT, half_t, real_t> {
#ifdef BUILDRELATIVEERROR
std::vector<float> thresholds_host;
#else
std::vector<uint32_t> thresholds_host;
#endif
DMRMixedKernelCaller(const uint32_t threshold) :
KernelCaller<COUNT, half_t, real_t>(threshold) {
#ifdef BUILDRELATIVEERROR
this->thresholds_host = std::vector<float>(THRESHOLD_SIZE_THREAD * 2);
//Store lower limits and upper limits after
std::fill_n(this->thresholds_host.begin(), THRESHOLD_SIZE_THREAD, 9999);
std::fill_n(this->thresholds_host.begin() + THRESHOLD_SIZE_THREAD, THRESHOLD_SIZE_THREAD, -9999);
std::string path(THRESHOLD_PATH);
File<float>::read_from_file(path, thresholds_host);
//load lower limits
rad::checkFrameworkErrors(
cudaMemcpyToSymbol(lower_relative_limit, this->thresholds_host.data(),
sizeof(float) * THRESHOLD_SIZE_THREAD, 0,
cudaMemcpyHostToDevice));
//load upper limits
rad::checkFrameworkErrors(
cudaMemcpyToSymbol(upper_relative_limit,
this->thresholds_host.data() + THRESHOLD_SIZE_THREAD,
sizeof(float) * THRESHOLD_SIZE_THREAD, 0,
cudaMemcpyHostToDevice));
#else
this->thresholds_host = std::vector < uint32_t > (THRESHOLD_SIZE, 0);
std::string path(THRESHOLD_PATH);
File<uint32_t>::read_from_file(path, thresholds_host);
rad::checkFrameworkErrors(
cudaMemcpyToSymbol(thresholds, thresholds_host.data(),
sizeof(uint32_t) * THRESHOLD_SIZE, 0, cudaMemcpyHostToDevice));
#endif
}
uint32_t get_max_threshold(std::vector<std::vector<FOUR_VECTOR<real_t>>>& fv_cpu_rt) {
real_t max_threshold = -3333;
for (uint32_t i = 0; i < fv_cpu_rt.size(); i++) {
auto& fv_rt_i = fv_cpu_rt[i];
auto& fv_ht_i = this->fv_cpu_ht[i];
for(uint32_t j = 0; j < fv_rt_i.size(); j++) {
auto& fv_rt_ij = fv_rt_i[j];
auto& fv_ht_ij = fv_ht_i[j];
max_threshold = std::max(std::fabs((real_t)fv_rt_ij.v - (real_t)fv_ht_ij.v), max_threshold);
max_threshold = std::max(std::fabs((real_t)fv_rt_ij.x - (real_t)fv_ht_ij.x), max_threshold);
max_threshold = std::max(std::fabs((real_t)fv_rt_ij.y - (real_t)fv_ht_ij.y), max_threshold);
max_threshold = std::max(std::fabs((real_t)fv_rt_ij.z - (real_t)fv_ht_ij.z), max_threshold);
}
}
#ifdef BUILDRELATIVEERROR
//Copy the block lower limits
rad::checkFrameworkErrors(
cudaMemcpyFromSymbol(this->thresholds_host.data(), lower_relative_limit,
sizeof(float) * THRESHOLD_SIZE_THREAD, 0,
cudaMemcpyDeviceToHost));
//upper limits
rad::checkFrameworkErrors(
cudaMemcpyFromSymbol(this->thresholds_host.data() + THRESHOLD_SIZE_THREAD, upper_relative_limit,
sizeof(float) * THRESHOLD_SIZE_THREAD, 0,
cudaMemcpyDeviceToHost));
std::string path(THRESHOLD_PATH);
File<float>::write_to_file(path, this->thresholds_host);
#else
//Copy the block threshold back
rad::checkFrameworkErrors(
cudaMemcpyFromSymbol(this->thresholds_host.data(),thresholds,
sizeof(uint32_t) * THRESHOLD_SIZE, 0,
cudaMemcpyDeviceToHost));
std::string path(THRESHOLD_PATH);
File<uint32_t>::write_to_file(path, this->thresholds_host);
#endif
return max_threshold;
}
void sync_half_t() override {
for (uint32_t i = 0; i < this->d_fv_gpu_ht.size(); i++) {
this->fv_cpu_ht[i] = this->d_fv_gpu_ht[i].to_vector();
}
}
void clear_half_t() override {
for (uint32_t i = 0; i < this->d_fv_gpu_ht.size(); i++) {
std::fill(this->fv_cpu_ht[i].begin(), this->fv_cpu_ht[i].end(), FOUR_VECTOR<half_t>());
this->d_fv_gpu_ht[i].clear();
}
}
void set_half_t_vectors(uint32_t nstreams, uint32_t element_per_stream) {
this->d_fv_gpu_ht.resize(nstreams);
this->fv_cpu_ht.resize(nstreams);
for (auto i = 0; i < nstreams; i++) {
this->d_fv_gpu_ht[i].resize(element_per_stream);
this->fv_cpu_ht[i].resize(element_per_stream);
}
}
bool cmp(std::vector<FOUR_VECTOR<real_t>>& fv_cpu_rt,
std::vector<FOUR_VECTOR<real_t>>& fv_cpu_GOLD, rad::Log& log,
uint32_t streamIdx, bool verbose, uint32_t i, uint32_t& host_errors)
override {
auto val_gold = fv_cpu_GOLD[i];
auto val_output = fv_cpu_rt[i];
auto val_output_ht = this->fv_cpu_ht[streamIdx][i];
bool result = false;
if (val_gold != val_output) {
std::stringstream error_detail;
error_detail << std::scientific << std::setprecision(20);
error_detail << "stream: " << streamIdx;
error_detail << ", p: [" << i << "]";
error_detail << ", v_r: " << val_output.v << ", v_e: "
<< val_gold.v;
error_detail << ", x_r: " << val_output.x << ", x_e: "
<< val_gold.x;
error_detail << ", y_r: " << val_output.y << ", y_e: "
<< val_gold.y;
error_detail << ", z_r: " << val_output.z << ", z_e: "
<< val_gold.z;
error_detail << ", s_v_r: " << val_output_ht.v;
error_detail << ", s_x_r: " << val_output_ht.x;
error_detail << ", s_y_r: " << val_output_ht.y;
error_detail << ", s_z_r: " << val_output_ht.z;
if (verbose && (host_errors < 10)) {
std::cout << error_detail.str() << std::endl;
}
auto result_i = check_bit_error(val_output_ht, val_output, val_gold, i);
#pragma omp critical
{
host_errors++;
log.log_error_detail(error_detail.str());
result = result_i;
}
}
return result;
}
void kernel_call(dim3& blocks, dim3& threads, CudaStream& stream,
par_str<real_t>& par_cpu, dim_str& dim_cpu, box_str* d_box_gpu,
FOUR_VECTOR<real_t>* d_rv_gpu, real_t* d_qv_gpu,
FOUR_VECTOR<real_t>* d_fv_gpu, const uint32_t stream_idx) {
kernel_gpu_cuda_dmr<COUNT> <<<blocks, threads, 0, stream.stream>>>(
par_cpu, dim_cpu, d_box_gpu, d_rv_gpu, d_qv_gpu, d_fv_gpu,
this->d_fv_gpu_ht[stream_idx].data(), this->threshold_);
// kernel_gpu_cuda<<<blocks, threads, 0, stream.stream>>>(
// par_cpu, dim_cpu, d_box_gpu, d_rv_gpu, d_qv_gpu, d_fv_gpu);
//
// kernel_gpu_cuda<<<blocks, threads, 0, stream.stream>>>(
// par_cpu, dim_cpu, d_box_gpu, d_rv_gpu, d_qv_gpu,
// this->d_fv_gpu_ht[stream_idx].data());
stream.sync();
//
// compare_two_outputs<<<blocks, threads, 0, stream.stream>>>
// (this->d_fv_gpu_ht[stream_idx].data(), d_fv_gpu);
}
inline std::vector<uint32_t>
get_4vector_diffs(FOUR_VECTOR<float>& lhs, FOUR_VECTOR<double>& rhs) {
float rhs_float_v = float(rhs.v);
float rhs_float_x = float(rhs.x);
float rhs_float_y = float(rhs.y);
float rhs_float_z = float(rhs.z);
//To INT
uint32_t rhs_data_v = reinterpret_cast<uint32_t&>(rhs_float_v);
uint32_t rhs_data_x = reinterpret_cast<uint32_t&>(rhs_float_x);
uint32_t rhs_data_y = reinterpret_cast<uint32_t&>(rhs_float_y);
uint32_t rhs_data_z = reinterpret_cast<uint32_t&>(rhs_float_z);
uint32_t lhs_data_v = reinterpret_cast<uint32_t&>(lhs.v);
uint32_t lhs_data_x = reinterpret_cast<uint32_t&>(lhs.x);
uint32_t lhs_data_y = reinterpret_cast<uint32_t&>(lhs.y);
uint32_t lhs_data_z = reinterpret_cast<uint32_t&>(lhs.z);
uint32_t sub_res_v = SUB_ABS(lhs_data_v, rhs_data_v);
uint32_t sub_res_x = SUB_ABS(lhs_data_x, rhs_data_x);
uint32_t sub_res_y = SUB_ABS(lhs_data_y, rhs_data_y);
uint32_t sub_res_z = SUB_ABS(lhs_data_z, rhs_data_z);
return {sub_res_v, sub_res_x, sub_res_y, sub_res_z};
}
inline std::vector<uint32_t>
get_4vector_diffs(FOUR_VECTOR<real_t>& lhs, FOUR_VECTOR<real_t>& rhs) {
return {0, 0, 0, 0};
}
bool check_bit_error(FOUR_VECTOR<float>& lhs, FOUR_VECTOR<double>& rhs, FOUR_VECTOR<double>& gold, uint32_t i) {
float relative_v = lhs.v / rhs.v;
float relative_x = lhs.x / rhs.x;
float relative_y = lhs.y / rhs.y;
float relative_z = lhs.z / rhs.z;
float min_relative = this->thresholds_host[i];
float max_relative = this->thresholds_host[i * 2];
if(((relative_v < min_relative || relative_v > max_relative) && gold.v != rhs.v) ||
((relative_x < min_relative || relative_x > max_relative) && gold.x != rhs.x) ||
((relative_y < min_relative || relative_y > max_relative) && gold.y != rhs.y) ||
((relative_z < min_relative || relative_z > max_relative) && gold.z != rhs.z)) {
return true;
}
return false;
// auto diff_vec = this->get_4vector_diffs(lhs, rhs);
//
// for(auto it : diff_vec) {
// if(it > this->threshold_) {
// return true;
// }
// }
// return false;
}
bool check_bit_error(FOUR_VECTOR<real_t>& lhs, FOUR_VECTOR<real_t>& rhs, FOUR_VECTOR<real_t>& gold, uint32_t i) {
if((lhs.v != rhs.v && gold.v != rhs.v) ||
(lhs.x != rhs.x && gold.x != rhs.x) ||
(lhs.y != rhs.y && gold.y != rhs.y) ||
(lhs.z != rhs.z && gold.z != rhs.z)) {
return true;
}
return false;
// if (rhs->v != rhs.v && //V
// rhs->x != rhs.x && //X
// rhs->y != rhs.y && //Y
// rhs->z != rhs.z) { //Z
// return false;
// }
// return true;
}
};
template<typename real_t>
struct UnhardenedKernelCaller: public KernelCaller<0, real_t, real_t> {
void kernel_call(dim3& blocks, dim3& threads, CudaStream& stream, par_str<real_t>& par_cpu,
dim_str& dim_cpu, box_str* d_box_gpu, FOUR_VECTOR<real_t>* d_rv_gpu, real_t* d_qv_gpu,
FOUR_VECTOR<real_t>* d_fv_gpu, const uint32_t stream_idx) {
kernel_gpu_cuda_nondmr<<<blocks, threads, 0, stream.stream>>>(par_cpu, dim_cpu, d_box_gpu,
d_rv_gpu, d_qv_gpu, d_fv_gpu);
}
};
template<typename real_t>
struct DMRKernelCaller: public DMRMixedKernelCaller<NUMBER_PAR_PER_BOX + 2, real_t, real_t> {
void kernel_call(dim3& blocks, dim3& threads, CudaStream& stream, par_str<real_t>& par_cpu,
dim_str& dim_cpu, box_str* d_box_gpu, FOUR_VECTOR<real_t>* d_rv_gpu, real_t* d_qv_gpu,
FOUR_VECTOR<real_t>* d_fv_gpu, const uint32_t stream_idx) {
kernel_gpu_cuda_nondmr<<<blocks, threads, 0, stream.stream>>>(par_cpu, dim_cpu, d_box_gpu,
d_rv_gpu, d_qv_gpu, d_fv_gpu);
kernel_gpu_cuda_nondmr<<<blocks, threads, 0, stream.stream>>>(par_cpu, dim_cpu, d_box_gpu,
d_rv_gpu, d_qv_gpu, this->d_fv_gpu_ht[stream_idx].data());
stream.sync();
/*
* blocks.x = dim_cpu.number_boxes;
threads.x = NUMBER_THREADS;
so the number of elements
*/
static uint32_t elements = blocks.x * threads.x;
static uint32_t thread_block = 1024;
static uint32_t thread_grid = ceil(float(elements) / float(thread_block));
compare_two_outputs<<<thread_grid, thread_block, 0, stream.stream>>>(d_fv_gpu,
this->d_fv_gpu_ht[stream_idx].data());
}
DMRKernelCaller() :
DMRMixedKernelCaller<NUMBER_PAR_PER_BOX + 2, real_t, real_t>(0) {
}
};
#endif /* KERNELCALLER_H_ */
|
deconvolution_pack4to1.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void deconvolution_pack4to1_msa(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_pack4to1, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int channels = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1;
const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1;
const int maxk = kernel_w * kernel_h;
const float* bias_data_ptr = bias_data;
// num_output
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
float* outptr = top_blob.channel(p);
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
float sum = 0.f;
if (bias_data_ptr)
{
sum = bias_data_ptr[p];
}
v4f32 _sum = (v4f32)__msa_fill_w(0);
const float* kptr = (const float*)weight_data_pack4to1 + maxk * channels * p * 4;
// channels
for (int q = 0; q < channels; q++)
{
const Mat m = bottom_blob.channel(q);
for (int y = 0; y < kernel_h; y++)
{
int sys = (i + y * dilation_h - (kernel_extent_h - 1));
if (sys < 0 || sys % stride_h != 0)
continue;
int sy = sys / stride_h;
if (sy >= h)
continue;
for (int x = 0; x < kernel_w; x++)
{
int sxs = (j + x * dilation_w - (kernel_extent_w - 1));
if (sxs < 0 || sxs % stride_w != 0)
continue;
int sx = sxs / stride_w;
if (sx >= w)
continue;
const float* sptr = m.row(sy) + sx * 4;
int k = y * kernel_w + x;
v4f32 _val = (v4f32)__msa_ld_w(sptr, 0);
v4f32 _w = (v4f32)__msa_ld_w(kptr + k * 4, 0);
_sum = __msa_fadd_w(_sum, __msa_fmul_w(_val, _w));
}
}
kptr += maxk * 4;
}
sum += __msa_fhadd_w(_sum);
sum = activation_ss(sum, activation_type, activation_params);
outptr[j] = sum;
}
outptr += outw;
}
}
}
|
NDArray.h | #ifndef NDARRAY_H
#define NDARRAY_H
#include <initializer_list>
#include <functional>
#include <shape.h>
#include "NativeOpExcutioner.h"
#include <memory/Workspace.h>
#include <indexing/NDIndex.h>
#include <indexing/IndicesList.h>
#include <graph/Intervals.h>
#include <array/DataType.h>
#include <stdint.h>
namespace nd4j {
template<typename T> class ND4J_EXPORT NDArray;
ND4J_EXPORT NDArray<float> operator-(const float, const NDArray<float>&);
ND4J_EXPORT NDArray<float16> operator-(const float16, const NDArray<float16>&);
ND4J_EXPORT NDArray<double> operator-(const double, const NDArray<double>&);
ND4J_EXPORT NDArray<float> operator+(const float, const NDArray<float>&);
ND4J_EXPORT NDArray<float16> operator+(const float16, const NDArray<float16>&);
ND4J_EXPORT NDArray<double> operator+(const double, const NDArray<double>&);
template<typename T> NDArray<T> mmul(const NDArray<T>&, const NDArray<T>&);
template<typename T>
class NDArray {
protected:
/**
* if true then array doesn't own buffer and simply points to another's buffer
*/
bool _isView = false;
/**
* pointer on flattened data array in memory
*/
T *_buffer = nullptr;
/**
* contains shape info: matrix rank, numbers of elements per each dimension, dimensions strides, element-wise-stride, c-like or fortan-like order
*/
Nd4jLong *_shapeInfo = nullptr;
/**
* pointer on externally allocated memory where _buffer and _shapeInfo are stored
*/
nd4j::memory::Workspace* _workspace = nullptr;
/**
* alternative buffers for special computational devices (like GPUs for CUDA)
*/
T* _bufferD = nullptr;
Nd4jLong *_shapeInfoD = nullptr;
/**
* indicates whether user allocates memory for _buffer/_shapeInfo by himself, in opposite case the memory must be allocated from outside
*/
bool _isShapeAlloc = false;
bool _isBuffAlloc = false;
/**
* type of array elements
*/
DataType _dataType = DataType_FLOAT;
std::string toStringValue(T value);
public:
/**
* default constructor, do not allocate memory, memory for array is passed from outside
*/
NDArray(T *buffer = nullptr, Nd4jLong* shapeInfo = nullptr, nd4j::memory::Workspace* workspace = nullptr);
NDArray(std::initializer_list<Nd4jLong> shape, nd4j::memory::Workspace* workspace = nullptr);
/**
* Constructor for scalar NDArray
*/
NDArray(T scalar);
/**
* copy constructor
*/
NDArray(const NDArray<T>& other);
/**
* move constructor
*/
NDArray(NDArray<T>&& other) noexcept;
#ifndef __JAVACPP_HACK__
// this method only available out of javacpp
/**
* This constructor creates vector of T
*
* @param values
*/
NDArray(std::initializer_list<T> values, nd4j::memory::Workspace* workspace = nullptr);
NDArray(std::vector<T> &values, nd4j::memory::Workspace* workspace = nullptr);
#endif
/**
* constructor, create empty array stored at given workspace
*/
NDArray(nd4j::memory::Workspace* workspace);
/**
* this constructor creates new NDArray with shape matching "other" array, do not copy "other" elements into new array
*/
NDArray(const NDArray<T> *other, const bool copyStrides = false, nd4j::memory::Workspace* workspace = nullptr);
/**
* constructor creates new NDArray using shape information from "shapeInfo", set all elements in new array to be zeros, if copyStrides is true then use stride values from "shapeInfo", else calculate strides independently
*/
NDArray(const Nd4jLong* shapeInfo, const bool copyStrides = false, nd4j::memory::Workspace* workspace = nullptr);
/**
* this constructor creates new array using shape information contained in vector argument
*/
NDArray(const char order, const std::vector<Nd4jLong> &shape, nd4j::memory::Workspace* workspace = nullptr);
/**
* This constructor creates new array with elements copied from data and using shape information stored in shape
*
* PLEASE NOTE: data will be copied AS IS, without respect to specified order. You must ensure order match here.
*/
NDArray(const char order, const std::vector<Nd4jLong> &shape, const std::vector<T> &data, nd4j::memory::Workspace* workspace = nullptr);
/**
* this constructor creates new array using given buffer (without memory allocating) and shape information stored in shape
*/
NDArray(T *buffer, const char order, const std::vector<Nd4jLong> &shape , nd4j::memory::Workspace* workspace = nullptr);
/**
* copy assignment operator
*/
NDArray<T>& operator=(const NDArray<T>& other);
/**
* move assignment operator
*/
NDArray<T>& operator=(NDArray<T>&& other) noexcept;
/**
* assignment operator, assigns the same scalar to all array elements
*/
NDArray<T>& operator=(const T scalar);
/**
* operators for memory allocation and deletion
*/
void* operator new(size_t i);
void operator delete(void* p);
/**
* method replaces existing buffer/shapeinfo, AND releases original pointers (if releaseExisting TRUE)
*/
void replacePointers(T *buffer, Nd4jLong *shapeInfo, const bool releaseExisting = true);
/**
* create a new array by replicating current array by repeats times along given dimension
* dimension - dimension along which to repeat elements
* repeats - number of repetitions
*/
NDArray<T>* repeat(int dimension, const std::vector<Nd4jLong>& repeats) const;
/**
* fill target array by repeating current array
* dimension - dimension along which to repeat elements
*/
void repeat(int dimension, NDArray<T>& target) const;
/**
* return _dataType;
*/
DataType dataType() const;
/**
* creates array which is view of this array
*/
NDArray<T>* getView();
/**
* creates array which points on certain sub-range of this array, sub-range is defined by given indices
*/
NDArray<T> *subarray(IndicesList& indices) const;
NDArray<T> *subarray(IndicesList& indices, std::vector<Nd4jLong>& strides) const;
NDArray<T>* subarray(const std::initializer_list<NDIndex*>& idx) const;
NDArray<T>* subarray(const Intervals& idx) const;
/**
* cast array elements to given dtype
*/
NDArray<T>* cast(DataType dtype);
void cast(NDArray<T>* target, DataType dtype);
/**
* returns _workspace
*/
nd4j::memory::Workspace* getWorkspace() const {
return _workspace;
}
/**
* returns _buffer
*/
T* getBuffer();
T* buffer();
/**
* returns _shapeInfo
*/
Nd4jLong* shapeInfo();
Nd4jLong* getShapeInfo() const;
/**
* if _bufferD==nullptr return _buffer, else return _bufferD
*/
T* specialBuffer();
/**
* if _shapeInfoD==nullptr return _shapeInfo, else return _shapeInfoD
*/
Nd4jLong* specialShapeInfo();
/**
* set values for _bufferD and _shapeInfoD
*/
void setSpecialBuffers(T * buffer, Nd4jLong *shape);
/**
* permutes (in-place) the dimensions in array according to "dimensions" array
*/
bool permutei(const std::initializer_list<int>& dimensions);
bool permutei(const std::vector<int>& dimensions);
bool permutei(const int* dimensions, const int rank);
bool permutei(const std::initializer_list<Nd4jLong>& dimensions);
bool permutei(const std::vector<Nd4jLong>& dimensions);
bool permutei(const Nd4jLong* dimensions, const int rank);
/**
* permutes the dimensions in array according to "dimensions" array, new array points on _buffer of this array
*/
NDArray<T>* permute(const std::initializer_list<int>& dimensions) const;
NDArray<T>* permute(const std::vector<int>& dimensions) const;
NDArray<T>* permute(const int* dimensions, const int rank) const;
void permute(const int* dimensions, const int rank, NDArray<T>& target) const;
void permute(const std::vector<int>& dimensions, NDArray<T>& target) const;
NDArray<T>* permute(const std::initializer_list<Nd4jLong>& dimensions) const;
NDArray<T>* permute(const std::vector<Nd4jLong>& dimensions) const;
NDArray<T>* permute(const Nd4jLong* dimensions, const int rank) const;
void permute(const Nd4jLong* dimensions, const int rank, NDArray<T>& target) const;
void permute(const std::vector<Nd4jLong>& dimensions, NDArray<T>& target) const;
/**
* This method streamlines given view or permuted array, and reallocates buffer
*/
void streamline(char order = 'a');
/**
* check whether array is contiguous in memory
*/
bool isContiguous();
/**
* prints information about array shape
* msg - message to print out
*/
void printShapeInfo(const char * msg = nullptr) const;
/**
* prints buffer elements
* msg - message to print out
* limit - number of array elements to print out
*/
void printBuffer(const char* msg = nullptr, Nd4jLong limit = -1);
/**
* prints buffer elements, takes into account offset between elements (element-wise-stride)
* msg - message to print out
* limit - number of array elements to print out
*/
void printIndexedBuffer(const char* msg = nullptr, Nd4jLong limit = -1) const;
std::string asIndexedString(Nd4jLong limit = -1);
std::string asString(Nd4jLong limit = -1);
/**
* this method assigns values of given array to this one
*/
void assign(const NDArray<T>* other);
/**
* this method assigns values of given array to this one
*/
void assign(const NDArray<T>& other);
/**
* this method assigns given value to all elements in array
*/
void assign(const T value);
/**
* returns new copy of this array, optionally in different order
*/
NDArray<T> *dup(const char newOrder = 'a');
/**
* returns sum of all elements of array
*/
T sumNumber() const;
/**
* returns mean number of array
*/
T meanNumber() const;
/**
* This method explicitly enforces new shape for this NDArray, old shape/stride information is lost
*/
void enforce(const std::initializer_list<Nd4jLong> &dimensions, char order = 'a');
void enforce(std::vector<Nd4jLong> &dimensions, char order = 'a');
/**
* calculates sum along dimension(s) in this array and save it to created reduced array
* dimensions - array of dimensions to calculate sum over
* keepDims - if true then put unities in place of reduced dimensions
*/
NDArray<T> *sum(const std::vector<int> &dimensions) const;
/**
* method reduces array by excluding its shapes along dimensions present in given dimensions vector, result is stored in new array to be returned
* dimensions - array of dimensions to reduce along
* keepDims - if true then put unities in place of reduced dimensions
*/
template<typename OpName>
NDArray<T>* reduceAlongDimension(const std::vector<int>& dimensions, const bool keepDims = false, const bool supportOldShapes = false) const;
template<typename OpName>
NDArray<T>* reduceAlongDimension(const std::initializer_list<int>& dimensions, const bool keepDims = false, const bool supportOldShapes = false) const;
template<typename OpName>
NDArray<T> reduceAlongDims(const std::vector<int>& dimensions, const bool keepDims = false, const bool supportOldShapes = false) const;
/**
* method reduces array by excluding its shapes along dimensions present in given dimensions vector
* target - where to save result of reducing
* dimensions - array of dimensions to reduce along
* keepDims - if true then put unities in place of reduced dimensions
* extras - extra parameters
*/
template<typename OpName>
void reduceAlongDimension(NDArray<T>* target, const std::vector<int>& dimensions, const bool keepDims = false, const bool supportOldShapes = false, T *extras = nullptr) const;
/**
* return variance of array elements set
* biasCorrected - if true bias correction will be applied
*/
template<typename OpName>
T varianceNumber(bool biasCorrected = true);
/**
* apply scalar operation to array
* extraParams - extra parameters for operation
*/
template<typename OpName>
T reduceNumber(T *extraParams = nullptr) const;
/**
* returns element index which corresponds to some condition imposed by operation
* extraParams - extra parameters for operation
*/
template<typename OpName>
Nd4jLong indexReduceNumber(T *extraParams = nullptr);
/**
* returns index of max element in a given array (optionally: along given dimension(s))
* dimensions - optional vector with dimensions
*/
Nd4jLong argMax(std::initializer_list<int> dimensions = {});
/**
* apply OpName transformation directly to array
* extraParams - extra parameters for operation
*/
template<typename OpName>
void applyTransform(T *extraParams = nullptr);
/**
* apply OpName transformation to array and store result in target
* target - where to store result
* extraParams - extra parameters for operation
*/
template<typename OpName>
void applyTransform(NDArray<T> *target, T *extraParams = nullptr);
/**
* apply OpName transformation to this array and store result in new array being returned
* extraParams - extra parameters for operation
*/
template<typename OpName>
NDArray<T> transform(T *extraParams = nullptr);
/**
* apply pairwise OpName transformation based on "this" and "other" arras elements, store result in this array
* other - second array necessary for pairwise operation
* extraParams - extra parameters for operation
*/
template<typename OpName>
void applyPairwiseTransform(NDArray<T> *other, T *extraParams);
/**
* apply pairwise OpName transformation based on "this" and "other" arras elements, store result in target array
* other - second array necessary for pairwise operation
* target - where to store result
* extraParams - extra parameters for operation
*/
template<typename OpName>
void applyPairwiseTransform(NDArray<T> *other, NDArray<T> *target, T *extraParams);
/**
* apply operation which requires broadcasting, broadcast a smaller array (tad) along bigger one (this)
* tad - array to broadcast
* dimensions - dimensions array to broadcast along
* target - where to store result
* extraParams - extra parameters for operation
*/
template<typename OpName>
void applyBroadcast(std::initializer_list<int> dimensions, const NDArray<T>* tad, NDArray<T>* target = nullptr, T* extraArgs = nullptr);
template <typename OpName>
void applyBroadcast(std::vector<int> &dimensions, const NDArray<T> *tad, NDArray<T> *target = nullptr, T *extraArgs = nullptr);
/**
* apply operation which requires broadcasting, broadcast one tensor along another, also this method checks the possibility of broadcasting
* other - input array
* extraParams - extra parameters for operation
*/
template <typename OpName>
NDArray<T> applyTrueBroadcast(const NDArray<T>& other, T *extraArgs = nullptr) const;
template <typename OpName>
NDArray<T>* applyTrueBroadcast(const NDArray<T>* other, T *extraArgs = nullptr) const;
/**
* apply operation which requires broadcasting, broadcast one tensor along another, also this method checks the possibility of broadcasting
* other - input array
* target - where to store result
* checkTargetShape - if true check whether target shape is suitable for broadcasting
* extraParams - extra parameters for operation
*/
template <typename OpName>
void applyTrueBroadcast(const NDArray<T>* other, NDArray<T>* target, const bool checkTargetShape = true, T *extraArgs = nullptr) const;
/**
* apply a scalar operation to an array
* scalar - input scalar
* target - where to store result
* extraParams - extra parameters for operation
*/
template<typename OpName>
void applyScalar(T scalar, NDArray<T>* target = nullptr, T *extraParams = nullptr);
/**
* apply a scalar operation to an array
* scalar - input array which is simple scalar
* target - where to store result
* extraParams - extra parameters for operation
*/
template<typename OpName>
void applyScalar(NDArray<T>& scalar, NDArray<T>* target = nullptr, T *extraParams = nullptr);
#ifndef __JAVACPP_HACK__
/**
* apply operation "func" to an array
* func - what operation to apply
* target - where to store result
*/
void applyLambda(const std::function<T(T)>& func, NDArray<T>* target = nullptr);
void applyIndexedLambda(const std::function<T(Nd4jLong, T)>& func, NDArray<T>* target = nullptr);
/**
* apply pairwise operation "func" to an array
* other - input array
* func - what pairwise operation to apply
* target - where to store result
*/
void applyPairwiseLambda(NDArray<T>* other, const std::function<T(T, T)>& func, NDArray<T>* target = nullptr);
void applyIndexedPairwiseLambda(NDArray<T>* other, const std::function<T(Nd4jLong, T, T)>& func, NDArray<T>* target = nullptr);
void applyTriplewiseLambda(NDArray<T>* second, NDArray<T> *third, const std::function<T(T, T, T)>& func, NDArray<T>* target = nullptr);
#endif
/**
* apply OpName random operation to array
* buffer - pointer on RandomBuffer
* y - optional input array
* z - optional input array
* extraArgs - extra parameters for operation
*/
template<typename OpName>
void applyRandom(nd4j::random::RandomBuffer *buffer, NDArray<T>* y = nullptr, NDArray<T>* z = nullptr, T* extraArgs = nullptr);
/**
* apply transpose operation to the copy of this array, that is this array remains unaffected
*/
NDArray<T> *transpose() const;
/**
* perform transpose operation and store result in target, this array remains unaffected
* target - where to store result
*/
void transpose(NDArray<T>& target) const;
/**
* apply in-place transpose operation to this array, so this array becomes transposed
*/
void transposei();
/**
* return array pointing on certain range of this array
* index - the number of array to be returned among set of possible arrays
* dimensions - array of dimensions to point on
*/
NDArray<T>* tensorAlongDimension(Nd4jLong index, const std::initializer_list<int>& dimensions) const;
NDArray<T>* tensorAlongDimension(Nd4jLong index, const std::vector<int>& dimensions) const;
/**
* returns the number of arrays pointing on specified dimension(s)
* dimensions - array of dimensions to point on
*/
Nd4jLong tensorsAlongDimension(const std::initializer_list<int> dimensions) const ;
Nd4jLong tensorsAlongDimension(const std::vector<int>& dimensions) const ;
/**
* returns true if elements of two arrays are equal to within given epsilon value
* other - input array to compare
* eps - epsilon, this value defines the precision of elements comparison
*/
bool equalsTo(const NDArray<T> *other, T eps = (T) 1e-5f) const;
bool equalsTo(NDArray<T> &other, T eps = (T) 1e-5f) const;
/**
* add given row vector to all rows of this array
* row - row vector to add
*/
void addiRowVector(const NDArray<T> *row);
/**
* add given row vector to all rows of this array, store result in target
* row - row vector to add
* target - where to store result
*/
void addRowVector(const NDArray<T> *row, NDArray<T>* target) const;
/**
* subtract given row vector from all rows of this array, store result in target
* row - row vector to subtract
* target - where to store result
*/
void subRowVector(const NDArray<T> *row, NDArray<T>* target) const;
/**
* multiply all rows of this array on given row vector, store result in target
* row - row vector to multiply on
* target - where to store result
*/
void mulRowVector(const NDArray<T> *row, NDArray<T>* target) const;
/**
* divide all rows of this array on given row vector, store result in target
* row - row vector to divide on
* target - where to store result
*/
void divRowVector(const NDArray<T> *row, NDArray<T>* target) const;
/**
* add given column vector to all columns of this array, store result in target
* column - column vector to add
* target - where to store result
*/
void addColumnVector(const NDArray<T> *column, NDArray<T>* target) const;
/**
* add given column vector to all columns of this array, this array becomes affected (in-place operation)
* column - column vector to add
*/
void addiColumnVector(const NDArray<T> *column);
/**
* multiply all columns of this array on given column vector, this array becomes affected (in-place operation)
* column - column vector to multiply on
*/
void muliColumnVector(const NDArray<T> *column);
/**
* returns number of bytes used by _buffer & _shapeInfo
*/
Nd4jLong memoryFootprint();
/**
* these methods suited for FlatBuffers use
*/
std::vector<T> getBufferAsVector();
std::vector<Nd4jLong> getShapeAsVector();
std::vector<Nd4jLong> getShapeInfoAsVector();
std::vector<int64_t> getShapeInfoAsFlatVector();
/**
* set new order and shape in case of suitable array length (in-place operation)
* order - order to set
* shape - shape to set
*
* if there was permute applied before or there are weird strides, then new buffer is allocated for array
*/
bool reshapei(const char order, const std::initializer_list<Nd4jLong>& shape);
bool reshapei(const char order, const std::vector<Nd4jLong>& shape);
bool reshapei(const std::initializer_list<Nd4jLong>& shape);
bool reshapei(const std::vector<Nd4jLong>& shape);
/**
* creates new array with corresponding order and shape, new array will point on _buffer of this array
* order - order to set
* shape - shape to set
*
* if permute have been applied before or there are weird strides, then new buffer is allocated for new array
*/
NDArray<T>* reshape(const char order, const std::vector<Nd4jLong>& shape) const;
/**
* calculate strides and set given order
* order - order to set
*/
void updateStrides(const char order);
/**
* change an array by repeating it the number of times given by reps (in-place operation)
* repeats - contains numbers of repetitions
*/
void tilei(const std::vector<Nd4jLong>& repeats);
/**
* returns new array which is created by by repeating of this array the number of times given by reps
* repeats - contains numbers of repetitions
*/
NDArray<T> tile(const std::vector<Nd4jLong>& repeats) const;
/**
* change an array by repeating it the number of times given by reps (in-place operation)
* repeats - contains numbers of repetitions
* target - where to store result
*/
void tile(const std::vector<Nd4jLong>& repeats, NDArray<T>& target) const;
/**
* change an array by repeating it the number of times to acquire the new shape which is the same as target shape
* target - where to store result
*/
void tile(NDArray<T>& target) const;
/**
* returns an array which is result of broadcasting of this and other arrays
* other - input array
*/
NDArray<T>* broadcast(const NDArray<T>& other);
/**
* check whether array's rows (arg=0) or columns (arg=1) create orthogonal basis
* arg - 0 -> row, 1 -> column
*/
bool hasOrthonormalBasis(const int arg);
/**
* check whether array is identity matrix
*/
bool isIdentityMatrix();
/**
* check whether array is unitary matrix
*/
bool isUnitary();
/**
* reduces dimensions in this array relying on index operation OpName
* dimensions - vector of dimensions to reduce along
* extraArgs - extra parameters for operation
*/
template<typename OpName>
NDArray<T>* applyIndexReduce(const std::vector<int>& dimensions, const T *extraParams = nullptr) const;
/**
* reduces dimensions in array relying on index operation OpName
* target - where to store result
* dimensions - vector of dimensions to reduce along
* extraArgs - extra parameters for operation
*/
template<typename OpName>
void applyIndexReduce(const NDArray<T>* target, const std::vector<int>& dimensions, const T *extraParams = nullptr) const;
/**
* apply reduce3 operation OpName to this and other array, return result in new output array
* other - input array
* extraArgs - extra parameters for operation
*/
template<typename OpName>
NDArray<T>* applyReduce3(const NDArray<T>* other, const T* extraParams = nullptr) const;
/**
* apply reduce3 operation OpName to this and other array, return result in new output array
* other - input array
* dimensions - vector of dimensions to reduce along
* extraArgs - extra parameters for operation
*/
template<typename OpName>
NDArray<T>* applyAllReduce3(const NDArray<T>* other, const std::vector<int>& dimensions, const T* extraParams = nullptr) const;
/**
* apply reduce3 (exec) operation OpName to this and other array, return result in new output array
* other - input array
* dimensions - vector of dimensions to reduce along
* extraArgs - extra parameters for operation
*/
template<typename OpName>
NDArray<T>* applyReduce3(const NDArray<T>* other, const std::vector<int>& dimensions, const T* extraParams = nullptr) const;
/**
* returns variance along given dimensions
* biasCorrected - if true bias correction will be applied
* dimensions - vector of dimensions to calculate variance along
*/
template<typename OpName>
NDArray<T>* varianceAlongDimension(const bool biasCorrected, const std::vector<int>& dimensions) const;
template<typename OpName>
NDArray<T>* varianceAlongDimension(const bool biasCorrected, const std::initializer_list<int>& dimensions) const;
template<typename OpName>
void varianceAlongDimension(const NDArray<T>* target, const bool biasCorrected, const std::vector<int>& dimensions);
template<typename OpName>
void varianceAlongDimension(const NDArray<T>* target, const bool biasCorrected, const std::initializer_list<int>& dimensions);
/**
* operator returns sub-array with buffer pointing at this->_buffer with offset defined by given intervals
* idx - intervals of indexes which define the sub-arrays to point on
* keepUnitiesInShape - if false then eliminate unities from resulting array shape, for example {1,a,1,b} -> {a,b}
*/
NDArray<T> operator()(const Intervals& idx, bool keepUnitiesInShape = false) const;
/**
* operator returns sub-array with buffer pointing at this->_buffer with offset defined by given intervals
* idx - intervals of indexes which define the sub-arrays to point on, idx has form {dim0Start,dim0End, dim1Start,dim1End, ....} and length (2 * this->rankOf())
* when (dimStart == dimEnd) then whole range will be used for current dimension
* keepUnitiesInShape - if false then eliminate unities from resulting array shape, for example {1,a,1,b} -> {a,b}
*/
NDArray<T> operator()(const int* idx, bool keepUnitiesInShape = false) const;
/**
* addition operator: array + other
* other - input array to add
*/
NDArray<T> operator+(const NDArray<T>& other) const;
/**
* addition operator: array + scalar
* scalar - input scalar to add
*/
NDArray<T> operator+(const T scalar) const;
/**
* friend functions which implement addition operator: scalar + array
* scalar - input scalar to add
*/
friend NDArray<float> nd4j::operator+(const float scalar, const NDArray<float>& arr);
friend NDArray<float16> nd4j::operator+(const float16 scalar, const NDArray<float16>& arr);
friend NDArray<double> nd4j::operator+(const double scalar, const NDArray<double>& arr);
/**
* addition unary operator array += other
* other - input array to add
*/
void operator+=(const NDArray<T>& other);
/**
* subtraction unary operator array -= other
* other - input array to add
*/
void operator-=(const NDArray<T>& other);
void operator+=(const T other);
void operator-=(const T other);
/**
* subtraction operator: array - other
* other - input array to subtract
*/
NDArray<T> operator-(const NDArray<T>& other) const;
/**
* subtraction operator: array - scalar
* scalar - input scalar to subtract
*/
NDArray<T> operator-(const T& scalar) const;
/**
* negative operator, it changes sign of all array elements on opposite
*/
NDArray<T> operator-() const;
/**
* friend functions which implement subtraction operator: scalar - array
* scalar - input scalar to subtract
*/
friend NDArray<float> nd4j::operator-(const float scalar, const NDArray<float>& arr);
friend NDArray<float16> nd4j::operator-(const float16 scalar, const NDArray<float16>& arr);
friend NDArray<double> nd4j::operator-(const double scalar, const NDArray<double>& arr);
/**
* pairwise multiplication operator: array * other
* other - input array to multiply on
*/
NDArray<T> operator*(const NDArray<T>& other) const;
/**
* multiplication operator: array * scalar
* scalar - input scalar to multiply on
*/
NDArray<T> operator*(const T scalar) const;
/**
* pairwise multiplication unary operator array *= other
* other - input array to multiply on
*/
void operator*=(const NDArray<T>& other);
/**
* multiplication unary operator array *= scalar
* scalar - input scalar to multiply on
*/
void operator*=(const T scalar);
/**
* pairwise division operator: array / other
* other - input array to divide on
*/
NDArray<T> operator/(const NDArray<T>& other) const;
/**
* division operator: array / scalar
* scalar - input scalar to divide each array element on
*/
NDArray<T> operator/(const T scalar) const;
/**
* pairwise division unary operator: array /= other
* other - input array to divide on
*/
void operator/=(const NDArray<T>& other);
/**
* division unary operator: array /= scalar
* scalar - input scalar to divide on
*/
void operator/=(const T scalar);
/**
* friend function which implements mathematical multiplication of two arrays
* left - input array
* right - input array
*/
friend NDArray<T> mmul<>(const NDArray<T>& left, const NDArray<T>& right);
/**
* this method assigns elements of other array to the sub-array of this array defined by given intervals
* other - input array to assign elements from
* idx - intervals of indexes which define the sub-array
*/
void assign(const NDArray<T>& other, const Intervals& idx);
/**
* return vector containing _buffer as flat binary array
*/
std::vector<int8_t> asByteVector();
/**
* makes array to be identity matrix (not necessarily square), that is set all diagonal elements = 1, rest = 0
*/
void setIdentity();
/**
* swaps the contents of tow arrays,
* PLEASE NOTE: method doesn't take into account the shapes of arrays, shapes may be different except one condition: arrays lengths must be the same
*/
void swapUnsafe(NDArray<T>& other);
/**
* return vector with buffer which points on corresponding diagonal elements of array
* type - means of vector to be returned: column ('c') or row ('r')
*/
NDArray<T>* diagonal(const char type ) const;
/**
* fill matrix with given value starting from specified diagonal in given direction, works only with 2D matrix
*
* diag - diagonal starting from matrix is filled.
* diag = 0 corresponds to main diagonal,
* diag < 0 below main diagonal
* diag > 0 above main diagonal
* direction - in what direction to fill matrix. There are 2 possible directions:
* 'u' - fill up, mathematically this corresponds to lower triangular matrix
* 'l' - fill down, mathematically this corresponds to upper triangular matrix
*/
void setValueInDiagMatrix(const T& value, const int diag, const char direction);
/**
* change an array by repeating it the number of times in order to acquire new shape equal to the input shape
*
* shape - contains new shape to broadcast array to
* target - optional argument, if target != nullptr the resulting array will be placed it target, in opposite case tile operation is done in place
*/
void tileToShape(const std::vector<Nd4jLong>& shape, NDArray<T>* target = nullptr);
void tileToShape(const std::initializer_list<Nd4jLong>& shape, NDArray<T>* target = nullptr);
template <typename N>
NDArray<N>* asT();
/**
* calculates the trace of an array, that is sum of elements on main diagonal = sum array[i, i, i, ...]
*/
T getTrace() const;
/**
* default destructor
*/
~NDArray() noexcept;
/**
* set _shapeInfo
*/
FORCEINLINE void setShapeInfo(Nd4jLong *shapeInfo);
/**
* set _buffer
*/
FORCEINLINE void setBuffer(T* buffer);
/**
* set _isBuffAlloc and _isShapeAlloc
*/
FORCEINLINE void triggerAllocationFlag(bool bufferAllocated, bool shapeAllocated);
/**
* returns the value of "dim" dimension
*/
Nd4jLong sizeAt(int dim) const;
/**
* returns order of array
*/
FORCEINLINE char ordering() const;
/**
* return _isView
*/
FORCEINLINE bool isView();
/**
* returns shape portion of shapeInfo
*/
FORCEINLINE Nd4jLong* shapeOf() const;
/**
* returns strides portion of shapeInfo
*/
FORCEINLINE Nd4jLong* stridesOf() const;
/**
* returns rank of array
*/
FORCEINLINE int rankOf() const;
/**
* returns length of array
*/
FORCEINLINE Nd4jLong lengthOf() const;
/**
* returns number of rows in array
*/
FORCEINLINE Nd4jLong rows() const;
/**
* returns number of columns in array
*/
FORCEINLINE Nd4jLong columns() const;
/**
* returns size of array elements type
*/
FORCEINLINE int sizeOfT() const;
/**
* returns element-wise-stride
*/
FORCEINLINE Nd4jLong ews() const;
// returns true if arrays have same shape
FORCEINLINE bool isSameShape(const NDArray<T> *other) const;
FORCEINLINE bool isSameShape(NDArray<T> &other) const;
FORCEINLINE bool isSameShape(const std::initializer_list<Nd4jLong>& shape) const;
FORCEINLINE bool isSameShape(const std::vector<Nd4jLong>& shape) const;
/**
* returns true if these two NDArrays have same rank, dimensions, strides, ews and order
*/
FORCEINLINE bool isSameShapeStrict(const NDArray<T> *other) const;
/**
* returns true if buffer && shapeInfo were defined (non nullptr)
*/
FORCEINLINE bool nonNull() const;
/**
* returns array element with given index from linear buffer
* i - element index in array
*/
FORCEINLINE T getScalar(const Nd4jLong i) const;
/**
* returns array element with given index, takes into account offset between elements (element-wise-stride)
* i - element index in array
*/
FORCEINLINE T getIndexedScalar(const Nd4jLong i) const;
/**
* returns element with given indexes from 2D array
* i - number of row
* j - number of column
*/
FORCEINLINE T getScalar(const Nd4jLong i, const Nd4jLong j) const;
/**
* returns element with given indexes from 3D array
* i - height
* j - width
* k - depth
*/
FORCEINLINE T getScalar(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) const;
/**
* assigns given scalar to array element by given index, takes into account offset between elements (element-wise-stride)
* i - element index in array
* value - scalar value to assign
*/
FORCEINLINE void putIndexedScalar(const Nd4jLong i, const T value);
/**
* assigns given scalar to array element by given index, regards array buffer as linear
* i - element index in array
* value - scalar value to assign
*/
FORCEINLINE void putScalar(const Nd4jLong i, const T value);
/**
* assigns given scalar to 2D array element by given indexes
* i - number of row
* j - number of row
* value - scalar value to assign
*/
FORCEINLINE void putScalar(const Nd4jLong i, const Nd4jLong j, const T value);
/**
* assigns given scalar to 3D array element by given indexes
* i - height
* j - width
* k - depth
* value - scalar value to assign
*/
FORCEINLINE void putScalar(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k, const T value);
/**
* returns true if array is 2D
*/
FORCEINLINE bool isMatrix() const;
/**
* returns true if array is vector
*/
FORCEINLINE bool isVector() const;
/**
* returns true if array is column vector
*/
FORCEINLINE bool isColumnVector() const;
/**
* returns true if array is row vector
*/
FORCEINLINE bool isRowVector() const;
/**
* returns true if array is scalar
*/
FORCEINLINE bool isScalar() const;
/**
* inline accessing operator for matrix, i - absolute index
*/
FORCEINLINE T operator()(const Nd4jLong i) const;
/**
* inline modifying operator for matrix, i - absolute index
*/
FORCEINLINE T& operator()(const Nd4jLong i);
/**
* inline accessing operator for 2D array, i - row, j - column
*/
FORCEINLINE T operator()(const Nd4jLong i, const Nd4jLong j) const;
/**
* inline modifying operator for 2D array, i - row, j - column
*/
FORCEINLINE T& operator()(const Nd4jLong i, const Nd4jLong j);
/**
* inline accessing operator for 3D array, i - height, j - width, k - depth
*/
FORCEINLINE T operator()(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) const;
/**
* inline modifying operator for 3D array, i - height, j - width, k - depth
*/
FORCEINLINE T& operator()(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k);
/**
* inline modifying operator for 4D array, i - height, j - width, k - depth
*/
FORCEINLINE T& operator()(const Nd4jLong t, const Nd4jLong u, const Nd4jLong v, const Nd4jLong w);
/**
* inline accessing operator for 4D array, i - height, j - width, k - depth
*/
FORCEINLINE T operator()(const Nd4jLong t, const Nd4jLong u, const Nd4jLong v, const Nd4jLong w) const;
template <typename T2>
FORCEINLINE std::vector<T2> asVectorT();
FORCEINLINE bool isAttached();
NDArray<T>* detach();
};
//////////////////////////////////////////////////////////////////////////
///// IMLEMENTATION OF INLINE METHODS /////
//////////////////////////////////////////////////////////////////////////
template <typename T>
template <typename T2>
std::vector<T2> NDArray<T>::asVectorT() {
std::vector<T2> result(this->lengthOf());
#pragma omp parallel for simd
for (int e = 0; e < this->lengthOf(); e++)
result[e] = (T2) this->getIndexedScalar(e);
return result;
}
template<typename T>
bool NDArray<T>::isAttached() {
return this->_workspace != nullptr;
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void NDArray<T>::setShapeInfo(Nd4jLong *shapeInfo) {
if(_isShapeAlloc && _workspace == nullptr)
delete []_shapeInfo;
_shapeInfo = shapeInfo;
_isShapeAlloc = false;
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void NDArray<T>::setBuffer(T* buffer) {
if(_isBuffAlloc && _workspace == nullptr)
delete []_buffer;
_buffer = buffer;
_isBuffAlloc = false;
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void NDArray<T>::triggerAllocationFlag(bool bufferAllocated, bool shapeAllocated) {
_isBuffAlloc = bufferAllocated;
_isShapeAlloc = shapeAllocated;
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
char NDArray<T>::ordering() const {
return shape::order(_shapeInfo);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
bool NDArray<T>::isView() {
return _isView;
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
Nd4jLong* NDArray<T>::shapeOf() const {
return shape::shapeOf(_shapeInfo);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
Nd4jLong* NDArray<T>::stridesOf() const {
return shape::stride(_shapeInfo);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
int NDArray<T>::rankOf() const {
return shape::rank(_shapeInfo);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
Nd4jLong NDArray<T>::lengthOf() const {
return shape::length(_shapeInfo);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
Nd4jLong NDArray<T>::rows() const {
return shapeOf()[0];
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
Nd4jLong NDArray<T>::columns() const {
return shapeOf()[1];
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
int NDArray<T>::sizeOfT() const {
return sizeof(T);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
Nd4jLong NDArray<T>::ews() const {
return shape::elementWiseStride(_shapeInfo);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
bool NDArray<T>::nonNull() const {
return this->_buffer != nullptr && this->_shapeInfo != nullptr;
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
bool NDArray<T>::isMatrix() const {
return shape::isMatrix(this->_shapeInfo);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
bool NDArray<T>::isVector() const {
return !isScalar() && shape::isVector(this->_shapeInfo);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
bool NDArray<T>::isColumnVector() const {
return !isScalar() && shape::isColumnVector(this->_shapeInfo);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
bool NDArray<T>::isRowVector() const {
// 1D edge case
if (shape::rank(this->_shapeInfo) == 1)
return true;
return !isScalar() && shape::isRowVector(this->_shapeInfo);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
bool NDArray<T>::isScalar() const {
return shape::isScalar(this->_shapeInfo);
}
// accessing operator for matrix, i - absolute index
template<typename T>
T NDArray<T>::operator()(const Nd4jLong i) const {
if (i >= shape::length(_shapeInfo))
throw std::invalid_argument("NDArray::operator(i): dinput index is out of array length !");
auto ews = shape::elementWiseStride(_shapeInfo);
char order = ordering();
if(ews == 1 && order == 'c')
return _buffer[i];
else if(ews > 1 && order == 'c')
return _buffer[i*ews];
else {
Nd4jLong idx[MAX_RANK];
shape::ind2subC(rankOf(), shapeOf(), i, idx);
Nd4jLong offset = shape::getOffset(0, shapeOf(), stridesOf(), idx, rankOf());
return _buffer[offset];
}
}
//////////////////////////////////////////////////////////////////////////
// modifying operator for matrix, i - absolute index
template<typename T>
T& NDArray<T>::operator()(const Nd4jLong i) {
if (i >= shape::length(_shapeInfo))
throw std::invalid_argument("NDArray::operator(i): input index is out of array length !");
auto ews = shape::elementWiseStride(_shapeInfo);
auto order = ordering();
if(ews == 1 && order == 'c')
return _buffer[i];
else if(ews > 1 && order == 'c')
return _buffer[i*ews];
else {
Nd4jLong idx[MAX_RANK];
shape::ind2subC(rankOf(), shapeOf(), i, idx);
auto offset = shape::getOffset(0, shapeOf(), stridesOf(), idx, rankOf());
return _buffer[offset];
}
}
//////////////////////////////////////////////////////////////////////////
// accessing operator for 2D matrix, i - row, j - column
template<typename T>
T NDArray<T>::operator()(const Nd4jLong i, const Nd4jLong j) const {
if (rankOf() != 2 || i >= shapeOf()[0] || j >= shapeOf()[1])
throw std::invalid_argument("NDArray::operator(i,j): one of input indexes is out of array length or rank!=2 !");
Nd4jLong coords[2] = {i, j};
auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf());
return _buffer[xOffset];
}
//////////////////////////////////////////////////////////////////////////
// modifying operator for 2D matrix, i - row, j - column
template<typename T>
T& NDArray<T>::operator()(const Nd4jLong i, const Nd4jLong j) {
if (rankOf() != 2 || i >= shapeOf()[0] || j >= shapeOf()[1])
throw std::invalid_argument("NDArray::operator(i,j): one of input indexes is out of array length or rank!=2 !");
Nd4jLong coords[2] = {i, j};
auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf());
return _buffer[xOffset];
}
//////////////////////////////////////////////////////////////////////////
// accessing operator for 3D array, i - row, j - column
template<typename T>
T NDArray<T>::operator()(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) const {
if (rankOf() != 3 || i >= shapeOf()[0] || j >= shapeOf()[1] || j >= shapeOf()[2])
throw std::invalid_argument("NDArray::operator(i,j,k): one of input indexes is out of array length or rank!=3 !");
Nd4jLong coords[3] = {i, j, k};
auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf());
return _buffer[xOffset];
}
//////////////////////////////////////////////////////////////////////////
// modifying operator for 3D array
template<typename T>
T& NDArray<T>::operator()(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) {
if (rankOf() != 3 || i >= shapeOf()[0] || j >= shapeOf()[1] || k >= shapeOf()[2])
throw std::invalid_argument("NDArray::operator(i,j,k): one of input indexes is out of array length or rank!=3 !");
Nd4jLong coords[3] = {i, j, k};
auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf());
return _buffer[xOffset];
}
template<typename T>
T NDArray<T>::operator()(const Nd4jLong t, const Nd4jLong u, const Nd4jLong v, const Nd4jLong w) const {
if (rankOf() != 4 || t >= shapeOf()[0] || u >= shapeOf()[1] || v >= shapeOf()[2] || w >= shapeOf()[3])
throw std::invalid_argument("NDArray::operator(t,u,v,w): one of input indexes is out of array length or rank!=4 !");
Nd4jLong coords[4] = {t, u, v, w};
auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf());
return _buffer[xOffset];
}
template<typename T>
T& NDArray<T>::operator()(const Nd4jLong t, const Nd4jLong u, const Nd4jLong v, const Nd4jLong w) {
if (rankOf() != 4 || t >= shapeOf()[0] || u >= shapeOf()[1] || v >= shapeOf()[2] || w >= shapeOf()[3])
throw std::invalid_argument("NDArray::operator(t,u,v,w): one of input indexes is out of array length or rank!=4 !");
Nd4jLong coords[4] = {t, u, v, w};
auto xOffset = shape::getOffset(0, shapeOf(), stridesOf(), coords, rankOf());
return _buffer[xOffset];
}
//////////////////////////////////////////////////////////////////////////
// Return value from linear buffer
template<typename T>
T NDArray<T>::getScalar(const Nd4jLong i) const
{ return (*this)(i); }
//////////////////////////////////////////////////////////////////////////
template<typename T>
T NDArray<T>::getIndexedScalar(const Nd4jLong i) const {
return (*this)(i);
}
//////////////////////////////////////////////////////////////////////////
// Returns value from 2D matrix by coordinates/indexes
template<typename T>
T NDArray<T>::getScalar(const Nd4jLong i, const Nd4jLong j) const
{ return (*this)(i, j); }
//////////////////////////////////////////////////////////////////////////
// returns value from 3D tensor by coordinates
template<typename T>
T NDArray<T>::getScalar(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k) const
{ return (*this)(i, j, k); }
//////////////////////////////////////////////////////////////////////////
template<typename T>
void NDArray<T>::putIndexedScalar(const Nd4jLong i, const T value)
{ (*this)(i) = value; }
//////////////////////////////////////////////////////////////////////////
// This method sets value in linear buffer to position i
template<typename T>
void NDArray<T>::putScalar(const Nd4jLong i, const T value)
{ (*this)(i) = value; }
//////////////////////////////////////////////////////////////////////////
// This method sets value in 2D matrix to position i, j
template<typename T>
void NDArray<T>::putScalar(const Nd4jLong i, const Nd4jLong j, const T value)
{ (*this)(i,j) = value; }
//////////////////////////////////////////////////////////////////////////
// This method sets value in 3D matrix to position i,j,k
template<typename T>
void NDArray<T>::putScalar(const Nd4jLong i, const Nd4jLong j, const Nd4jLong k, const T value)
{ (*this)(i,j,k) = value; }
//////////////////////////////////////////////////////////////////////////
template<typename T>
Nd4jLong NDArray<T>::memoryFootprint() {
Nd4jLong size = this->lengthOf() * this->sizeOfT();
size += shape::shapeInfoByteLength(this->rankOf());
return size;
}
//////////////////////////////////////////////////////////////////////////
// returns true if these two NDArrays have same shape
// still the definition of inline function must be in header file
template<typename T>
bool NDArray<T>::isSameShape(const std::vector<Nd4jLong>& other) const{
if (this->rankOf() != (int) other.size())
return false;
for (int e = 0; e < this->rankOf(); e++) {
if (this->shapeOf()[e] != other.at(e) && other.at(e) != -1)
return false;
}
return true;
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
bool NDArray<T>::isSameShape(const NDArray<T> *other) const {
return isSameShape(std::vector<Nd4jLong>(other->_shapeInfo+1, other->_shapeInfo+1+other->_shapeInfo[0]));
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
bool NDArray<T>::isSameShape(NDArray<T> &other) const {
return isSameShape(&other);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
bool NDArray<T>::isSameShape(const std::initializer_list<Nd4jLong>& other) const {
return isSameShape(std::vector<Nd4jLong>(other));
}
//////////////////////////////////////////////////////////////////////////
// returns true if these two NDArrays have same _shapeInfo
// still the definition of inline function must be in header file
template<typename T>
bool NDArray<T>::isSameShapeStrict(const NDArray<T> *other) const {
return shape::equalsStrict(_shapeInfo, other->_shapeInfo);
}
}
#endif
|
Polygon.c | #include "Polygon.h"
#include "utils.h"
void P_init(Polygon *p){
p->_nb_vertices=0;
p->_is_closed=FALSE;
p->_is_filled=FALSE;
p->_is_convex=TRUE;
}
// initialise un polygone (0 sommets)
void P_copy(Polygon *original, Polygon *copie){
int i;
copie->_nb_vertices=original->_nb_vertices;
copie->_is_closed=original->_is_closed;
copie->_is_filled=original->_is_filled;
copie->_is_convex=original->_is_convex;
#pragma omp parallel for
for (i = 0; i < P_MAX_VERTICES; i++) {
copie->_vertices[i]=(Vector)original->_vertices[i];
}
}
// original et copie sont deux polygones déjà alloués.
// Cette fonction copie les donnée
// depuis original vers copie de façon à ce que les
// deux polygones soient identiques.
void P_addVertex(Polygon *P, Vector pos){
int index;
bool is_filled=P->_is_filled;
index=P->_nb_vertices;
if (!is_filled) {
P->_vertices[index]=(Vector)pos;
P->_nb_vertices++;
}
if (P->_nb_vertices==P_MAX_VERTICES) {
P->_is_filled=TRUE;
}
}
// ajoute un sommet au polygone P. Ce nouveau sommet est situé en pos.
void P_removeLastVertex(Polygon *P){
P->_nb_vertices--;
if (P->_nb_vertices<0) {
P->_nb_vertices=0;
}
}
// enlève le dernier sommet de P
void P_draw(Polygon *P){
Vector* tab=P->_vertices;
int nb_vertices=P->_nb_vertices;
bool is_closed=P->_is_closed;
int i;
Vector current;
Vector current2;
if (P->_is_convex) {
//glColor rouge
glColor3d(1,0,0);
}
else{
//glColor bleu
glColor3d(0,0,1);
}
if(is_closed){
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_POLYGON);
for (i = 0; i < nb_vertices ; i++) {
current=(Vector) tab[i];
glVertex3f(current.x,current.y,current.z+325);
}
glEnd();
}
else{
if (nb_vertices>1) {
for (i = 0; i < nb_vertices-1; i++) {
current=(Vector) tab[i];
current2=(Vector) tab[i+1];
current.z++;
current2.z++;
drawLine(current,current2);
}
}
}
}
// dessine le polygone P
void P_print(Polygon *P, char *message){
Vector* tab=P->_vertices;
int nb_vertices=P->_nb_vertices;
Vector current;
int i;
for (i = 0; i < nb_vertices; i++) {
current=(Vector) tab[i];
printf("point %d : x %f, y %f, z %f \n",i,current.x,current.y,current.z);
}
}
// Affiche sur une console les données de P
// à des fins de debuggage.
Vector P_center(Polygon *P){
int i;
int x=0,y=0,z=0;
Vector* vertices=P->_vertices;
int nb_vertices=P->_nb_vertices;
for (i = 0; i <nb_vertices; i++) {
x+=vertices[i].x;
y+=vertices[i].y;
z+=vertices[i].z;
}
if(nb_vertices==0) //cas polygone vide
nb_vertices=1;
return V_new(x/nb_vertices,y/nb_vertices,z/nb_vertices);
}
int P_close(Polygon *P){
/*On ajoute un vertex egale au vertex du debut pour tester si le polygone est simple
* puis on l'enleve */
if (!P->_is_closed ){
P_addVertex(P,P->_vertices[0]);
if(P_simple(P)){
P->_is_convex=P_isConvex(P);
P_removeLastVertex(P);
P->_is_closed=TRUE;
return TRUE;
}
else{
P_removeLastVertex(P);
P->_is_closed=FALSE;
return FALSE;
}
}
return FALSE;
}
Vector P_normal(Polygon *P){
if (!P->_is_closed) {
return V_new(0,0,0);
}
Vector* vertices=P->_vertices;
Vector V1=V_substract(vertices[1],vertices[0]);
Vector V2=V_substract(vertices[2],vertices[1]);
Vector normal=V_cross(V1,V2);
Vector normal_unit=V_multiply((double)(1./V_length(normal)),normal);
return normal_unit;
}
void P_translate(Polygon *P, Vector trans){
int i;
Vector* vertices=P->_vertices;
int nb_vertices=P->_nb_vertices;
#pragma omp parallel for
for (i = 0; i < nb_vertices; i++) {
vertices[i].x+=trans.x;
vertices[i].y+=trans.y;
vertices[i].z+=trans.z;
}
}
//Marche uniquement pour de s point avec z=0;
int P_isConvex(Polygon *P){
int i;
int nb_vertices=P->_nb_vertices;
int signe;
if (nb_vertices<3) {
return TRUE;
}
Vector* vertices=P->_vertices;
Vector V1;
Vector V2;
Vector crossProduct;
V1=V_substract(vertices[1],vertices[0]);
V2=V_substract(vertices[2],vertices[1]);
crossProduct=V_cross(V1,V2);
if(crossProduct.z>0)
signe=1;
else
signe=0;
for (i = 1; i < nb_vertices-2; i++) {
V1=V_substract(vertices[i+1],vertices[i]);
V2=V_substract(vertices[i+2],vertices[i+1]);
crossProduct=V_cross(V1,V2);
if(!((crossProduct.z>0 && signe==1) || (crossProduct.z<0 && signe==0)))
return FALSE;
}
if(P->_is_closed){
V1=V_substract(vertices[nb_vertices-1],vertices[nb_vertices-2]);
V2=V_substract(vertices[0],vertices[nb_vertices-1]);
crossProduct=V_cross(V1,V2);
if(!((crossProduct.z>0 && signe==1) || (crossProduct.z<0 && signe==0)))
return FALSE;
}
return TRUE;
}
int P_simple(Polygon *P){
Vector* vertices=P->_vertices;
int nb_vertices=P->_nb_vertices;
Vector last_vertex=vertices[nb_vertices-1];
Vector before_last_vertex=vertices[nb_vertices-2];
int i;
/*Un polygone est toujours simple avec n sommet n < 3*/
if (nb_vertices<3) {
return TRUE;
}
/*On verifie que le dernier segment du polygone coupe un des segment precedent*/
for (i = 0; i < nb_vertices-2; i++) {
if (V_segmentsIntersect(last_vertex,before_last_vertex,vertices[i],vertices[i+1])) {
return FALSE;
}
}
return TRUE;
}
void drawRepereTest(Vector x,Vector y, Vector z,Vector center,int mod){
glColor3d(1,0+mod,0);
glBegin(GL_LINES);
glVertex3d(center.x,center.y,325+center.z);
glVertex3d(center.x+10*x.x,center.y-10*x.y,325+center.z+10*x.z);
glEnd();
glColor3d(0,1,0+mod);
glBegin(GL_LINES);
glVertex3d(center.x,center.y,325+center.z);
glVertex3d(center.x+10*y.x,center.y-10*y.y,325+center.z+10*y.z);
glEnd();
glColor3d(0+mod,0,1);
glBegin(GL_LINES);
glVertex3d(center.x,center.y,325+center.z);
glVertex3d(center.x+10*z.x,center.y-10*z.y,325+center.z+10*z.z);
glEnd();
}
//transform un vecteur de A dans B
Vector transform(Vector Ax,Vector Ay,Vector Az,Vector Bx,Vector By,Vector Bz,Vector P){
double newX,newY,newZ;
newX=V_dot(Bx,Ax)*P.x+V_dot(Bx,Ay)*P.y+V_dot(Bx,Az)*P.z;
newY=V_dot(By,Ax)*P.x+V_dot(By,Ay)*P.y+V_dot(By,Az)*P.z;
newZ=V_dot(Bz,Ax)*P.x+V_dot(Bz,Ay)*P.y+V_dot(Bz,Az)*P.z;
return V_new(newX,newY,newZ);
}
void P_rotate(Vector a,Vector b,Vector center,Polygon* P){
int i;
int nb_vertices=P->_nb_vertices;
Vector* vertices=P->_vertices;
b=V_unit(b);
Vector P1;
//repere perlin
Vector bx,by;
V_uxUyFromUz(b,&bx,&by);
//repere normal
Vector ax,ay;
V_uxUyFromUz(a,&ax,&ay);
#pragma omp parallel for
for (i = 0; i <nb_vertices; i++) {
vertices[i]=V_translate(vertices[i],center,1);
P1=V_new(V_decompose(V_substract(vertices[i],center),bx),
V_decompose(V_substract(vertices[i],center),by),
V_decompose(V_substract(vertices[i],center),b));
vertices[i]=V_recompose(P1.x,P1.y,P1.z,ax,ay,a);
vertices[i]=V_translate(vertices[i],center,-1);
}
}
|
GB_binop__lt_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__lt_uint16)
// A.*B function (eWiseMult): GB (_AemultB_08__lt_uint16)
// A.*B function (eWiseMult): GB (_AemultB_02__lt_uint16)
// A.*B function (eWiseMult): GB (_AemultB_04__lt_uint16)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__lt_uint16)
// A*D function (colscale): GB (_AxD__lt_uint16)
// D*A function (rowscale): GB (_DxB__lt_uint16)
// C+=B function (dense accum): GB (_Cdense_accumB__lt_uint16)
// C+=b function (dense accum): GB (_Cdense_accumb__lt_uint16)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lt_uint16)
// C=scalar+B GB (_bind1st__lt_uint16)
// C=scalar+B' GB (_bind1st_tran__lt_uint16)
// C=A+scalar GB (_bind2nd__lt_uint16)
// C=A'+scalar GB (_bind2nd_tran__lt_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_LT || GxB_NO_UINT16 || GxB_NO_LT_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__lt_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__lt_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__lt_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__lt_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__lt_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__lt_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__lt_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__lt_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__lt_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__lt_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__lt_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__lt_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__lt_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__lt_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
|
GB_unaryop__identity_int16_int16.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__identity_int16_int16
// op(A') function: GB_tran__identity_int16_int16
// C type: int16_t
// A type: int16_t
// cast: int16_t cij = (int16_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
int16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, x) \
int16_t z = (int16_t) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__identity_int16_int16
(
int16_t *restrict Cx,
const int16_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__identity_int16_int16
(
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
|
test_omp.c | #include <nautilus/nautilus.h>
#include <nautilus/shell.h>
#include <rt/omp/omp.h>
#define N 4
volatile float a[N];
volatile float b[N];
volatile float c[N];
static int omp_simple()
{
int i;
for (i=0;i<N;i++) {
a[i] = i;
b[i] = i;
}
#pragma omp parallel
nk_vc_printf("I am thread %d (%d total)\n",omp_get_thread_num(),omp_get_num_threads());
#pragma omp parallel for
for (i=0;i<N;i++) {
c[i] = a[i] * b[i];
}
for (i=0;i<N;i++) {
nk_vc_printf("a[%d]=%d b[%d]=%d c[%d]=%d\n",i,(int)a[i],i,(int)b[i],i,(int)c[i]);
}
return 0;
}
static void report_num_threads(int level)
{
#pragma omp single
{
nk_vc_printf("Level %d: number of threads in the team - %d\n",
level, omp_get_num_threads());
}
}
static int
omp_nested (void)
{
omp_set_dynamic(0);
#pragma omp parallel num_threads(2)
{
report_num_threads(1);
#pragma omp parallel num_threads(2)
{
report_num_threads(2);
#pragma omp parallel num_threads(2)
{
report_num_threads(3);
}
}
}
return(0);
}
int
test_omp (void)
{
nk_omp_thread_init();
nk_vc_printf("Starting simple test\n");
omp_simple();
// goto out;
nk_vc_printf("Starting nested test\n");
omp_nested();
//out:
nk_vc_printf("OMP test finished\n");
nk_omp_thread_deinit();
return 0;
}
static int
handle_omp (char * buf, void * priv)
{
test_omp();
return 0;
}
static struct shell_cmd_impl omp_impl = {
.cmd = "omp",
.help_str = "omp",
.handler = handle_omp,
};
nk_register_shell_cmd(omp_impl);
|
density.h | // Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess
// 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.
/** \file density.h
*
* \brief Contains definition and partial implementation of sirius::Density class.
*/
#ifndef __DENSITY_H__
#define __DENSITY_H__
#include "periodic_function.h"
#include "k_point_set.h"
#include "simulation_context.h"
#ifdef __GPU
extern "C" void generate_dm_pw_gpu(int num_atoms__,
int num_gvec_loc__,
int num_beta__,
double const* atom_pos__,
int const* gvec__,
double* phase_factors__,
double const* dm__,
double* dm_pw__,
int stream_id__);
extern "C" void sum_q_pw_dm_pw_gpu(int num_gvec_loc__,
int nbf__,
double const* q_pw__,
double const* dm_pw__,
double const* sym_weight__,
double_complex* rho_pw__,
int stream_id__);
extern "C" void update_density_rg_1_gpu(int size__,
cuDoubleComplex const* psi_rg__,
double wt__,
double* density_rg__);
#endif
namespace sirius
{
/// Generate charge density and magnetization from occupied spinor wave-functions.
/** Let's start from the definition of the complex density matrix:
* \f[
* \rho_{\sigma' \sigma}({\bf r}) =
* \sum_{j{\bf k}} n_{j{\bf k}} \Psi_{j{\bf k}}^{\sigma*}({\bf r}) \Psi_{j{\bf k}}^{\sigma'}({\bf r}) =
* \frac{1}{2} \left( \begin{array}{cc} \rho({\bf r})+m_z({\bf r}) &
* m_x({\bf r})-im_y({\bf r}) \\ m_x({\bf r})+im_y({\bf r}) & \rho({\bf r})-m_z({\bf r}) \end{array} \right)
* \f]
* We notice that the diagonal components of the density matrix are actually real and the off-diagonal components are
* expressed trough two independent functions \f$ m_x({\bf r}) \f$ and \f$ m_y({\bf r}) \f$. Having this in mind we
* will work with a slightly different object, namely a real density matrix, defined as a 1-, 2- or 4-dimensional
* (depending on the number of magnetic components) vector with the following elements:
* - \f$ [ \rho({\bf r}) ] \f$ in case of non-magnetic configuration
* - \f$ [ \rho_{\uparrow \uparrow}({\bf r}), \rho_{\downarrow \downarrow}({\bf r}) ] =
* [ \frac{\rho({\bf r})+m_z({\bf r})}{2}, \frac{\rho({\bf r})-m_z({\bf r})}{2} ] \f$ in case of collinear
* magnetic configuration
* - \f$ [ \rho_{\uparrow \uparrow}({\bf r}), \rho_{\downarrow \downarrow}({\bf r}),
* 2 \Re \rho_{\uparrow \downarrow}({\bf r}), -2 \Im \rho_{\uparrow \downarrow}({\bf r}) ] =
* [ \frac{\rho({\bf r})+m_z({\bf r})}{2}, \frac{\rho({\bf r})-m_z({\bf r})}{2},
* m_x({\bf r}), m_y({\bf r}) ] \f$ in the general case of non-collinear magnetic configuration
*
* At this point it is straightforward to compute the density and magnetization in the interstitial (see add_k_point_contribution_rg()).
* The muffin-tin part of the density and magnetization is obtained in a slighlty more complicated way. Recall the
* expansion of spinor wave-functions inside the muffin-tin \f$ \alpha \f$
* \f[
* \Psi_{j{\bf k}}^{\sigma}({\bf r}) = \sum_{\xi}^{N_{\xi}^{\alpha}} {S_{\xi}^{\sigma j {\bf k},\alpha}}
* f_{\ell_{\xi} \lambda_{\xi}}^{\alpha}(r)Y_{\ell_{\xi}m_{\xi}}(\hat {\bf r})
* \f]
* which we insert into expression for the complex density matrix:
* \f[
* \rho_{\sigma' \sigma}({\bf r}) = \sum_{j{\bf k}} n_{j{\bf k}} \sum_{\xi}^{N_{\xi}^{\alpha}}
* S_{\xi}^{\sigma j {\bf k},\alpha*} f_{\ell_{\xi} \lambda_{\xi}}^{\alpha}(r)
* Y_{\ell_{\xi}m_{\xi}}^{*}(\hat {\bf r}) \sum_{\xi'}^{N_{\xi'}^{\alpha}} S_{\xi'}^{\sigma' j{\bf k},\alpha}
* f_{\ell_{\xi'} \lambda_{\xi'}}^{\alpha}(r)Y_{\ell_{\xi'}m_{\xi'}}(\hat {\bf r})
* \f]
* First, we eliminate a sum over bands and k-points by forming an auxiliary density tensor:
* \f[
* D_{\xi \sigma, \xi' \sigma'}^{\alpha} = \sum_{j{\bf k}} n_{j{\bf k}} S_{\xi}^{\sigma j {\bf k},\alpha*}
* S_{\xi'}^{\sigma' j {\bf k},\alpha}
* \f]
* The expression for complex density matrix simplifies to:
* \f[
* \rho_{\sigma' \sigma}({\bf r}) = \sum_{\xi \xi'} D_{\xi \sigma, \xi' \sigma'}^{\alpha}
* f_{\ell_{\xi} \lambda_{\xi}}^{\alpha}(r)Y_{\ell_{\xi}m_{\xi}}^{*}(\hat {\bf r})
* f_{\ell_{\xi'} \lambda_{\xi'}}^{\alpha}(r)Y_{\ell_{\xi'}m_{\xi'}}(\hat {\bf r})
* \f]
* Now we can switch to the real density matrix and write its' expansion in real spherical harmonics. Let's take
* non-magnetic case as an example:
* \f[
* \rho({\bf r}) = \sum_{\xi \xi'} D_{\xi \xi'}^{\alpha}
* f_{\ell_{\xi} \lambda_{\xi}}^{\alpha}(r)Y_{\ell_{\xi}m_{\xi}}^{*}(\hat {\bf r})
* f_{\ell_{\xi'} \lambda_{\xi'}}^{\alpha}(r)Y_{\ell_{\xi'}m_{\xi'}}(\hat {\bf r}) =
* \sum_{\ell_3 m_3} \rho_{\ell_3 m_3}^{\alpha}(r) R_{\ell_3 m_3}(\hat {\bf r})
* \f]
* where
* \f[
* \rho_{\ell_3 m_3}^{\alpha}(r) = \sum_{\xi \xi'} D_{\xi \xi'}^{\alpha} f_{\ell_{\xi} \lambda_{\xi}}^{\alpha}(r)
* f_{\ell_{\xi'} \lambda_{\xi'}}^{\alpha}(r) \langle Y_{\ell_{\xi}m_{\xi}} | R_{\ell_3 m_3} | Y_{\ell_{\xi'}m_{\xi'}} \rangle
* \f]
* We are almost done. Now it is time to switch to the full index notation \f$ \xi \rightarrow \{ \ell \lambda m \} \f$
* and sum over \a m and \a m' indices:
* \f[
* \rho_{\ell_3 m_3}^{\alpha}(r) = \sum_{\ell \lambda, \ell' \lambda'} f_{\ell \lambda}^{\alpha}(r)
* f_{\ell' \lambda'}^{\alpha}(r) d_{\ell \lambda, \ell' \lambda', \ell_3 m_3}^{\alpha}
* \f]
* where
* \f[
* d_{\ell \lambda, \ell' \lambda', \ell_3 m_3}^{\alpha} =
* \sum_{mm'} D_{\ell \lambda m, \ell' \lambda' m'}^{\alpha}
* \langle Y_{\ell m} | R_{\ell_3 m_3} | Y_{\ell' m'} \rangle
* \f]
* This is our final answer: radial components of density and magnetization are expressed as a linear combination of
* quadratic forms in radial functions.
*
* \note density and potential are allocated as global function because it's easier to load and save them. */
class Density
{
private:
Simulation_context& ctx_;
Unit_cell& unit_cell_;
/// Density matrix of the system.
/** In case of full-potential, matrix is stored for local fraction of atoms.
* In case of pseudo-potential, full matrix for all atoms is stored. */
mdarray<double_complex, 4> density_matrix_;
struct paw_density_data_t
{
Atom *atom_{nullptr};
int ia{-1};
/// ae and ps local densities
mdarray<double, 2> ae_density_; // TODO: -> Spheric_function
mdarray<double, 2> ps_density_;
mdarray<double, 3> ae_magnetization_;
mdarray<double, 3> ps_magnetization_;
};
std::vector<paw_density_data_t> paw_density_data_;
/// Pointer to charge density.
/** In the case of full-potential calculation this is the full (valence + core) electron charge density.
* In the case of pseudopotential this is the valence charge density. */
Periodic_function<double>* rho_;
/// Density and magnetization on the coarse FFT mesh.
/** Coarse FFT grid is enough to generate density and magnetization from the wave-functions. The components
* of the <tt>rho_mag_coarse</tt> vector have the following order:
* \f$ \{\rho({\bf r}), m_z({\bf r}), m_x({\bf r}), m_y({\bf r}) \} \f$. */
std::array<std::unique_ptr<experimental::Smooth_periodic_function<double>>, 4> rho_mag_coarse_;
/// Pointer to pseudo core charge density
/** In the case of pseudopotential we need to know the non-linear core correction to the
* exchange-correlation energy which is introduced trough the pseudo core density:
* \f$ E_{xc}[\rho_{val} + \rho_{core}] \f$. The 'pseudo' reflects the fact that
* this density integrated does not reproduce the total number of core elctrons. */
Periodic_function<double>* rho_pseudo_core_{nullptr};
Periodic_function<double>* magnetization_[3];
/// Non-zero Gaunt coefficients.
std::unique_ptr<Gaunt_coefficients<double_complex>> gaunt_coefs_{nullptr};
/// Fast mapping between composite lm index and corresponding orbital quantum number.
std::vector<int> l_by_lm_;
std::unique_ptr<Mixer<double_complex>> high_freq_mixer_{nullptr};
std::unique_ptr<Mixer<double_complex>> low_freq_mixer_{nullptr};
std::unique_ptr<Mixer<double>> mixer_{nullptr};
std::vector<int> lf_gvec_;
std::vector<int> hf_gvec_;
/// Allocate PAW data.
void init_paw();
void generate_paw_atom_density(paw_density_data_t &pdd);
/// Initialize \rho_{ij} - density matrix, occupation on basis of beta-projectors (used for PAW).
void init_density_matrix_for_paw();
/// Symmetrize density matrix.
/** Initially, density matrix is obtained with summation over irreducible BZ:
* \f[
* \tilde n_{\ell \lambda m \sigma, \ell' \lambda' m' \sigma'}^{\alpha} =
* \sum_{j} \sum_{{\bf k}}^{IBZ} \langle Y_{\ell m} u_{\ell \lambda}^{\alpha}| \Psi_{j{\bf k}}^{\sigma} \rangle w_{\bf k} n_{j{\bf k}}
* \langle \Psi_{j{\bf k}}^{\sigma'} | u_{\ell' \lambda'}^{\alpha} Y_{\ell' m'} \rangle
* \f]
* In order to symmetrize it, the following operation is performed:
* \f[
* n_{\ell \lambda m \sigma, \ell' \lambda' m' \sigma'}^{\alpha} = \sum_{{\bf P}}
* \sum_{j} \sum_{\bf k}^{IBZ} \langle Y_{\ell m} u_{\ell \lambda}^{\alpha}| \Psi_{j{\bf P}{\bf k}}^{\sigma} \rangle w_{\bf k} n_{j{\bf k}}
* \langle \Psi_{j{\bf P}{\bf k}}^{\sigma'} | u_{\ell' \lambda'}^{\alpha} Y_{\ell' m'} \rangle
* \f]
* where \f$ {\bf P} \f$ is the space-group symmetry operation. The inner product between wave-function and
* local orbital is transformed as:
* \f[
* \langle \Psi_{j{\bf P}{\bf k}}^{\sigma} | u_{\ell \lambda}^{\alpha} Y_{\ell m} \rangle =
* \int \Psi_{j{\bf P}{\bf k}}^{\sigma *}({\bf r}) u_{\ell \lambda}^{\alpha}(r) Y_{\ell m}(\hat {\bf r}) dr =
* \int \Psi_{j{\bf k}}^{\sigma *}({\bf P}^{-1}{\bf r}) u_{\ell \lambda}^{\alpha}(r) Y_{\ell m}(\hat {\bf r}) dr =
* \int \Psi_{j{\bf k}}^{\sigma *}({\bf r}) u_{\ell \lambda}^{{\bf P}\alpha}(r) Y_{\ell m}({\bf P} \hat{\bf r}) dr
* \f]
* Under rotation the spherical harmonic is transformed as:
* \f[
* Y_{\ell m}({\bf P} \hat{\bf r}) = {\bf P}^{-1}Y_{\ell m}(\hat {\bf r}) = \sum_{m'} D_{m'm}^{\ell}({\bf P}^{-1}) Y_{\ell m'}(\hat {\bf r}) =
* \sum_{m'} D_{mm'}^{\ell}({\bf P}) Y_{\ell m'}(\hat {\bf r})
* \f]
* The inner-product integral is then rewritten as:
* \f[
* \langle \Psi_{j{\bf P}{\bf k}}^{\sigma} | u_{\ell \lambda}^{\alpha} Y_{\ell m} \rangle =
* \sum_{m'} D_{mm'}^{\ell}({\bf P}) \langle \Psi_{j{\bf k}}^{\sigma} | u_{\ell \lambda}^{{\bf P}\alpha} Y_{\ell m} \rangle
* \f]
* and the final expression for density matrix gets the following form:
* \f[
* n_{\ell \lambda m \sigma, \ell' \lambda' m' \sigma'}^{\alpha} = \sum_{{\bf P}}
* \sum_{j} \sum_{\bf k}^{IBZ} \sum_{m_1 m_2} D_{mm_1}^{\ell *}({\bf P}) D_{m'm_2}^{\ell'}({\bf P})
* \langle Y_{\ell m_1} u_{\ell \lambda}^{{\bf P} \alpha}|
* \Psi_{j{\bf k}}^{\sigma} \rangle w_{\bf k} n_{j{\bf k}} \langle \Psi_{j{\bf k}}^{\sigma'} |
* u_{\ell' \lambda'}^{{\bf P}\alpha} Y_{\ell' m_2} \rangle = \sum_{{\bf P}}
* \sum_{m_1 m_2} D_{mm_1}^{\ell *}({\bf P}) D_{m'm_2}^{\ell'}({\bf P})
* \tilde n_{\ell \lambda m_1 \sigma, \ell' \lambda' m_2 \sigma'}^{{\bf P}\alpha}
* \f]
*/
void symmetrize_density_matrix();
/// Reduce complex density matrix over magnetic quantum numbers
/** The following operation is performed:
* \f[
* d_{\ell \lambda, \ell' \lambda', \ell_3 m_3}^{\alpha} =
* \sum_{mm'} D_{\ell \lambda m, \ell' \lambda' m'}^{\alpha}
* \langle Y_{\ell m} | R_{\ell_3 m_3} | Y_{\ell' m'} \rangle
* \f]
*/
template <int num_mag_dims, typename T>
void reduce_density_matrix(Atom_type const& atom_type__,
int ia__,
mdarray<double_complex, 4> const& zdens__,
Gaunt_coefficients<T> const& gaunt_coeffs__,
mdarray<double, 3>& mt_density_matrix__)
{
mt_density_matrix__.zero();
#pragma omp parallel for default(shared)
for (int idxrf2 = 0; idxrf2 < atom_type__.mt_radial_basis_size(); idxrf2++) {
int l2 = atom_type__.indexr(idxrf2).l;
for (int idxrf1 = 0; idxrf1 <= idxrf2; idxrf1++) {
int offs = idxrf2 * (idxrf2 + 1) / 2 + idxrf1;
int l1 = atom_type__.indexr(idxrf1).l;
int xi2 = atom_type__.indexb().index_by_idxrf(idxrf2);
for (int lm2 = Utils::lm_by_l_m(l2, -l2); lm2 <= Utils::lm_by_l_m(l2, l2); lm2++, xi2++) {
int xi1 = atom_type__.indexb().index_by_idxrf(idxrf1);
for (int lm1 = Utils::lm_by_l_m(l1, -l1); lm1 <= Utils::lm_by_l_m(l1, l1); lm1++, xi1++) {
for (int k = 0; k < gaunt_coeffs__.num_gaunt(lm1, lm2); k++) {
int lm3 = gaunt_coeffs__.gaunt(lm1, lm2, k).lm3;
T gc = gaunt_coeffs__.gaunt(lm1, lm2, k).coef;
switch (num_mag_dims) {
case 3: {
mt_density_matrix__(lm3, offs, 2) += 2.0 * std::real(zdens__(xi1, xi2, 2, ia__) * gc);
mt_density_matrix__(lm3, offs, 3) -= 2.0 * std::imag(zdens__(xi1, xi2, 2, ia__) * gc);
}
case 1: {
mt_density_matrix__(lm3, offs, 1) += std::real(zdens__(xi1, xi2, 1, ia__) * gc);
}
case 0: {
mt_density_matrix__(lm3, offs, 0) += std::real(zdens__(xi1, xi2, 0, ia__) * gc);
}
}
}
}
}
}
}
}
/// Add k-point contribution to the auxiliary density matrix.
/** In case of full-potential LAPW complex density matrix has the following expression:
* \f[
* d_{\xi \sigma, \xi' \sigma'}^{\alpha} = \sum_{j{\bf k}} n_{j{\bf k}}
* S_{\xi}^{\sigma j {\bf k},\alpha*} S_{\xi'}^{\sigma' j {\bf k},\alpha}
* \f]
*
* where \f$ S_{\xi}^{\sigma j {\bf k},\alpha} \f$ are the expansion coefficients of
* spinor wave functions inside muffin-tin spheres.
*
* In case of LDA+U the occupation matrix is also computed. It has the following expression:
* \f[
* n_{\ell,mm'}^{\sigma \sigma'} = \sum_{i {\bf k}}^{occ} \int_{0}^{R_{MT}} r^2 dr
* \Psi_{\ell m}^{i{\bf k}\sigma *}({\bf r}) \Psi_{\ell m'}^{i{\bf k}\sigma'}({\bf r})
* \f]
*
* In case of ultrasoft pseudopotential the following density matrix has to be computed for each atom:
* \f[
* d_{\xi \xi'}^{\alpha} = \langle \beta_{\xi}^{\alpha} | \hat N | \beta_{\xi'}^{\alpha} \rangle =
* \sum_{j {\bf k}} \langle \beta_{\xi}^{\alpha} | \Psi_{j{\bf k}} \rangle n_{j{\bf k}}
* \langle \Psi_{j{\bf k}} | \beta_{\xi'}^{\alpha} \rangle
* \f]
* Here \f$ \hat N = \sum_{j{\bf k}} | \Psi_{j{\bf k}} \rangle n_{j{\bf k}} \langle \Psi_{j{\bf k}} | \f$ is
* the occupancy operator written in spectral representation. */
template <typename T>
inline void add_k_point_contribution_dm(K_point* kp__,
mdarray<double_complex, 4>& density_matrix__);
/// Add k-point contribution to the density and magnetization defined on the regular FFT grid.
inline void add_k_point_contribution_rg(K_point* kp__);
/// Generate valence density in the muffin-tins
void generate_valence_mt(K_point_set& ks);
/// Generate charge density of core states
void generate_core_charge_density()
{
PROFILE("sirius::Density::generate_core_charge_density");
for (int icloc = 0; icloc < unit_cell_.spl_num_atom_symmetry_classes().local_size(); icloc++) {
int ic = unit_cell_.spl_num_atom_symmetry_classes(icloc);
unit_cell_.atom_symmetry_class(ic).generate_core_charge_density(ctx_.core_relativity());
}
for (int ic = 0; ic < unit_cell_.num_atom_symmetry_classes(); ic++) {
int rank = unit_cell_.spl_num_atom_symmetry_classes().local_rank(ic);
unit_cell_.atom_symmetry_class(ic).sync_core_charge_density(ctx_.comm(), rank);
}
}
void generate_pseudo_core_charge_density()
{
PROFILE("sirius::Density::generate_pseudo_core_charge_density");
auto v = unit_cell_.make_periodic_function([this](int iat, double g)
{
return ctx_.radial_integrals().pseudo_core_radial_integral(iat, g);
},
ctx_.gvec());
ctx_.fft().transform<1>(ctx_.gvec().partition(), &v[ctx_.gvec().partition().gvec_offset_fft()]);
ctx_.fft().output(&rho_pseudo_core_->f_rg(0));
}
public:
/// Constructor
Density(Simulation_context& ctx__)
: ctx_(ctx__)
, unit_cell_(ctx_.unit_cell())
{
rho_ = new Periodic_function<double>(ctx_, ctx_.lmmax_rho(), 1);
for (int i = 0; i < ctx_.num_mag_dims() + 1; i++) {
rho_mag_coarse_[i] = std::unique_ptr<experimental::Smooth_periodic_function<double>>(new experimental::Smooth_periodic_function<double>(ctx_.fft_coarse(), ctx_.gvec_coarse()));
}
/* core density of the pseudopotential method */
if (!ctx_.full_potential()) {
rho_pseudo_core_ = new Periodic_function<double>(ctx_, 0, false);
rho_pseudo_core_->zero();
generate_pseudo_core_charge_density();
}
for (int i = 0; i < ctx_.num_mag_dims(); i++) {
magnetization_[i] = new Periodic_function<double>(ctx_, ctx_.lmmax_rho(), 1);
}
using gc_z = Gaunt_coefficients<double_complex>;
switch (ctx_.esm_type()) {
case electronic_structure_method_t::full_potential_lapwlo: {
gaunt_coefs_ = std::unique_ptr<gc_z>(new gc_z(ctx_.lmax_apw(), ctx_.lmax_rho(), ctx_.lmax_apw(), SHT::gaunt_hybrid));
break;
}
case electronic_structure_method_t::full_potential_pwlo: {
gaunt_coefs_ = std::unique_ptr<gc_z>(new gc_z(ctx_.lmax_pw(), ctx_.lmax_rho(), ctx_.lmax_pw(), SHT::gaunt_hybrid));
break;
}
default : {
break;
}
}
l_by_lm_ = Utils::l_by_lm(ctx_.lmax_rho());
density_matrix_ = mdarray<double_complex, 4>(unit_cell_.max_mt_basis_size(), unit_cell_.max_mt_basis_size(),
ctx_.num_mag_comp(), unit_cell_.num_atoms());
if (!ctx_.full_potential()) {
lf_gvec_ = std::vector<int>(ctx_.gvec_coarse().num_gvec());
std::vector<double> weights(ctx_.gvec_coarse().num_gvec() * (1 + ctx_.num_mag_dims()), 1.0);
for (size_t i = 0; i < density_matrix_.size(); i++) {
weights.push_back(0);
}
weights[0] = 0;
lf_gvec_[0] = 0;
for (int ig = 1; ig < ctx_.gvec_coarse().num_gvec(); ig++) {
auto G = ctx_.gvec_coarse().gvec(ig);
/* save index of low-frequency G-vector */
lf_gvec_[ig] = ctx_.gvec().index_by_gvec(G);
weights[ig] = fourpi * unit_cell_.omega() / std::pow(ctx_.gvec_coarse().gvec_len(ig), 2);
}
/* find high-frequency G-vectors */
for (int ig = 0; ig < ctx_.gvec().num_gvec(); ig++) {
if (ctx_.gvec().gvec_len(ig) > 2 * ctx_.gk_cutoff()) {
hf_gvec_.push_back(ig);
}
}
if (static_cast<int>(hf_gvec_.size()) != ctx_.gvec().num_gvec() - ctx_.gvec_coarse().num_gvec()) {
std::stringstream s;
s << "Wrong count of high-frequency G-vectors" << std::endl
<< "number of found high-frequency G-vectors: " << hf_gvec_.size() << std::endl
<< "expected number of high-frequency G-vectors: " << ctx_.gvec().num_gvec() - ctx_.gvec_coarse().num_gvec() << std::endl
<< "G-vector cutoff: " << ctx_.gk_cutoff();
TERMINATE(s);
}
if (hf_gvec_.size()) {
high_freq_mixer_ = Mixer_factory<double_complex>("linear",
hf_gvec_.size() * (1 + ctx_.num_mag_dims()),
ctx_.mixer_input_section(),
ctx_.comm());
}
low_freq_mixer_ = Mixer_factory<double_complex>(ctx_.mixer_input_section().type_,
lf_gvec_.size() * (1 + ctx_.num_mag_dims()) + density_matrix_.size(),
ctx_.mixer_input_section(),
ctx_.comm(),
weights);
}
if (ctx_.full_potential()) {
mixer_ = Mixer_factory<double>(ctx_.mixer_input_section().type_, size(), ctx_.mixer_input_section(), ctx_.comm());
}
}
/// Destructor
~Density()
{
delete rho_;
for (int j = 0; j < ctx_.num_mag_dims(); j++) {
delete magnetization_[j];
}
if (rho_pseudo_core_ != nullptr) {
delete rho_pseudo_core_;
}
}
/// Set pointers to muffin-tin and interstitial charge density arrays
void set_charge_density_ptr(double* rhomt, double* rhorg)
{
if (ctx_.full_potential() && rhomt) {
rho_->set_mt_ptr(rhomt);
}
if (rhorg) {
rho_->set_rg_ptr(rhorg);
}
}
/// Set pointers to muffin-tin and interstitial magnetization arrays
void set_magnetization_ptr(double* magmt, double* magir)
{
if (ctx_.num_mag_dims() == 0) {
return;
}
assert(ctx_.num_spins() == 2);
// set temporary array wrapper
mdarray<double, 4> magmt_tmp(magmt, ctx_.lmmax_rho(), unit_cell_.max_num_mt_points(),
unit_cell_.num_atoms(), ctx_.num_mag_dims());
mdarray<double, 2> magir_tmp(magir, ctx_.fft().size(), ctx_.num_mag_dims());
if (ctx_.num_mag_dims() == 1) {
/* z component is the first and only one */
if (magmt) {
magnetization_[0]->set_mt_ptr(&magmt_tmp(0, 0, 0, 0));
}
if (magir) {
magnetization_[0]->set_rg_ptr(&magir_tmp(0, 0));
}
}
if (ctx_.num_mag_dims() == 3) {
if (magmt) {
/* z component is the first */
magnetization_[0]->set_mt_ptr(&magmt_tmp(0, 0, 0, 2));
/* x component is the second */
magnetization_[1]->set_mt_ptr(&magmt_tmp(0, 0, 0, 0));
/* y component is the third */
magnetization_[2]->set_mt_ptr(&magmt_tmp(0, 0, 0, 1));
}
if (magir) {
/* z component is the first */
magnetization_[0]->set_rg_ptr(&magir_tmp(0, 2));
/* x component is the second */
magnetization_[1]->set_rg_ptr(&magir_tmp(0, 0));
/* y component is the third */
magnetization_[2]->set_rg_ptr(&magir_tmp(0, 1));
}
}
}
/// Zero density and magnetization
void zero()
{
rho_->zero();
for (int i = 0; i < ctx_.num_mag_dims(); i++) {
magnetization_[i]->zero();
}
}
/// Find the total leakage of the core states out of the muffin-tins
double core_leakage()
{
double sum = 0.0;
for (int ic = 0; ic < unit_cell_.num_atom_symmetry_classes(); ic++) {
sum += core_leakage(ic) * unit_cell_.atom_symmetry_class(ic).num_atoms();
}
return sum;
}
/// Return core leakage for a specific atom symmetry class
double core_leakage(int ic)
{
return unit_cell_.atom_symmetry_class(ic).core_leakage();
}
/// Generate initial charge density and magnetization
void initial_density();
void initial_density_pseudo();
void initial_density_full_pot();
/// Check total density for the correct number of electrons.
inline void check_num_electrons()
{
double nel{0};
if (ctx_.full_potential()) {
std::vector<double> nel_mt;
double nel_it;
nel = rho_->integrate(nel_mt, nel_it);
} else {
nel = rho_->f_pw(0).real() * unit_cell_.omega();
}
/* check the number of electrons */
if (std::abs(nel - unit_cell_.num_electrons()) > 1e-5) {
std::stringstream s;
s << "wrong number of electrons" << std::endl
<< " obtained value : " << nel << std::endl
<< " target value : " << unit_cell_.num_electrons() << std::endl
<< " difference : " << std::abs(nel - unit_cell_.num_electrons()) << std::endl;
if (ctx_.full_potential()) {
s << " total core leakage : " << core_leakage();
for (int ic = 0; ic < unit_cell_.num_atom_symmetry_classes(); ic++) {
s << std::endl << " atom class : " << ic << ", core leakage : " << core_leakage(ic);
}
}
WARNING(s);
}
}
/// Generate full charge density (valence + core) and magnetization from the wave functions.
/** This function calls generate_valence() and then in case of full-potential LAPW method adds a core density
* to get the full charge density of the system. */
inline void generate(K_point_set& ks__)
{
PROFILE("sirius::Density::generate");
generate_valence(ks__);
if (ctx_.full_potential()) {
/* find the core states */
generate_core_charge_density();
/* add core contribution */
for (int ialoc = 0; ialoc < (int)unit_cell_.spl_num_atoms().local_size(); ialoc++) {
int ia = unit_cell_.spl_num_atoms(ialoc);
for (int ir = 0; ir < unit_cell_.atom(ia).num_mt_points(); ir++) {
rho_->f_mt<index_domain_t::local>(0, ir, ialoc) += unit_cell_.atom(ia).symmetry_class().core_charge_density(ir) / y00;
}
}
/* synchronize muffin-tin part */
rho_->sync_mt();
for (int j = 0; j < ctx_.num_mag_dims(); j++) {
magnetization_[j]->sync_mt();
}
}
}
/// Generate valence charge density and magnetization from the wave functions.
/** The interstitial density is generated on the coarse FFT grid and then transformed to the PW domain.
* After symmetrization and mixing and before the generation of the XC potential density is transformted to the
* real-space domain and checked for the number of electrons. */
inline void generate_valence(K_point_set& ks__);
/// Add augmentation charge Q(r).
/** Restore valence density by adding the Q-operator constribution.
* The following term is added to the valence density, generated by the pseudo wave-functions:
* \f[
* \tilde \rho({\bf G}) = \sum_{\alpha} \sum_{\xi \xi'} d_{\xi \xi'}^{\alpha} Q_{\xi' \xi}^{\alpha}({\bf G})
* \f]
* Plane-wave coefficients of the Q-operator for a given atom \f$ \alpha \f$ can be obtained from the
* corresponding coefficients of the Q-operator for a given atom \a type A:
* \f[
* Q_{\xi' \xi}^{\alpha(A)}({\bf G}) = e^{-i{\bf G}\tau_{\alpha(A)}} Q_{\xi' \xi}^{A}({\bf G})
* \f]
* We use this property to split the sum over atoms into sum over atom types and inner sum over atoms of the
* same type:
* \f[
* \tilde \rho({\bf G}) = \sum_{A} \sum_{\xi \xi'} Q_{\xi' \xi}^{A}({\bf G}) \sum_{\alpha(A)}
* d_{\xi \xi'}^{\alpha(A)} e^{-i{\bf G}\tau_{\alpha(A)}} =
* \sum_{A} \sum_{\xi \xi'} Q_{\xi' \xi}^{A}({\bf G}) d_{\xi \xi'}^{A}({\bf G})
* \f]
* where
* \f[
* d_{\xi \xi'}^{A}({\bf G}) = \sum_{\alpha(A)} d_{\xi \xi'}^{\alpha(A)} e^{-i{\bf G}\tau_{\alpha(A)}}
* \f]
*/
void augment(K_point_set& ks__)
{
PROFILE("sirius::Density::augment");
/*check if we need to augment charge density and magnetization */
bool need_to_augment{false};
for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) {
need_to_augment |= unit_cell_.atom_type(iat).pp_desc().augment;
}
if (!need_to_augment) {
return;
}
/* collect density and magnetization into single array */
std::vector<Periodic_function<double>*> rho_vec(ctx_.num_mag_dims() + 1);
rho_vec[0] = rho_;
for (int j = 0; j < ctx_.num_mag_dims(); j++) {
rho_vec[1 + j] = magnetization_[j];
}
if (ctx_.control().print_checksum_) {
for (auto e: rho_vec) {
auto cs = e->checksum_pw();
DUMP("checksum(rho_vec_pw): %20.14f %20.14f", cs.real(), cs.imag());
}
}
mdarray<double_complex, 2> rho_aug(ctx_.gvec_count(), ctx_.num_mag_dims() + 1, ctx_.dual_memory_t());
switch (ctx_.processing_unit()) {
case CPU: {
generate_rho_aug<CPU>(rho_vec, rho_aug);
break;
}
case GPU: {
generate_rho_aug<GPU>(rho_vec, rho_aug);
break;
}
}
for (int iv = 0; iv < ctx_.num_mag_dims() + 1; iv++) {
#pragma omp parallel for
for (int igloc = 0; igloc < ctx_.gvec_count(); igloc++) {
int ig = ctx_.gvec_offset() + igloc;
rho_vec[iv]->f_pw(ig) += rho_aug(igloc, iv);
}
}
sddk::timer t5("sirius::Density::augment|mpi");
for (auto e: rho_vec) {
ctx_.comm().allgather(&e->f_pw(0), ctx_.gvec_offset(), ctx_.gvec_count());
if (ctx_.control().print_checksum_) {
auto cs = e->checksum_pw();
DUMP("checksum(rho_vec_pw): %20.14f %20.14f", cs.real(), cs.imag());
}
}
t5.stop();
}
template <device_t pu>
inline void generate_rho_aug(std::vector<Periodic_function<double>*> rho__,
mdarray<double_complex, 2>& rho_aug__);
/// Check density at MT boundary
void check_density_continuity_at_mt();
mdarray<double, 2> generate_rho_radial_integrals(int type__);
void generate_pw_coefs()
{
rho_->fft_transform(-1);
}
void save()
{
if (ctx_.comm().rank() == 0)
{
HDF5_tree fout(storage_file_name, false);
rho_->hdf5_write(fout["density"]);
for (int j = 0; j < ctx_.num_mag_dims(); j++)
magnetization_[j]->hdf5_write(fout["magnetization"].create_node(j));
}
ctx_.comm().barrier();
}
void load()
{
HDF5_tree fout(storage_file_name, false);
rho_->hdf5_read(fout["density"]);
for (int j = 0; j < ctx_.num_mag_dims(); j++)
magnetization_[j]->hdf5_read(fout["magnetization"][j]);
}
void save_to_xsf()
{
//== FILE* fout = fopen("unit_cell.xsf", "w");
//== fprintf(fout, "CRYSTAL\n");
//== fprintf(fout, "PRIMVEC\n");
//== auto& lv = unit_cell_.lattice_vectors();
//== for (int i = 0; i < 3; i++)
//== {
//== fprintf(fout, "%18.12f %18.12f %18.12f\n", lv(0, i), lv(1, i), lv(2, i));
//== }
//== fprintf(fout, "CONVVEC\n");
//== for (int i = 0; i < 3; i++)
//== {
//== fprintf(fout, "%18.12f %18.12f %18.12f\n", lv(0, i), lv(1, i), lv(2, i));
//== }
//== fprintf(fout, "PRIMCOORD\n");
//== fprintf(fout, "%i 1\n", unit_cell_.num_atoms());
//== for (int ia = 0; ia < unit_cell_.num_atoms(); ia++)
//== {
//== auto pos = unit_cell_.get_cartesian_coordinates(unit_cell_.atom(ia).position());
//== fprintf(fout, "%i %18.12f %18.12f %18.12f\n", unit_cell_.atom(ia).zn(), pos[0], pos[1], pos[2]);
//== }
//== fclose(fout);
}
void save_to_xdmf()
{
//== mdarray<double, 3> rho_grid(&rho_->f_it<global>(0), fft_->size(0), fft_->size(1), fft_->size(2));
//== mdarray<double, 4> pos_grid(3, fft_->size(0), fft_->size(1), fft_->size(2));
//== mdarray<double, 4> mag_grid(3, fft_->size(0), fft_->size(1), fft_->size(2));
//== mag_grid.zero();
//== // loop over 3D array (real space)
//== for (int j0 = 0; j0 < fft_->size(0); j0++)
//== {
//== for (int j1 = 0; j1 < fft_->size(1); j1++)
//== {
//== for (int j2 = 0; j2 < fft_->size(2); j2++)
//== {
//== int ir = static_cast<int>(j0 + j1 * fft_->size(0) + j2 * fft_->size(0) * fft_->size(1));
//== // get real space fractional coordinate
//== double frv[] = {double(j0) / fft_->size(0),
//== double(j1) / fft_->size(1),
//== double(j2) / fft_->size(2)};
//== vector3d<double> rv = ctx_.unit_cell()->get_cartesian_coordinates(vector3d<double>(frv));
//== for (int x = 0; x < 3; x++) pos_grid(x, j0, j1, j2) = rv[x];
//== if (ctx_.num_mag_dims() == 1) mag_grid(2, j0, j1, j2) = magnetization_[0]->f_it<global>(ir);
//== if (ctx_.num_mag_dims() == 3)
//== {
//== mag_grid(0, j0, j1, j2) = magnetization_[1]->f_it<global>(ir);
//== mag_grid(1, j0, j1, j2) = magnetization_[2]->f_it<global>(ir);
//== }
//== }
//== }
//== }
//== HDF5_tree h5_rho("rho.hdf5", true);
//== h5_rho.write("rho", rho_grid);
//== h5_rho.write("pos", pos_grid);
//== h5_rho.write("mag", mag_grid);
//== FILE* fout = fopen("rho.xdmf", "w");
//== //== fprintf(fout, "<?xml version=\"1.0\" ?>\n"
//== //== "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\">\n"
//== //== "<Xdmf>\n"
//== //== " <Domain Name=\"name1\">\n"
//== //== " <Grid Name=\"fft_fine_grid\" Collection=\"Unknown\">\n"
//== //== " <Topology TopologyType=\"3DSMesh\" NumberOfElements=\" %i %i %i \"/>\n"
//== //== " <Geometry GeometryType=\"XYZ\">\n"
//== //== " <DataItem Dimensions=\"%i %i %i 3\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">rho.hdf5:/pos</DataItem>\n"
//== //== " </Geometry>\n"
//== //== " <Attribute\n"
//== //== " AttributeType=\"Scalar\"\n"
//== //== " Center=\"Node\"\n"
//== //== " Name=\"rho\">\n"
//== //== " <DataItem\n"
//== //== " NumberType=\"Float\"\n"
//== //== " Precision=\"8\"\n"
//== //== " Dimensions=\"%i %i %i\"\n"
//== //== " Format=\"HDF\">\n"
//== //== " rho.hdf5:/rho\n"
//== //== " </DataItem>\n"
//== //== " </Attribute>\n"
//== //== " </Grid>\n"
//== //== " </Domain>\n"
//== //== "</Xdmf>\n", fft_->size(0), fft_->size(1), fft_->size(2), fft_->size(0), fft_->size(1), fft_->size(2), fft_->size(0), fft_->size(1), fft_->size(2));
//== fprintf(fout, "<?xml version=\"1.0\" ?>\n"
//== "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\">\n"
//== "<Xdmf>\n"
//== " <Domain Name=\"name1\">\n"
//== " <Grid Name=\"fft_fine_grid\" Collection=\"Unknown\">\n"
//== " <Topology TopologyType=\"3DSMesh\" NumberOfElements=\" %i %i %i \"/>\n"
//== " <Geometry GeometryType=\"XYZ\">\n"
//== " <DataItem Dimensions=\"%i %i %i 3\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">rho.hdf5:/pos</DataItem>\n"
//== " </Geometry>\n"
//== " <Attribute\n"
//== " AttributeType=\"Vector\"\n"
//== " Center=\"Node\"\n"
//== " Name=\"mag\">\n"
//== " <DataItem\n"
//== " NumberType=\"Float\"\n"
//== " Precision=\"8\"\n"
//== " Dimensions=\"%i %i %i 3\"\n"
//== " Format=\"HDF\">\n"
//== " rho.hdf5:/mag\n"
//== " </DataItem>\n"
//== " </Attribute>\n"
//== " </Grid>\n"
//== " </Domain>\n"
//== "</Xdmf>\n", fft_->size(0), fft_->size(1), fft_->size(2), fft_->size(0), fft_->size(1), fft_->size(2), fft_->size(0), fft_->size(1), fft_->size(2));
//== fclose(fout);
}
inline size_t size()
{
size_t s = rho_->size();
for (int i = 0; i < ctx_.num_mag_dims(); i++) s += magnetization_[i]->size();
return s;
}
Periodic_function<double>* rho()
{
return rho_;
}
Periodic_function<double>* rho_pseudo_core()
{
return rho_pseudo_core_;
}
Periodic_function<double>** magnetization()
{
return magnetization_;
}
Periodic_function<double>* magnetization(int i)
{
return magnetization_[i];
}
Spheric_function<spectral, double> const& density_mt(int ialoc) const
{
return rho_->f_mt(ialoc);
}
/// generate n_1 and \tilda{n}_1 in lm components
void generate_paw_loc_density();
mdarray<double, 2> const& ae_paw_atom_density(int spl_paw_ind) const
{
return paw_density_data_[spl_paw_ind].ae_density_;
}
mdarray<double, 2> const& ps_paw_atom_density(int spl_paw_ind) const
{
return paw_density_data_[spl_paw_ind].ps_density_;
}
mdarray<double, 3> const& ae_paw_atom_magn(int spl_paw_ind) const
{
return paw_density_data_[spl_paw_ind].ae_magnetization_;
}
mdarray<double, 3> const& ps_paw_atom_magn(int spl_paw_ind) const
{
return paw_density_data_[spl_paw_ind].ps_magnetization_;
}
void allocate()
{
rho_->allocate_mt(true);
for (int j = 0; j < ctx_.num_mag_dims(); j++) {
magnetization_[j]->allocate_mt(true);
}
}
void mixer_input()
{
if (mixer_ != nullptr) {
size_t n = rho_->pack(0, *mixer_);
for (int i = 0; i < ctx_.num_mag_dims(); i++) {
n += magnetization_[i]->pack(n, *mixer_);
}
} else {
int k = 0;
for (int ig: lf_gvec_) {
low_freq_mixer_->input(k++, rho_->f_pw(ig));
}
for (int j = 0; j < ctx_.num_mag_dims(); j++) {
for (int ig: lf_gvec_) {
low_freq_mixer_->input(k++, magnetization_[j]->f_pw(ig));
}
}
for (size_t i = 0; i < density_matrix_.size(); i++) {
low_freq_mixer_->input(k++, density_matrix_[i]);
}
if (high_freq_mixer_) {
k = 0;
for (int ig: hf_gvec_) {
high_freq_mixer_->input(k++, rho_->f_pw(ig));
}
for (int j = 0; j < ctx_.num_mag_dims(); j++) {
for (int ig: hf_gvec_) {
high_freq_mixer_->input(k++, magnetization_[j]->f_pw(ig));
}
}
}
}
}
void mixer_output()
{
if (mixer_ != nullptr) {
size_t n = rho_->unpack(mixer_->output_buffer());
for (int i = 0; i < ctx_.num_mag_dims(); i++) {
n += magnetization_[i]->unpack(&mixer_->output_buffer()[n]);
}
} else {
int k = 0;
for (int ig: lf_gvec_) {
rho_->f_pw(ig) = low_freq_mixer_->output_buffer(k++);
}
for (int j = 0; j < ctx_.num_mag_dims(); j++) {
for (int ig: lf_gvec_) {
magnetization_[j]->f_pw(ig) = low_freq_mixer_->output_buffer(k++);
}
}
for (size_t i = 0; i < density_matrix_.size(); i++) {
density_matrix_[i] = low_freq_mixer_->output_buffer(k++);
}
if (high_freq_mixer_) {
k = 0;
for (int ig: hf_gvec_) {
rho_->f_pw(ig) = high_freq_mixer_->output_buffer(k++);
}
for (int j = 0; j < ctx_.num_mag_dims(); j++) {
for (int ig: hf_gvec_) {
magnetization_[j]->f_pw(ig) = high_freq_mixer_->output_buffer(k++);
}
}
}
}
}
void mixer_init()
{
mixer_input();
if (mixer_ != nullptr) {
mixer_->initialize();
} else {
low_freq_mixer_->initialize();
if (high_freq_mixer_) {
high_freq_mixer_->initialize();
}
}
}
double mix()
{
double rms;
if (mixer_ != nullptr) {
STOP(); // TODO: redesign mixer
/* mix in real-space in case of FP-LAPW */
mixer_input();
rms = mixer_->mix();
mixer_output();
/* get rho(G) after mixing */
rho_->fft_transform(-1);
} else {
/* mix in G-space in case of PP */
mixer_input();
rms = low_freq_mixer_->mix();
if (high_freq_mixer_) {
rms += high_freq_mixer_->mix();
}
mixer_output();
}
return rms;
}
inline double dr2()
{
return low_freq_mixer_->rss();
}
mdarray<double_complex, 4> const& density_matrix() const
{
return density_matrix_;
}
inline void fft_transform(int direction__)
{
rho_->fft_transform(direction__);
for (int j = 0; j < ctx_.num_mag_dims(); j++) {
magnetization_[j]->fft_transform(direction__);
}
}
};
#include "Density/initial_density.hpp"
#include "Density/add_k_point_contribution_rg.hpp"
#include "Density/add_k_point_contribution_dm.hpp"
#include "Density/generate_valence.hpp"
#include "Density/generate_rho_aug.hpp"
#include "Density/symmetrize_density_matrix.hpp"
#include "Density/generate_valence_mt.hpp"
#include "Density/generate_rho_radial_integrals.hpp"
#include "Density/check_density_continuity_at_mt.hpp"
#include "Density/paw_density.hpp"
}
#endif // __DENSITY_H__
|
Index.h | // Index.h
#ifndef INDEX_H
#define INDEX_H
#include "_ug.h"
#include <nanoflann.hpp>
#include <tuple>
#include "Vec3.h"
#include "Direction.h"
#include "Picture.h"
#include "Projection.h"
#include "ProjectedStar.h"
#include "Quad.h"
#include "Pose.h"
#include "IndexEighth.h"
#include "Orientation.h"
namespace ugps
{
class Index
{
public:
Index(const vector<Vec3>& universe3D, const vector<Direction>& directions);
template <class star_t, starToVec2Fn<star_t> vec2>
Pose3 search(const Picture<star_t,vec2>& pic) const
{
return searchQuads(pic.calculateQuads());
}
private:
num_ug quadErrorRadius() const;
void buildTrees() const
{
#pragma omp parallel for
for(int i = 0; i < 8; i++)
{
orientedIndex[i].tree->buildIndex();
}
}
Oriented<IndexEighth> orientedIndex;
template<class star_t, starToVec2Fn<star_t> vec2>
vector<const ProjectionQuad*> nearestNeighbours(const Quad<star_t,vec2>& query, size_t n) const;
template<class star_t, starToVec2Fn<star_t> vec2>
vector<const ProjectionQuad*> radiusSearch(const Quad<star_t,vec2>& query, const num_ug& r) const;
template<class star_t, starToVec2Fn<star_t> vec2>
Pose3 searchQuads(const vector<unique_ptr<const Quad<star_t, vec2> > >& pictureQuads) const;
vector<unique_ptr<const Vec3> > uniqueStars;
vector<unique_ptr<const Projection> > uniqueProjections;
};
template<class star_t, starToVec2Fn<star_t> vec2>
vector<const ProjectionQuad*> Index::nearestNeighbours(const Quad<star_t, vec2>& query, size_t n) const
{
vector<size_t> ret_indexes(n);
vector<num_ug> out_dists_sqr(n);
nanoflann::KNNResultSet<num_ug> resultSet(n);
resultSet.init(&ret_indexes[0], &out_dists_sqr[0]);
num_ug queryPoint[4];
queryPoint[0] = query.q1;
queryPoint[1] = query.q2;
queryPoint[2] = query.q3;
queryPoint[3] = query.q4;
orientedIndex[query.orientation].tree->findNeighbors(resultSet,queryPoint,nanoflann::SearchParams());
vector<const ProjectionQuad*> returnQuads;
for(auto idx : ret_indexes)
{
returnQuads.push_back(orientedIndex[query.orientation].quads[idx].get());
}
return returnQuads;
}
template<class star_t, starToVec2Fn<star_t> vec2>
vector<const ProjectionQuad*> Index::radiusSearch(const Quad<star_t,vec2>& query, const num_ug& r) const
{
vector<pair<size_t,num_ug> > indices_dists;
nanoflann::RadiusResultSet<num_ug,size_t> resultSet(r,indices_dists);
num_ug queryPoint[4];
queryPoint[0] = query.q1;
queryPoint[1] = query.q2;
queryPoint[2] = query.q3;
queryPoint[3] = query.q4;
orientedIndex[query.orientation].tree->findNeighbors(resultSet,queryPoint,nanoflann::SearchParams());
vector<const ProjectionQuad*> returnQuads;
for(auto idx_dist : indices_dists)
{
returnQuads.push_back(orientedIndex[query.orientation].quads[idx_dist.first].get());
}
return returnQuads;
}
template<class star_t, starToVec2Fn<star_t> vec2>
Pose3 Index::searchQuads(const vector<unique_ptr<const Quad<star_t,vec2> > >& pictureQuads) const
{
vector<unique_ptr<const Pose2> > pose2s;
#pragma omp parallel for
for(auto q = pictureQuads.begin(); q < pictureQuads.end(); q++)
{
vector<const ProjectionQuad*> qms = nearestNeighbours(**q,1);//radiusSearch(**q,0.05);
for(auto qm : qms)
{
#pragma omp critical(addPose2)
{
pose2s.push_back(make_unique<const Pose2>(measure(*qm,**q)));
}
}
}
num_ug filterRadius = sqrt(4*M_PI/(num_ug)uniqueProjections.size());
vector<const Pose2*> pose2sfiltered;
for(auto pose2 = pose2s.begin(); pose2 < pose2s.end(); pose2++)
{
for(auto pose2n = pose2s.begin(); pose2n < pose2s.end(); pose2n++)
{
if (pose2 == pose2n) continue;
if (dist((*pose2)->dir,(*pose2n)->dir)<filterRadius)
{
pose2sfiltered.push_back(pose2->get());
//std::cout << (*pose2)->dir.theta << std::endl;
break;
}
}
}
//std::cout << pose2sfiltered.size() << "/" << pose2s.size() << std::endl;
Vec2 aLoc;
Vec2 aRollVec;
Vec3 aDirVec;
num_ug aScale;
for(auto pose2 : pose2sfiltered)
{
aLoc += pose2->loc;
aRollVec += Vec2(cos(pose2->roll), sin(pose2->roll));
aDirVec += pose2->dir.unit();
aScale += pose2->scale;
}
aLoc /= (num_ug)pose2sfiltered.size();
num_ug aRoll = aRollVec.angle();
Direction aDir = Direction(aDirVec);
aScale /= (num_ug)pose2sfiltered.size();
Pose2 aPose2(aLoc, aDir, aRoll, aScale);
return aPose2.pose3();
}
num_ug meanDist(const num_ug& D, const num_ug& N, const num_ug& k);
}
#endif
|
mapped_avg_pool.h | #ifndef MAPPED_AVG_POOL_H_
#define MAPPED_AVG_POOL_H_
#include <math.h>
#include <omp.h>
#include <torch/extension.h>
#include <limits>
#include "common/mapped_avg_pool.h"
#include "core/resample.h"
namespace spherical {
namespace cpu {
template <typename T>
void MappedAvgPool2D(const int num_kernels, torch::Tensor in_data,
torch::Tensor sample_map, // OH x OW x K x 2
const int channels, const int in_height,
const int in_width, const int out_height,
const int out_width, const int kernel_size,
const InterpolationType interpolation,
torch::Tensor out_data) {
const T *in_data_ptr = in_data.data_ptr<T>();
const T *sample_map_ptr = sample_map.data_ptr<T>();
T *out_data_ptr = out_data.data_ptr<T>();
int index;
#pragma omp parallel for shared(in_data_ptr, sample_map_ptr, \
out_data_ptr) private(index) schedule(static)
for (index = 0; index < num_kernels; index++) {
common::MappedAvgPool2D(index, in_data_ptr, sample_map_ptr, channels,
in_height, in_width, out_height, out_width,
kernel_size, interpolation, out_data_ptr);
}
}
template <typename T>
void MappedAvgUnpool2D(const int num_kernels, torch::Tensor grad_output,
torch::Tensor sample_map, const int channels,
const int orig_height, const int orig_width,
const int pooled_height, const int pooled_width,
const int kernel_size,
const InterpolationType interpolation,
torch::Tensor grad_input) {
const T *grad_output_ptr = grad_output.data_ptr<T>();
const T *sample_map_ptr = sample_map.data_ptr<T>();
T *grad_input_ptr = grad_input.data_ptr<T>();
int index;
#pragma omp parallel for shared(grad_output_ptr, sample_map_ptr, \
grad_input_ptr) private(index) \
schedule(static)
for (index = 0; index < num_kernels; index++) {
common::MappedAvgUnpool2D(index, grad_output_ptr, sample_map_ptr, channels,
orig_height, orig_width, pooled_height,
pooled_width, kernel_size, interpolation,
grad_input_ptr);
}
}
// -------------------------------------------------
// -------------------------------------------------
template <typename T>
void MappedAvgPool2DWeighted(const int num_kernels, torch::Tensor in_data,
torch::Tensor sample_map, // OH x OW x K x P x 2
torch::Tensor interp_weights, // OH x OW x K x P
const int channels, const int in_height,
const int in_width, const int out_height,
const int out_width, const int kernel_size,
const InterpolationType interpolation,
const int num_interp_pts,
torch::Tensor out_data) {
const T *in_data_ptr = in_data.data_ptr<T>();
const T *sample_map_ptr = sample_map.data_ptr<T>();
const T *interp_weights_ptr = interp_weights.data_ptr<T>();
T *out_data_ptr = out_data.data_ptr<T>();
int index;
#pragma omp parallel for shared(in_data_ptr, sample_map_ptr, \
interp_weights_ptr, \
out_data_ptr) private(index) schedule(static)
for (index = 0; index < num_kernels; index++) {
common::MappedAvgPool2DWeighted(
index, in_data_ptr, sample_map_ptr, interp_weights_ptr, channels,
in_height, in_width, out_height, out_width, kernel_size, interpolation,
num_interp_pts, out_data_ptr);
}
}
template <typename T>
void MappedAvgUnpool2DWeighted(
const int num_kernels, torch::Tensor grad_output, torch::Tensor sample_map,
torch::Tensor interp_weights, const int channels, const int orig_height,
const int orig_width, const int pooled_height, const int pooled_width,
const int kernel_size, const InterpolationType interpolation,
const int num_interp_pts, torch::Tensor grad_input) {
const T *grad_output_ptr = grad_output.data_ptr<T>();
const T *sample_map_ptr = sample_map.data_ptr<T>();
const T *interp_weights_ptr = interp_weights.data_ptr<T>();
T *grad_input_ptr = grad_input.data_ptr<T>();
int index;
#pragma omp parallel for shared( \
grad_output_ptr, sample_map_ptr, interp_weights_ptr, \
grad_input_ptr) private(index) schedule(static)
for (index = 0; index < num_kernels; index++) {
common::MappedAvgUnpool2DWeighted(
index, grad_output_ptr, sample_map_ptr, interp_weights_ptr, channels,
orig_height, orig_width, pooled_height, pooled_width, kernel_size,
interpolation, num_interp_pts, grad_input_ptr);
}
}
} // namespace cpu
} // namespace spherical
#endif |
elemwise_binary_scalar_op.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2016 by Contributors
* \file elemwise_binary_scalar_op.h
* \brief Function definition of elementwise binary scalar operators
*/
#ifndef MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_SCALAR_OP_H_
#define MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_SCALAR_OP_H_
#include <mxnet/operator_util.h>
#include <dmlc/strtonum.h>
#include <vector>
#include <utility>
#include <string>
#include "../mshadow_op.h"
#include "../elemwise_op_common.h"
#include "elemwise_unary_op.h"
namespace mxnet {
namespace op {
struct NumpyBinaryScalarParam : public dmlc::Parameter<NumpyBinaryScalarParam> {
double scalar;
bool is_int;
DMLC_DECLARE_PARAMETER(NumpyBinaryScalarParam) {
DMLC_DECLARE_FIELD(scalar)
.set_default(1)
.describe("Scalar input value");
DMLC_DECLARE_FIELD(is_int)
.set_default(true)
.describe("Indicate whether scalar input is int type");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream scalar_s, is_int_s;
scalar_s << scalar;
is_int_s << is_int;
(*dict)["scalar"] = scalar_s.str();
(*dict)["is_int"] = is_int_s.str();
}
};
inline bool NumpyBinaryScalarType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
const NumpyBinaryScalarParam& param = nnvm::get<NumpyBinaryScalarParam>(attrs.parsed);
bool scalar_is_int = param.is_int;
if (common::is_int(in_attrs->at(0)) && !scalar_is_int) {
TYPE_ASSIGN_CHECK(*out_attrs, 0, mshadow::kFloat64);
} else if (in_attrs->at(0) == mshadow::kBool) {
TYPE_ASSIGN_CHECK(*out_attrs, 0, scalar_is_int ? mshadow::kInt64 : mshadow::kFloat64);
} else {
TYPE_ASSIGN_CHECK(*out_attrs, 0, in_attrs->at(0));
TYPE_ASSIGN_CHECK(*in_attrs, 0, out_attrs->at(0));
}
return out_attrs->at(0) != -1;
}
class BinaryScalarOp : public UnaryOp {
/*! \brief Tensor operation against a scalar with a dense result */
template<typename OP, typename DType, typename IType>
static void ComputeExDenseResultRsp(mshadow::Stream<cpu> *stream,
const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &input,
const OpReqType req,
const NDArray &output) {
const NumpyBinaryScalarParam& param = nnvm::get<NumpyBinaryScalarParam>(attrs.parsed);
const double alpha = param.scalar;
CHECK_EQ(output.shape(), input.shape());
const int64_t row_count = output.shape()[0];
const int64_t items_per_row = output.shape().Size() / row_count;
const DType result_for_zero = OP::Map(DType(0), DType(alpha));
mshadow::Tensor<cpu, 1, DType> input_data = input.data().FlatTo1D<cpu, DType>(stream);
mshadow::Tensor<cpu, 1, DType> output_data = output.data().FlatTo1D<cpu, DType>(stream);
const int64_t sparse_row_count = input.aux_shape(rowsparse::kIdx).Size();
if (sparse_row_count != row_count) {
mshadow::Tensor<cpu, 1, IType> row_indexes = input.aux_data(
rowsparse::kIdx).FlatTo1D<cpu, IType>(stream);
int64_t input_iter = 0;
int64_t output_row = 0;
IType next_input_row = 0;
while (output_row < row_count) {
next_input_row = input_iter < sparse_row_count ? int64_t(row_indexes[input_iter])
: row_count;
// Split up into blocks of contiguous data and do those together
// Do contiguous dense blocks
const int64_t dense_block_count = next_input_row - output_row;
if (dense_block_count > 0) {
MXNET_ASSIGN_REQ_SWITCH(req, Req, {
mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::identity, Req>, cpu>::Launch(
stream,
items_per_row * dense_block_count,
output_data.dptr_ + items_per_row * output_row,
result_for_zero);
});
output_row += dense_block_count;
continue;
}
// Do contiguous sparse blocks
int64_t next_non_contiguous_sparse = input_iter;
while (next_non_contiguous_sparse < sparse_row_count - 1) {
if (row_indexes[next_non_contiguous_sparse + 1]
!= row_indexes[next_non_contiguous_sparse] + 1) {
break;
}
++next_non_contiguous_sparse;
}
const int64_t sparse_block_count = next_non_contiguous_sparse - input_iter + 1;
if (sparse_block_count > 0) {
MXNET_ASSIGN_REQ_SWITCH(req, Req, {
mxnet_op::Kernel<mxnet_op::op_with_req<OP, Req>, cpu>::Launch(
stream,
items_per_row * sparse_block_count,
&output_data.dptr_[items_per_row * output_row],
&input_data.dptr_[items_per_row * input_iter],
DType(alpha));
});
output_row += sparse_block_count;
input_iter += sparse_block_count;
continue;
}
}
} else {
// All rows exist (eventually we don't have to do complex
// things to call GPU kernels because we don't need to access row indices)
MXNET_ASSIGN_REQ_SWITCH(req, Req, {
mxnet_op::Kernel<mxnet_op::op_with_req<OP, Req>, cpu>::Launch(
stream,
items_per_row * row_count,
output_data.dptr_,
input_data.dptr_,
DType(alpha));
});
}
}
/*! \brief Tensor operation against a scalar with a dense result */
template<typename OP, typename DType, typename IType>
static void ComputeExDenseResultRsp(mshadow::Stream<gpu> *stream,
const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &input,
const OpReqType req,
const NDArray &output) {
LOG(FATAL) << "NOT IMPLEMENTED";
}
/*! \brief Tensor operation against a scalar with a dense result */
template<typename OP, typename DType, typename IType, typename CType>
static void ComputeExDenseResultCsr(mshadow::Stream<cpu> *stream,
const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &input,
const OpReqType req,
const NDArray &output) {
CHECK_EQ(output.shape(), input.shape());
const NumpyBinaryScalarParam& param = nnvm::get<NumpyBinaryScalarParam>(attrs.parsed);
const double alpha = param.scalar;
const DType dense_fill_val = OP::Map(DType(0), DType(alpha));
const TBlob column_indexes = input.aux_data(csr::kIdx);
const size_t item_count = column_indexes.Size();
// Pre-fill dense with 0-input/output value
FillDense<DType>(stream, output.shape().Size(), dense_fill_val,
req, output.data().dptr<DType>());
mshadow::Tensor<cpu, 2, DType> out = AsRowise2D<DType>(stream, output.data());
if (item_count) {
const DType *in = input.data().dptr<DType>();
const IType *column_indexes_ptr = column_indexes.dptr<IType>();
const auto row_count = static_cast<size_t>(input.shape()[0]);
const TBlob row_starts = input.aux_data(csr::kIndPtr);
const CType *row_starts_ptr = row_starts.dptr<CType>();
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(row_count); ++i) {
const bool last_row = i == static_cast<int>(row_count) - 1;
// Split up into blocks of contiguous data and do those together
const size_t row_item_start_iter = row_starts_ptr[i];
const size_t input_items_this_row = !last_row
? static_cast<size_t>(row_starts_ptr[i + 1])
- row_item_start_iter
: item_count - row_item_start_iter;
if (input_items_this_row) {
const IType *this_row_column_indexes = column_indexes_ptr + row_item_start_iter;
const DType *row_data_start = in + row_item_start_iter;
DType *output_this_row = out[i].dptr_;
// More overhead to use OMP for small loops, so don't
if (input_items_this_row > 1000) {
#pragma omp parallel for
for (CType j = 0; j < static_cast<CType>(input_items_this_row); ++j) {
const IType col = this_row_column_indexes[j];
const DType val = row_data_start[j];
output_this_row[col] = OP::Map(val, DType(alpha));
}
} else {
for (CType j = 0; j < static_cast<CType>(input_items_this_row); ++j) {
const IType col = this_row_column_indexes[j];
const DType val = row_data_start[j];
output_this_row[col] = OP::Map(val, DType(alpha));
}
}
}
}
}
}
/*! \brief Tensor operation against a scalar with a dense result */
template<typename OP, typename DType, typename IType, typename CType>
static void ComputeExDenseResultCsr(mshadow::Stream<gpu> *stream,
const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &input,
const OpReqType req,
const NDArray &output) {
LOG(FATAL) << "NOT IMPLEMENTED";
}
template<typename xpu, typename OP, typename DType, typename IType>
static void ComputeExDenseResult(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const NDArray &input,
const OpReqType req,
const NDArray output) {
mshadow::Stream<xpu> *stream = ctx.get_stream<xpu>();
CHECK_EQ(output.storage_type(), kDefaultStorage);
switch (input.storage_type()) {
case kRowSparseStorage: {
ComputeExDenseResultRsp<OP, DType, IType>(stream, attrs, ctx, input, req, output);
break;
}
case kCSRStorage: {
MSHADOW_IDX_TYPE_SWITCH(input.aux_data(csr::kIndPtr).type_flag_, CType, {
ComputeExDenseResultCsr<OP, DType, IType, CType>(stream, attrs, ctx, input, req, output);
});
break;
}
default:
CHECK(false) << "Unsupported sparse storage type";
break;
}
}
public:
template<typename xpu, typename OP>
static void Compute(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
DCHECK_EQ(inputs.size(), 1);
DCHECK_EQ(outputs.size(), 1);
using namespace mshadow;
using namespace mshadow::expr;
Stream<xpu> *s = ctx.get_stream<xpu>();
TBlob temp_tblob;
const NumpyBinaryScalarParam& param = nnvm::get<NumpyBinaryScalarParam>(attrs.parsed);
bool scalar_is_int = param.is_int;
const double alpha = param.scalar;
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
if ((common::is_int(inputs[0].type_flag_) && !scalar_is_int) ||
(inputs[0].type_flag_ == kBool)) {
Tensor<xpu, 1, DType> temp_tensor =
ctx.requested[0].get_space_typed<xpu, 1, DType>(Shape1(inputs[0].Size()), s);
temp_tblob = TBlob(temp_tensor);
CastCompute<xpu>(attrs, ctx, {inputs[0]}, {kWriteTo}, {temp_tblob});
} else {
temp_tblob = inputs[0];
}
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
mxnet_op::Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(
s, inputs[0].Size(), outputs[0].dptr<DType>(), temp_tblob.dptr<DType>(), DType(alpha));
});
});
}
template<typename xpu, typename OP>
static void ComputeInt(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
DCHECK_EQ(inputs.size(), 1);
DCHECK_EQ(outputs.size(), 1);
using namespace mshadow;
using namespace mshadow::expr;
Stream<xpu> *s = ctx.get_stream<xpu>();
const NumpyBinaryScalarParam& param = nnvm::get<NumpyBinaryScalarParam>(attrs.parsed);
const double alpha = param.scalar;
MXNET_INT_TYPE_SWITCH(outputs[0].type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
mxnet_op::Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(
s, inputs[0].Size(), outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), DType(alpha));
});
});
}
template<typename xpu, typename OP>
static void ComputeLogic(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
DCHECK_EQ(inputs.size(), 1);
DCHECK_EQ(outputs.size(), 1);
using namespace mshadow;
using namespace mshadow::expr;
Stream<xpu> *s = ctx.get_stream<xpu>();
const NumpyBinaryScalarParam& param = nnvm::get<NumpyBinaryScalarParam>(attrs.parsed);
bool scalar_is_int = param.is_int;
const double alpha = param.scalar;
TBlob temp_tblob;
if (common::is_int(inputs[0].type_flag_) && !scalar_is_int) {
Tensor<xpu, 1, double> temp_tensor =
ctx.requested[0].get_space_typed<xpu, 1, double>(Shape1(inputs[0].Size()), s);
temp_tblob = TBlob(temp_tensor);
CastCompute<xpu>(attrs, ctx, {inputs[0]}, {kWriteTo}, {temp_tblob});
} else {
temp_tblob = inputs[0];
}
MSHADOW_TYPE_SWITCH_WITH_BOOL(temp_tblob.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
mxnet_op::Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(
s, inputs[0].Size(), outputs[0].dptr<bool>(), temp_tblob.dptr<DType>(), DType(alpha));
});
});
}
template<typename xpu, typename OP>
static void ComputeEx(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs) {
DCHECK_EQ(inputs.size(), 1);
DCHECK_EQ(outputs.size(), 1);
const auto in_stype = inputs[0].storage_type();
const auto out_stype = outputs[0].storage_type();
if (req[0] == kNullOp) {
return;
}
if ((in_stype == kRowSparseStorage && out_stype == kRowSparseStorage) ||
(in_stype == kCSRStorage && out_stype == kCSRStorage)) {
// csr -> csr, or rsp -> rsp
UnaryOp::MapToFCompute<xpu>(attrs, ctx, inputs, req, outputs, Compute<xpu, OP>);
} else if (out_stype == kDefaultStorage &&
(in_stype == kRowSparseStorage || in_stype == kCSRStorage)) {
MSHADOW_TYPE_SWITCH(outputs[0].data().type_flag_, DType, {
MSHADOW_IDX_TYPE_SWITCH(inputs[0].aux_type(rowsparse::kIdx), IType, {
ComputeExDenseResult<xpu, OP, DType, IType>(attrs, ctx, inputs[0], req[0], outputs[0]);
});
});
} else {
LogUnimplementedOp(attrs, ctx, inputs, req, outputs);
}
}
template<typename xpu, typename OP>
static void LogicComputeEx(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<NDArray> &inputs,
const std::vector<OpReqType> &req,
const std::vector<NDArray> &outputs) {
DCHECK_EQ(inputs.size(), 1);
DCHECK_EQ(outputs.size(), 1);
const auto in_stype = inputs[0].storage_type();
const auto out_stype = outputs[0].storage_type();
if (req[0] == kNullOp) {
return;
}
if ((in_stype == kRowSparseStorage && out_stype == kRowSparseStorage) ||
(in_stype == kCSRStorage && out_stype == kCSRStorage)) {
// csr -> csr, or rsp -> rsp
UnaryOp::MapToFCompute<xpu>(attrs, ctx, inputs, req, outputs, Compute<xpu, OP>);
} else {
LogUnimplementedOp(attrs, ctx, inputs, req, outputs);
}
}
template<typename xpu, typename OP>
static void Backward(const nnvm::NodeAttrs &attrs,
const OpContext &ctx,
const std::vector<TBlob> &inputs,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &outputs) {
using namespace mshadow;
using namespace mshadow::expr;
Stream<xpu> *s = ctx.get_stream<xpu>();
const NumpyBinaryScalarParam& param = nnvm::get<NumpyBinaryScalarParam>(attrs.parsed);
const double alpha = param.scalar;
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
mxnet::op::mxnet_op::Kernel<mxnet::op::mxnet_op::op_with_req<
mxnet::op::mxnet_op::backward_grad_tuned<OP>, Req>, xpu>::
Launch(s, inputs[0].Size(), outputs[0].dptr<DType>(),
inputs[0].dptr<DType>(), inputs[1].dptr<DType>(),
DType(alpha));
});
});
}
};
#define MXNET_OPERATOR_REGISTER_BINARY_SCALAR(name) \
NNVM_REGISTER_OP(name) \
.set_num_inputs(1) \
.set_num_outputs(1) \
.set_attr_parser(ParamParser<NumpyBinaryScalarParam>) \
.set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<1, 1>) \
.set_attr<nnvm::FInferType>("FInferType", NumpyBinaryScalarType) \
.set_attr<nnvm::FInplaceOption>("FInplaceOption", \
[](const NodeAttrs& attrs){ \
return std::vector<std::pair<int, int> >{{0, 0}}; \
}) \
.set_attr<FResourceRequest>("FResourceRequest", \
[](const NodeAttrs& attrs) { \
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace}; \
}) \
.add_argument("data", "NDArray-or-Symbol", "source input") \
.add_arguments(NumpyBinaryScalarParam::__FIELDS__())
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_SCALAR_OP_H_
|
bit_vector_functions.h | #ifndef BIT_VECTOR_FUNCTIONS_H
#define BIT_VECTOR_FUNCTIONS_H
#include <vector>
#include <bitset>
#include "helper/confusion.h"
#include "config.h"
#include "io_and_allocation.hpp"
#include "updates_and_measures.cuh"
using std::vector;
template<typename bit_vector_t, typename index_t>
size_t computeHammingDistanceCPU(
const vector<bit_vector_t> &Ab,
const vector<bit_vector_t> &Bb,
const vector<bit_vector_t> &Cb,
const index_t height,
const index_t width)
{
size_t error = 0;
#pragma omp parallel for reduction(+:error)
for(index_t j=0; j < width; ++j) {
uint32_t B_j = Bb[j];
for(index_t i=0; i < height; ++i) {
const int product = (Ab[i] & B_j) ? 1 : 0;
const index_t vecId = i / 32 * width + j;
const index_t vecLane = i % 32;
const int C_ij = (Cb[vecId] >> vecLane) & 1;
error += product ^ C_ij;
}
}
return error;
}
template<typename bit_vector_t>
int nonzeroDimension(vector<bit_vector_t>& Ab)
{
bit_vector_t columns = 0;
for(auto& a : Ab) columns |= a;
std::bitset<std::numeric_limits<bit_vector_t>::digits> bits(columns);
return bits.count();
}
template<typename bit_vector_t, typename index_t>
confusion_matrix computeErrorsCPU(
const vector<bit_vector_t> &Ab,
const vector<bit_vector_t> &Bb,
const vector<bit_vector_t> &Cb,
const index_t height,
const index_t width)
{
size_t true_positives = 0;
size_t true_negatives = 0;
size_t false_positives = 0;
size_t false_negatives = 0;
#pragma omp parallel for reduction(+:true_positives) \
reduction(+:true_negatives) \
reduction(+:false_positives) \
reduction(+:false_negatives)
for(index_t j=0; j < width; ++j) {
uint32_t B_j = Bb[j];
for(index_t i=0; i < height; ++i) {
const int product = (Ab[i] & B_j) ? 1 : 0;
const index_t vecId = i / 32 * width + j;
const index_t vecLane = i % 32;
const int C_ij = (Cb[vecId] >> vecLane) & 1;
true_positives += C_ij & product;
true_negatives += !(C_ij | product);
false_positives += (!C_ij) & product;
false_negatives += C_ij & !product;
}
}
return confusion_matrix(true_positives, true_negatives, false_positives, false_negatives);
}
template<typename bit_vector_t, typename index_t>
size_t computeTruePositiveCPU(
const vector<bit_vector_t> &Ab,
const vector<bit_vector_t> &Bb,
const vector<bit_vector_t> &Cb,
const index_t height,
const index_t width)
{
size_t true_positives = 0;
#pragma omp parallel for reduction(+:true_positives)
for(index_t j=0; j < width; ++j) {
uint32_t B_j = Bb[j];
for(index_t i=0; i < height; ++i) {
const int product = (Ab[i] & B_j) ? 1 : 0;
const index_t vecId = i / 32 * width + j;
const index_t vecLane = i % 32;
const int C_ij = (Cb[vecId] >> vecLane) & 1;
if(product & C_ij) true_positives++;
}
}
return true_positives;
}
template<typename bit_vector_t, typename index_t>
float computeJaccardCPU(
const vector<bit_vector_t> &Ab,
const vector<bit_vector_t> &Bb,
const vector<bit_vector_t> &Cb,
const index_t height,
const index_t width)
{
float jaccard = 0;
#pragma omp parallel for reduction(+:jaccard)
for(index_t j=0; j < width; ++j) {
uint32_t B_j = Bb[j];
size_t true_positives = 0;
size_t false_positives = 0;
size_t false_negatives = 0;
for(index_t i=0; i < height; ++i) {
const int product = (Ab[i] & B_j) ? 1 : 0;
const index_t vecId = i / 32 * width + j;
const index_t vecLane = i % 32;
const int C_ij = (Cb[vecId] >> vecLane) & 1;
if(product) {
if(C_ij)
true_positives++;
else
false_positives++;
} else {
if(C_ij)
false_negatives++;
}
}
jaccard += (float) true_positives / (true_positives + false_positives + false_negatives);
}
return jaccard;
}
template<typename bit_factor_t, typename bit_matrix_t, typename index_t, typename error_t>
error_t computeDistanceCPU(
const vector<bit_factor_t> &Ab,
const vector<bit_factor_t> &Bb,
const vector<bit_matrix_t> &Cb,
const index_t height,
const index_t width,
const error_t weight)
{
error_t error = 0;
#pragma omp parallel for reduction(+:error)
for(index_t i=0; i < height; ++i) {
uint32_t A_i = Ab[i];
for(index_t j=0; j < width; ++j) {
const int product = (A_i & Bb[j]) ? 1 : 0;
const index_t vecId = i / 32 * width + j;
const index_t vecLane = i % 32;
const int C_ij = (Cb[vecId] >> vecLane) & 1;
error += error_measure(product, C_ij, weight);
}
}
return error;
}
template<typename bit_vector_t, typename index_t, typename error_t = float>
vector<error_t> computeDensitiesRows(
const vector<bit_vector_t> &Cb,
const index_t height,
const index_t width)
{
vector<error_t> density_rows(height);
#pragma omp parallel for
for(index_t i=0; i<height; ++i) {
size_t nonZeroCount = 0;
for(index_t j=0; j<width; ++j) {
const index_t vecId = i / 32 * width + j;
const index_t vecLane = i % 32;
const int C_ij = (Cb[vecId] >> vecLane) & 1;
nonZeroCount += C_ij;
}
density_rows[i] = (error_t) nonZeroCount / width;
}
return density_rows;
}
template<typename bit_vector_t, typename index_t, typename error_t = float>
vector<error_t> computeDensitiesCols(
const vector<bit_vector_t> &Cb,
const index_t height,
const index_t width)
{
vector<error_t> density_cols(width);
#pragma omp parallel for
for(index_t j=0; j<width; ++j) {
size_t nonZeroCount = 0;
for(index_t i=0; i<height; ++i) {
const index_t vecId = i / 32 * width + j;
const index_t vecLane = i % 32;
const int C_ij = (Cb[vecId] >> vecLane) & 1;
nonZeroCount += C_ij;
}
density_cols[j] = (error_t) nonZeroCount / height;
}
return density_cols;
}
template<typename bit_vector_t, typename index_t, typename error_t = float>
vector<error_t> computeInverseDensitiesRows(
const vector<bit_vector_t> &Cb,
const index_t height,
const index_t width)
{
vector<error_t> inverse_density_rows(height);
#pragma omp parallel for
for(index_t i=0; i<height; ++i) {
size_t nonZeroCount = 0;
for(index_t j=0; j<width; ++j) {
const index_t vecId = i / 32 * width + j;
const index_t vecLane = i % 32;
const int C_ij = (Cb[vecId] >> vecLane) & 1;
nonZeroCount += C_ij;
}
if(nonZeroCount == 0) nonZeroCount++;
inverse_density_rows[i] = (error_t) width / nonZeroCount;
}
return inverse_density_rows;
}
template<typename bit_vector_t, typename index_t, typename error_t = float>
vector<error_t> computeInverseDensitiesCols(
const vector<bit_vector_t> &Cb,
const index_t height,
const index_t width)
{
vector<error_t> inverse_density_cols(width);
#pragma omp parallel for
for(index_t j=0; j<width; ++j) {
size_t nonZeroCount = 0;
for(index_t i=0; i<height; ++i) {
const index_t vecId = i / 32 * width + j;
const index_t vecLane = i % 32;
const int C_ij = (Cb[vecId] >> vecLane) & 1;
nonZeroCount += C_ij;
}
if(nonZeroCount == 0) nonZeroCount++;
inverse_density_cols[j] = (error_t) height / nonZeroCount;
}
return inverse_density_cols;
}
template<typename bit_vector_t, typename index_t>
void updateWholeColumn(
vector<bit_vector_t> &Ab,
const index_t size_A,
const uint8_t factorDim,
const uint8_t column,
const float density,
const uint32_t seed)
{
updateColumnPart(Ab, size_A, factorDim, column, density, 0, size_A, seed);
}
template<typename bit_vector_t, typename index_t>
void updateColumnPart(
vector<bit_vector_t> &Ab,
const index_t size_A,
const uint8_t factorDim,
const uint8_t column,
const float density,
const index_t startline,
const index_t numlines,
const uint32_t seed)
{
const double threshold = getInitChance(density, factorDim);
#pragma omp for
for (index_t id = 0; id < numlines; ++id) {
const index_t i = (startline + id) % size_A;
fast_kiss_state32_t state;
state = get_initial_fast_kiss_state32(seed + i);
const bool set_one = fast_kiss32(state) < threshold * UINT32_MAX;
if (set_one)
Ab[i] |= 1 << column;
else //set 0
Ab[i] &= ~(1 << column);
}
}
template<bool transpose, typename bit_vector_t, typename index_t>
confusion_matrix optimizeWholeColumn(
vector<bit_vector_t> &Ab,
const index_t size_A,
const vector<bit_vector_t> &Bb,
const index_t size_B,
const vector<bit_vector_t> &Cb,
const uint8_t factorDim,
const uint8_t k)
{
confusion_matrix confusion_new;
#pragma omp for
for (index_t i = 0; i < size_A; ++i) {
const bit_vector_t A_i_0 = Ab[i] & ~(1 << k);
const bit_vector_t A_i_1 = Ab[i] | (1 << k);
confusion_matrix confusion_0;
confusion_matrix confusion_1;
for(index_t j=0; j < size_B; ++j) {
const index_t vecId = transpose ? j / 32 * size_A + i : i / 32 * size_B + j;
const index_t vecLane = transpose ? j % 32 : i % 32;
const int C_ij = (Cb[vecId] >> vecLane) & 1;
const int product_0 = (A_i_0 & Bb[j]) ? 1 : 0;
const int product_1 = (A_i_1 & Bb[j]) ? 1 : 0;
confusion_0.TP += C_ij & product_0;
confusion_1.TP += C_ij & product_1;
confusion_0.FN += C_ij & !product_0;
confusion_1.FN += C_ij & !product_1;
confusion_0.FP += (!C_ij) & product_0;
confusion_1.FP += (!C_ij) & product_1;
}
if(confusion_0.total_error() <= confusion_1.total_error()) {
Ab[i] = A_i_0;
confusion_new.TP += confusion_0.TP;
confusion_new.FN += confusion_0.FN;
confusion_new.FP += confusion_0.FP;
}
else {
Ab[i] = A_i_1;
confusion_new.TP += confusion_1.TP;
confusion_new.FN += confusion_1.FN;
confusion_new.FP += confusion_1.FP;
}
}
return confusion_new;
}
template<bool transpose, typename bit_vector_t, typename index_t>
confusion_matrix updateLinesJaccardCPU(vector<bit_vector_t> &Ab,
const index_t size_A,
const vector<bit_vector_t> &Bb,
const index_t size_B,
const vector<bit_vector_t> &Cb,
const uint8_t factorDim,
const index_t startline,
const index_t numlines,
const uint32_t seed,
const float temperature,
const float flipManyChance,
const uint32_t flipManyDepth,
const confusion_matrix confusion)
{
confusion_matrix confusion_update;
#pragma omp for
for(index_t id=0; id < numlines; ++id) {
const index_t i = (startline + id) % size_A;
fast_kiss_state32_t state;
state = get_initial_fast_kiss_state32(seed + id);
const bit_vector_t A_i = Ab[i];
const bit_vector_t A_i_draw = get_flip_mask_many(factorDim, state, flipManyDepth);
const bit_vector_t A_i_flip = A_i ^ A_i_draw;
confusion_matrix confusion_old;
confusion_matrix confusion_draw;
confusion_matrix confusion_flip;
for(index_t j=0; j < size_B; ++j) {
const index_t vecId = transpose ? j / 32 * size_A + i : i / 32 * size_B + j;
const index_t vecLane = transpose ? j % 32 : i % 32;
const int C_ij = (Cb[vecId] >> vecLane) & 1;
const int product_old = (A_i & Bb[j]) ? 1 : 0;
const int product_draw = (A_i_draw & Bb[j]) ? 1 : 0;
const int product_flip = (A_i_flip & Bb[j]) ? 1 : 0;
confusion_old.TP += C_ij & product_old;
confusion_draw.TP += C_ij & product_draw;
confusion_flip.TP += C_ij & product_flip;
confusion_old.FN += C_ij & !product_old;
confusion_draw.FN += C_ij & !product_draw;
confusion_flip.FN += C_ij & !product_flip;
confusion_old.FP += (!C_ij) & product_old;
confusion_draw.FP += (!C_ij) & product_draw;
confusion_flip.FP += (!C_ij) & product_flip;
}
const size_t all_tp_draw = confusion.TP - confusion_old.TP + confusion_draw.TP;
const size_t all_tp_flip = confusion.TP - confusion_old.TP + confusion_flip.TP;
const float jaccard_old = 1.0f * confusion.TP / (confusion.TP + 3*confusion_old.FN + confusion_old.FP);
const float jaccard_draw = 1.0f * all_tp_draw / (all_tp_draw + 3*confusion_draw.FN + confusion_draw.FP);
const float jaccard_flip = 1.0f * all_tp_flip / (all_tp_flip + 3*confusion_flip.FN + confusion_flip.FP);
bit_vector_t A_i_new = A_i_draw;
float jaccard_new = jaccard_draw;
confusion_matrix& confusion_new = confusion_draw;
if(jaccard_draw > jaccard_old) {
if(jaccard_flip > jaccard_draw) {
A_i_new = A_i_flip;
jaccard_new = jaccard_flip;
confusion_new = confusion_flip;
}
} else {
if(jaccard_flip > jaccard_old) {
A_i_new = A_i_flip;
jaccard_new = jaccard_flip;
confusion_new = confusion_flip;
} else {
const uint32_t coin = fast_kiss32(state) % 2;
if(coin) {
A_i_new = A_i_flip;
jaccard_new = jaccard_flip;
confusion_new = confusion_flip;
}
}
}
if (metro(state, jaccard_old - jaccard_new, temperature)) {
Ab[i] = A_i_new;
confusion_update.TP += confusion_new.TP - confusion_old.TP;
confusion_update.FP += confusion_new.FP - confusion_old.FP;
confusion_update.FN += confusion_new.FN - confusion_old.FN;
}
}
return confusion_update;
}
template<bool transpose, typename bit_vector_t, typename index_t, typename error_t>
int vectorMatrixMultCompareLineCPU(vector<bit_vector_t> &Ab,
const index_t size_A,
const vector<bit_vector_t> &Bb,
const index_t size_B,
const vector<bit_vector_t> &Cb,
const uint8_t factorDim,
const index_t startline,
const index_t numlines,
const uint32_t seed,
const float temperature,
const float flipManyChance,
const uint32_t flipManyDepth,
const error_t weight)
{
error_t error_update = 0;
#pragma omp for
// #pragma omp parallel for reduction(+:error_update)
for(index_t id=0; id < numlines; ++id) {
const index_t i = (startline + id) % size_A;
fast_kiss_state32_t state;
state = get_initial_fast_kiss_state32(seed + id);
const bit_vector_t A_i = Ab[i];
bit_vector_t A_i_changed = Ab[i] ^ get_flip_mask(factorDim, state, flipManyChance, flipManyDepth);
error_t error = 0;
for(index_t j=0; j < size_B; ++j) {
const index_t vecId = transpose ? j / 32 * size_A + i : i / 32 * size_B + j;
const index_t vecLane = transpose ? j % 32 : i % 32;
const int C_ij = (Cb[vecId] >> vecLane) & 1;
const int product_old = (A_i & Bb[j]) ? 1 : 0;
const int product_new = (A_i_changed & Bb[j]) ? 1 : 0;
error += error_measure(product_new, C_ij, weight)
- error_measure(product_old, C_ij, weight);
}
if (metro(state, error, temperature, size_B)) {
Ab[i] = A_i_changed;
error_update += error;
}
}
return error_update;
}
template <typename index_t>
struct coo {
coo(index_t x, index_t y) : x_{x}, y_{y} {}
index_t x_;
index_t y_;
};
template <typename bit_vector_t, typename index_t>
vector<coo<index_t>> computeProductCOO(
const vector<bit_vector_t> &Ab,
const vector<bit_vector_t> &Bb,
const index_t height,
const index_t width)
{
vector<coo<index_t>> C;
#pragma omp parallel for ordered schedule(static,1)
for(index_t i=0; i < height; ++i) {
bit_vector_t row = Ab[i];
vector<coo<index_t>> Ci;
for(index_t j=0; j < width; ++j) {
if(row & Bb[j])
Ci.emplace_back(i,j);
}
#pragma omp ordered
C.insert(C.end(), Ci.begin(), Ci.end());
}
return C;
}
#endif
|
Partition.h | /*
* Partition.h
*
* Created on: 03.10.2013
* Author: cls
*/
#ifndef PARTITION_H_
#define PARTITION_H_
#include <cinttypes>
#include <set>
#include <vector>
#include <map>
#include <cassert>
#include <limits>
#include "../Globals.h"
namespace NetworKit {
/**
* @ingroup structures
* Implements a partition of a set, i.e. a subdivision of the
* set into disjoint subsets.
*/
class Partition {
public:
Partition();
/**
* Create a new partition data structure for @a z elements.
*
* @param[in] z maximum index
*/
Partition(index z);
/**
* Create a new partition data structure for @a z elements.
* Initialize each entry to the default value.
* WARNING: this circumvents the standard interface and may leave the object
* in an inconsistent state. Use only in exceptional cases.
*
* @param[in] z maximum index
* @param[in] defaultValue
*/
Partition(index z, index defaultValue);
Partition(const std::vector<index>& data);
/**
* Index operator.
*
* @param[in] e an element
*/
inline index& operator [](const index& e) {
return this->data[e];
}
/**
* Index operator for const instances of this class.
*
* @param[in] e an element
*/
inline const index& operator [](const index& e) const {
return this->data[e];
}
/**
* Get the set (id) in which the element @a e is contained.
*
* @param e Index of element.
* @return The index of the set in which @a e is contained.
*/
inline index subsetOf(index e) const {
assert (e < this->numberOfElements());
return this->data[e];
}
/**
* Extend the data structure and create a slot
* for one more element. Initializes the entry to none
* and returns the index of the entry.
*/
inline index extend() {
data.push_back(none);
z++;
assert (z == data.size()); //(data.size() - 1)
return z-1;
}
/**
* Removes the entry for the given element
* by setting it to none.
*/
inline void remove(index e) {
assert (e < z);
data[e] = none;
}
/**
* Add a (previously unassigned) element @a e to the set @a s.
*
* @param s The index of the subset.
* @param e The element to add.
*/
inline void addToSubset(index s, index e) {
assert (data[e] == none); // guarantee that element was unassigned
assert (s <= omega); // do not create new subset ids
data[e] = s;
}
/**
* Move the (previously assigned) element @a e to the set @a s.
*
* @param s The index of the subset.
* @param e The element to move.
*/
inline void moveToSubset(index s, index e) {
assert (this->contains(e));
assert (s <= omega); // do not create new subset ids
data[e] = s;
}
/**
* Creates a singleton set containing the element @a e.
*
* @param e The index of the element.
*/
inline void toSingleton(index e) {
data[e] = newSubsetId();
}
/**
* Assigns every element to a singleton set.
* Set id is equal to element id.
*/
void allToSingletons();
/**
* Assigns every element to the same subset.
* Set id is equal to zero.
*/
void allToOnePartition();
/**
* Assigns the elements from both sets to a new set and returns the id of it.
*
* @param s Set to merge.
* @param t Set to merge.
* @return Id of newly created set.
*/
index mergeSubsets(index s, index t);
/**
* Sets an upper bound for the subset ids that CAN be assigned.
*
* @param[in] upper highest assigned subset ID + 1
*/
inline void setUpperBound(index upper) {
this->omega = upper-1;
}
/**
* Return an upper bound for the subset ids that have been assigned.
* (This is the maximum id + 1.)
*
* @return The upper bound.
*/
inline index upperBound() const {
return omega+1;
}
/**
* Get a lower bound for the subset ids that have been assigned.
*
* @return The lower bound.
*/
inline index lowerBound() const {
return 0;
}
/**
* Change subset IDs to be consecutive, starting at 0.
* @param useTurbo Default: false. If set to true, a vector instead of a map to assign new ids
* which results in a shorter running time but possibly a large space overhead.
*/
void compact(bool useTurbo = false);
/**
* Check if partition assigns a valid subset to the element @a e.
*
* @param e The element.
* @return @c true if the assigned subset is valid, @c false otherwise.
*/
inline bool contains(index e) const {
return (e < z) && (data[e] != none); // e is in the element index range and the entry is not empty
}
/**
* Check if two elements @a e1 and @a e2 belong to the same subset.
*
* @param e1 Element.
* @param e2 Element.
* @return @c true if @a e1 and @a e2 belong to same subset, @c false otherwise.
*/
inline bool inSameSubset(index e1, index e2) const {
assert (data[e1] != none);
assert (data[e2] != none);
return (data[e1] == data[e2]);
}
/**
* Get a list of subset sizes. Indices do not necessarily correspond to subset ids.
*
* @return A vector of subset sizes.
*/
std::vector<count> subsetSizes() const;
/**
* Get a map from subset id to size of the subset.
*
* @return A map from subset id to size of the subset.
*/
std::map<index, count> subsetSizeMap() const;
/**
* Get the members of the subset @a s.
*
* @param s The subset.
* @return A set containing the members of @a s.
*/
std::set<index> getMembers(const index s) const;
/**
* @return number of elements in the partition.
*/
inline count numberOfElements() const {
return z; // z is the maximum element id
}
/**
* Get the current number of sets in this partition.
*
* @return The current number of sets.
*/
count numberOfSubsets() const;
/**
* Get the actual vector representing the partition data structure.
* @return vector containing information about partitions.
*/
std::vector<index> getVector() const;
/**
* @return the subsets of the partition as a set of sets.
*/
std::set<std::set<index> > getSubsets() const;
/**
* Get the ids of nonempty subsets.
*
* @return A set of ids of nonempty subsets.
*/
std::set<index> getSubsetIds() const;
/**
* Set a human-readable identifier @a name for the instance.
*
* @param name The name.
*/
inline void setName(std::string name) {
this->name = name;
}
/**
* Get the human-readable identifier.
*
* @return The name of this partition.
*/
inline std::string getName() const {
return this->name;
}
/**
* Iterate over all entries (node, cluster id) and execute callback function @a func (lambda closure).
*
* @param func Takes parameters <code>(node, index)</code>
*/
template<typename Callback> void forEntries(Callback func) const;
/**
* Iterate over all entries (node, cluster id) in parallel and execute callback function @a handle (lambda closure).
*
* @param handle Takes parameters <code>(node, index)</code>
*/
template<typename Callback> void parallelForEntries(Callback handle) const;
private:
index z; //!< maximum element index that can be mapped
index omega; //!< maximum subset index ever assigned
std::vector<index> data; //!< data container, indexed by element index, containing subset index
std::string name;
/**
* Allocates and returns a new subset id.
*/
inline index newSubsetId() {
index s = ++omega;
return s;
}
};
template<typename Callback>
inline void Partition::forEntries(Callback handle) const {
for (index e = 0; e < this->z; e++) {
handle(e, data[e]);
}
}
template<typename Callback>
inline void Partition::parallelForEntries(Callback handle) const {
#pragma omp parallel for
for (omp_index e = 0; e < static_cast<omp_index>(this->z); e++) {
handle(e, this->data[e]);
}
}
} /* namespace NetworKit */
#endif /* PARTITION_H_ */
|
schur_eliminator_impl.h | // Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// 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 Google Inc. 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 OWNER 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.
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
//
// TODO(sameeragarwal): row_block_counter can perhaps be replaced by
// Chunk::start ?
#ifndef CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_
#define CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_
// Eigen has an internal threshold switching between different matrix
// multiplication algorithms. In particular for matrices larger than
// EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD it uses a cache friendly
// matrix matrix product algorithm that has a higher setup cost. For
// matrix sizes close to this threshold, especially when the matrices
// are thin and long, the default choice may not be optimal. This is
// the case for us, as the default choice causes a 30% performance
// regression when we moved from Eigen2 to Eigen3.
#define EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD 10
// This include must come before any #ifndef check on Ceres compile options.
#include "ceres/internal/port.h"
#ifdef CERES_USE_OPENMP
#include <omp.h>
#endif
#include <algorithm>
#include <map>
#include "ceres/block_random_access_matrix.h"
#include "ceres/block_sparse_matrix.h"
#include "ceres/block_structure.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/fixed_array.h"
#include "ceres/internal/scoped_ptr.h"
#include "ceres/map_util.h"
#include "ceres/schur_eliminator.h"
#include "ceres/small_blas.h"
#include "ceres/stl_util.h"
#include "Eigen/Dense"
#include "glog/logging.h"
namespace ceres {
namespace internal {
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::~SchurEliminator() {
STLDeleteElements(&rhs_locks_);
}
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
Init(int num_eliminate_blocks, const CompressedRowBlockStructure* bs) {
CHECK_GT(num_eliminate_blocks, 0)
<< "SchurComplementSolver cannot be initialized with "
<< "num_eliminate_blocks = 0.";
num_eliminate_blocks_ = num_eliminate_blocks;
const int num_col_blocks = bs->cols.size();
const int num_row_blocks = bs->rows.size();
buffer_size_ = 1;
chunks_.clear();
lhs_row_layout_.clear();
int lhs_num_rows = 0;
// Add a map object for each block in the reduced linear system
// and build the row/column block structure of the reduced linear
// system.
lhs_row_layout_.resize(num_col_blocks - num_eliminate_blocks_);
for (int i = num_eliminate_blocks_; i < num_col_blocks; ++i) {
lhs_row_layout_[i - num_eliminate_blocks_] = lhs_num_rows;
lhs_num_rows += bs->cols[i].size;
}
int r = 0;
// Iterate over the row blocks of A, and detect the chunks. The
// matrix should already have been ordered so that all rows
// containing the same y block are vertically contiguous. Along
// the way also compute the amount of space each chunk will need
// to perform the elimination.
while (r < num_row_blocks) {
const int chunk_block_id = bs->rows[r].cells.front().block_id;
if (chunk_block_id >= num_eliminate_blocks_) {
break;
}
chunks_.push_back(Chunk());
Chunk& chunk = chunks_.back();
chunk.size = 0;
chunk.start = r;
int buffer_size = 0;
const int e_block_size = bs->cols[chunk_block_id].size;
// Add to the chunk until the first block in the row is
// different than the one in the first row for the chunk.
while (r + chunk.size < num_row_blocks) {
const CompressedRow& row = bs->rows[r + chunk.size];
if (row.cells.front().block_id != chunk_block_id) {
break;
}
// Iterate over the blocks in the row, ignoring the first
// block since it is the one to be eliminated.
for (int c = 1; c < row.cells.size(); ++c) {
const Cell& cell = row.cells[c];
if (InsertIfNotPresent(
&(chunk.buffer_layout), cell.block_id, buffer_size)) {
buffer_size += e_block_size * bs->cols[cell.block_id].size;
}
}
buffer_size_ = max(buffer_size, buffer_size_);
++chunk.size;
}
CHECK_GT(chunk.size, 0);
r += chunk.size;
}
const Chunk& chunk = chunks_.back();
uneliminated_row_begins_ = chunk.start + chunk.size;
if (num_threads_ > 1) {
random_shuffle(chunks_.begin(), chunks_.end());
}
buffer_.reset(new double[buffer_size_ * num_threads_]);
// chunk_outer_product_buffer_ only needs to store e_block_size *
// f_block_size, which is always less than buffer_size_, so we just
// allocate buffer_size_ per thread.
chunk_outer_product_buffer_.reset(new double[buffer_size_ * num_threads_]);
STLDeleteElements(&rhs_locks_);
rhs_locks_.resize(num_col_blocks - num_eliminate_blocks_);
for (int i = 0; i < num_col_blocks - num_eliminate_blocks_; ++i) {
rhs_locks_[i] = new Mutex;
}
}
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
Eliminate(const BlockSparseMatrix* A,
const double* b,
const double* D,
BlockRandomAccessMatrix* lhs,
double* rhs) {
if (lhs->num_rows() > 0) {
lhs->SetZero();
VectorRef(rhs, lhs->num_rows()).setZero();
}
const CompressedRowBlockStructure* bs = A->block_structure();
const int num_col_blocks = bs->cols.size();
// Add the diagonal to the schur complement.
if (D != NULL) {
#pragma omp parallel for num_threads(num_threads_) schedule(dynamic)
for (int i = num_eliminate_blocks_; i < num_col_blocks; ++i) {
const int block_id = i - num_eliminate_blocks_;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block_id, block_id,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
const int block_size = bs->cols[i].size;
typename EigenTypes<kFBlockSize>::ConstVectorRef
diag(D + bs->cols[i].position, block_size);
CeresMutexLock l(&cell_info->m);
MatrixRef m(cell_info->values, row_stride, col_stride);
m.block(r, c, block_size, block_size).diagonal()
+= diag.array().square().matrix();
}
}
}
// Eliminate y blocks one chunk at a time. For each chunk,x3
// compute the entries of the normal equations and the gradient
// vector block corresponding to the y block and then apply
// Gaussian elimination to them. The matrix ete stores the normal
// matrix corresponding to the block being eliminated and array
// buffer_ contains the non-zero blocks in the row corresponding
// to this y block in the normal equations. This computation is
// done in ChunkDiagonalBlockAndGradient. UpdateRhs then applies
// gaussian elimination to the rhs of the normal equations,
// updating the rhs of the reduced linear system by modifying rhs
// blocks for all the z blocks that share a row block/residual
// term with the y block. EliminateRowOuterProduct does the
// corresponding operation for the lhs of the reduced linear
// system.
#pragma omp parallel for num_threads(num_threads_) schedule(dynamic)
for (int i = 0; i < chunks_.size(); ++i) {
#ifdef CERES_USE_OPENMP
int thread_id = omp_get_thread_num();
#else
int thread_id = 0;
#endif
double* buffer = buffer_.get() + thread_id * buffer_size_;
const Chunk& chunk = chunks_[i];
const int e_block_id = bs->rows[chunk.start].cells.front().block_id;
const int e_block_size = bs->cols[e_block_id].size;
VectorRef(buffer, buffer_size_).setZero();
typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix
ete(e_block_size, e_block_size);
if (D != NULL) {
const typename EigenTypes<kEBlockSize>::ConstVectorRef
diag(D + bs->cols[e_block_id].position, e_block_size);
ete = diag.array().square().matrix().asDiagonal();
} else {
ete.setZero();
}
FixedArray<double, 8> g(e_block_size);
typename EigenTypes<kEBlockSize>::VectorRef gref(g.get(), e_block_size);
gref.setZero();
// We are going to be computing
//
// S += F'F - F'E(E'E)^{-1}E'F
//
// for each Chunk. The computation is broken down into a number of
// function calls as below.
// Compute the outer product of the e_blocks with themselves (ete
// = E'E). Compute the product of the e_blocks with the
// corresonding f_blocks (buffer = E'F), the gradient of the terms
// in this chunk (g) and add the outer product of the f_blocks to
// Schur complement (S += F'F).
ChunkDiagonalBlockAndGradient(
chunk, A, b, chunk.start, &ete, g.get(), buffer, lhs);
// Normally one wouldn't compute the inverse explicitly, but
// e_block_size will typically be a small number like 3, in
// which case its much faster to compute the inverse once and
// use it to multiply other matrices/vectors instead of doing a
// Solve call over and over again.
typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix inverse_ete =
ete
.template selfadjointView<Eigen::Upper>()
.llt()
.solve(Matrix::Identity(e_block_size, e_block_size));
// For the current chunk compute and update the rhs of the reduced
// linear system.
//
// rhs = F'b - F'E(E'E)^(-1) E'b
FixedArray<double, 8> inverse_ete_g(e_block_size);
MatrixVectorMultiply<kEBlockSize, kEBlockSize, 0>(
inverse_ete.data(),
e_block_size,
e_block_size,
g.get(),
inverse_ete_g.get());
UpdateRhs(chunk, A, b, chunk.start, inverse_ete_g.get(), rhs);
// S -= F'E(E'E)^{-1}E'F
ChunkOuterProduct(bs, inverse_ete, buffer, chunk.buffer_layout, lhs);
}
// For rows with no e_blocks, the schur complement update reduces to
// S += F'F.
NoEBlockRowsUpdate(A, b, uneliminated_row_begins_, lhs, rhs);
}
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
BackSubstitute(const BlockSparseMatrix* A,
const double* b,
const double* D,
const double* z,
double* y) {
const CompressedRowBlockStructure* bs = A->block_structure();
#pragma omp parallel for num_threads(num_threads_) schedule(dynamic)
for (int i = 0; i < chunks_.size(); ++i) {
const Chunk& chunk = chunks_[i];
const int e_block_id = bs->rows[chunk.start].cells.front().block_id;
const int e_block_size = bs->cols[e_block_id].size;
double* y_ptr = y + bs->cols[e_block_id].position;
typename EigenTypes<kEBlockSize>::VectorRef y_block(y_ptr, e_block_size);
typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix
ete(e_block_size, e_block_size);
if (D != NULL) {
const typename EigenTypes<kEBlockSize>::ConstVectorRef
diag(D + bs->cols[e_block_id].position, e_block_size);
ete = diag.array().square().matrix().asDiagonal();
} else {
ete.setZero();
}
const double* values = A->values();
for (int j = 0; j < chunk.size; ++j) {
const CompressedRow& row = bs->rows[chunk.start + j];
const Cell& e_cell = row.cells.front();
DCHECK_EQ(e_block_id, e_cell.block_id);
FixedArray<double, 8> sj(row.block.size);
typename EigenTypes<kRowBlockSize>::VectorRef(sj.get(), row.block.size) =
typename EigenTypes<kRowBlockSize>::ConstVectorRef
(b + bs->rows[chunk.start + j].block.position, row.block.size);
for (int c = 1; c < row.cells.size(); ++c) {
const int f_block_id = row.cells[c].block_id;
const int f_block_size = bs->cols[f_block_id].size;
const int r_block = f_block_id - num_eliminate_blocks_;
MatrixVectorMultiply<kRowBlockSize, kFBlockSize, -1>(
values + row.cells[c].position, row.block.size, f_block_size,
z + lhs_row_layout_[r_block],
sj.get());
}
MatrixTransposeVectorMultiply<kRowBlockSize, kEBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
sj.get(),
y_ptr);
MatrixTransposeMatrixMultiply
<kRowBlockSize, kEBlockSize, kRowBlockSize, kEBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
values + e_cell.position, row.block.size, e_block_size,
ete.data(), 0, 0, e_block_size, e_block_size);
}
ete.llt().solveInPlace(y_block);
}
}
// Update the rhs of the reduced linear system. Compute
//
// F'b - F'E(E'E)^(-1) E'b
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
UpdateRhs(const Chunk& chunk,
const BlockSparseMatrix* A,
const double* b,
int row_block_counter,
const double* inverse_ete_g,
double* rhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
const int e_block_id = bs->rows[chunk.start].cells.front().block_id;
const int e_block_size = bs->cols[e_block_id].size;
int b_pos = bs->rows[row_block_counter].block.position;
const double* values = A->values();
for (int j = 0; j < chunk.size; ++j) {
const CompressedRow& row = bs->rows[row_block_counter + j];
const Cell& e_cell = row.cells.front();
typename EigenTypes<kRowBlockSize>::Vector sj =
typename EigenTypes<kRowBlockSize>::ConstVectorRef
(b + b_pos, row.block.size);
MatrixVectorMultiply<kRowBlockSize, kEBlockSize, -1>(
values + e_cell.position, row.block.size, e_block_size,
inverse_ete_g, sj.data());
for (int c = 1; c < row.cells.size(); ++c) {
const int block_id = row.cells[c].block_id;
const int block_size = bs->cols[block_id].size;
const int block = block_id - num_eliminate_blocks_;
CeresMutexLock l(rhs_locks_[block]);
MatrixTransposeVectorMultiply<kRowBlockSize, kFBlockSize, 1>(
values + row.cells[c].position,
row.block.size, block_size,
sj.data(), rhs + lhs_row_layout_[block]);
}
b_pos += row.block.size;
}
}
// Given a Chunk - set of rows with the same e_block, e.g. in the
// following Chunk with two rows.
//
// E F
// [ y11 0 0 0 | z11 0 0 0 z51]
// [ y12 0 0 0 | z12 z22 0 0 0]
//
// this function computes twp matrices. The diagonal block matrix
//
// ete = y11 * y11' + y12 * y12'
//
// and the off diagonal blocks in the Guass Newton Hessian.
//
// buffer = [y11'(z11 + z12), y12' * z22, y11' * z51]
//
// which are zero compressed versions of the block sparse matrices E'E
// and E'F.
//
// and the gradient of the e_block, E'b.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
ChunkDiagonalBlockAndGradient(
const Chunk& chunk,
const BlockSparseMatrix* A,
const double* b,
int row_block_counter,
typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix* ete,
double* g,
double* buffer,
BlockRandomAccessMatrix* lhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
int b_pos = bs->rows[row_block_counter].block.position;
const int e_block_size = ete->rows();
// Iterate over the rows in this chunk, for each row, compute the
// contribution of its F blocks to the Schur complement, the
// contribution of its E block to the matrix EE' (ete), and the
// corresponding block in the gradient vector.
const double* values = A->values();
for (int j = 0; j < chunk.size; ++j) {
const CompressedRow& row = bs->rows[row_block_counter + j];
if (row.cells.size() > 1) {
EBlockRowOuterProduct(A, row_block_counter + j, lhs);
}
// Extract the e_block, ETE += E_i' E_i
const Cell& e_cell = row.cells.front();
MatrixTransposeMatrixMultiply
<kRowBlockSize, kEBlockSize, kRowBlockSize, kEBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
values + e_cell.position, row.block.size, e_block_size,
ete->data(), 0, 0, e_block_size, e_block_size);
// g += E_i' b_i
MatrixTransposeVectorMultiply<kRowBlockSize, kEBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
b + b_pos,
g);
// buffer = E'F. This computation is done by iterating over the
// f_blocks for each row in the chunk.
for (int c = 1; c < row.cells.size(); ++c) {
const int f_block_id = row.cells[c].block_id;
const int f_block_size = bs->cols[f_block_id].size;
double* buffer_ptr =
buffer + FindOrDie(chunk.buffer_layout, f_block_id);
MatrixTransposeMatrixMultiply
<kRowBlockSize, kEBlockSize, kRowBlockSize, kFBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
values + row.cells[c].position, row.block.size, f_block_size,
buffer_ptr, 0, 0, e_block_size, f_block_size);
}
b_pos += row.block.size;
}
}
// Compute the outer product F'E(E'E)^{-1}E'F and subtract it from the
// Schur complement matrix, i.e
//
// S -= F'E(E'E)^{-1}E'F.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
ChunkOuterProduct(const CompressedRowBlockStructure* bs,
const Matrix& inverse_ete,
const double* buffer,
const BufferLayoutType& buffer_layout,
BlockRandomAccessMatrix* lhs) {
// This is the most computationally expensive part of this
// code. Profiling experiments reveal that the bottleneck is not the
// computation of the right-hand matrix product, but memory
// references to the left hand side.
const int e_block_size = inverse_ete.rows();
BufferLayoutType::const_iterator it1 = buffer_layout.begin();
#ifdef CERES_USE_OPENMP
int thread_id = omp_get_thread_num();
#else
int thread_id = 0;
#endif
double* b1_transpose_inverse_ete =
chunk_outer_product_buffer_.get() + thread_id * buffer_size_;
// S(i,j) -= bi' * ete^{-1} b_j
for (; it1 != buffer_layout.end(); ++it1) {
const int block1 = it1->first - num_eliminate_blocks_;
const int block1_size = bs->cols[it1->first].size;
MatrixTransposeMatrixMultiply
<kEBlockSize, kFBlockSize, kEBlockSize, kEBlockSize, 0>(
buffer + it1->second, e_block_size, block1_size,
inverse_ete.data(), e_block_size, e_block_size,
b1_transpose_inverse_ete, 0, 0, block1_size, e_block_size);
BufferLayoutType::const_iterator it2 = it1;
for (; it2 != buffer_layout.end(); ++it2) {
const int block2 = it2->first - num_eliminate_blocks_;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block2,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
const int block2_size = bs->cols[it2->first].size;
CeresMutexLock l(&cell_info->m);
MatrixMatrixMultiply
<kFBlockSize, kEBlockSize, kEBlockSize, kFBlockSize, -1>(
b1_transpose_inverse_ete, block1_size, e_block_size,
buffer + it2->second, e_block_size, block2_size,
cell_info->values, r, c, row_stride, col_stride);
}
}
}
}
// For rows with no e_blocks, the schur complement update reduces to S
// += F'F. This function iterates over the rows of A with no e_block,
// and calls NoEBlockRowOuterProduct on each row.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
NoEBlockRowsUpdate(const BlockSparseMatrix* A,
const double* b,
int row_block_counter,
BlockRandomAccessMatrix* lhs,
double* rhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
const double* values = A->values();
for (; row_block_counter < bs->rows.size(); ++row_block_counter) {
const CompressedRow& row = bs->rows[row_block_counter];
for (int c = 0; c < row.cells.size(); ++c) {
const int block_id = row.cells[c].block_id;
const int block_size = bs->cols[block_id].size;
const int block = block_id - num_eliminate_blocks_;
MatrixTransposeVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>(
values + row.cells[c].position, row.block.size, block_size,
b + row.block.position,
rhs + lhs_row_layout_[block]);
}
NoEBlockRowOuterProduct(A, row_block_counter, lhs);
}
}
// A row r of A, which has no e_blocks gets added to the Schur
// Complement as S += r r'. This function is responsible for computing
// the contribution of a single row r to the Schur complement. It is
// very similar in structure to EBlockRowOuterProduct except for
// one difference. It does not use any of the template
// parameters. This is because the algorithm used for detecting the
// static structure of the matrix A only pays attention to rows with
// e_blocks. This is becase rows without e_blocks are rare and
// typically arise from regularization terms in the original
// optimization problem, and have a very different structure than the
// rows with e_blocks. Including them in the static structure
// detection will lead to most template parameters being set to
// dynamic. Since the number of rows without e_blocks is small, the
// lack of templating is not an issue.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
NoEBlockRowOuterProduct(const BlockSparseMatrix* A,
int row_block_index,
BlockRandomAccessMatrix* lhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
const CompressedRow& row = bs->rows[row_block_index];
const double* values = A->values();
for (int i = 0; i < row.cells.size(); ++i) {
const int block1 = row.cells[i].block_id - num_eliminate_blocks_;
DCHECK_GE(block1, 0);
const int block1_size = bs->cols[row.cells[i].block_id].size;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block1,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
CeresMutexLock l(&cell_info->m);
// This multiply currently ignores the fact that this is a
// symmetric outer product.
MatrixTransposeMatrixMultiply
<Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, 1>(
values + row.cells[i].position, row.block.size, block1_size,
values + row.cells[i].position, row.block.size, block1_size,
cell_info->values, r, c, row_stride, col_stride);
}
for (int j = i + 1; j < row.cells.size(); ++j) {
const int block2 = row.cells[j].block_id - num_eliminate_blocks_;
DCHECK_GE(block2, 0);
DCHECK_LT(block1, block2);
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block2,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
const int block2_size = bs->cols[row.cells[j].block_id].size;
CeresMutexLock l(&cell_info->m);
MatrixTransposeMatrixMultiply
<Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, 1>(
values + row.cells[i].position, row.block.size, block1_size,
values + row.cells[j].position, row.block.size, block2_size,
cell_info->values, r, c, row_stride, col_stride);
}
}
}
}
// For a row with an e_block, compute the contribition S += F'F. This
// function has the same structure as NoEBlockRowOuterProduct, except
// that this function uses the template parameters.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
EBlockRowOuterProduct(const BlockSparseMatrix* A,
int row_block_index,
BlockRandomAccessMatrix* lhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
const CompressedRow& row = bs->rows[row_block_index];
const double* values = A->values();
for (int i = 1; i < row.cells.size(); ++i) {
const int block1 = row.cells[i].block_id - num_eliminate_blocks_;
DCHECK_GE(block1, 0);
const int block1_size = bs->cols[row.cells[i].block_id].size;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block1,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
CeresMutexLock l(&cell_info->m);
// block += b1.transpose() * b1;
MatrixTransposeMatrixMultiply
<kRowBlockSize, kFBlockSize, kRowBlockSize, kFBlockSize, 1>(
values + row.cells[i].position, row.block.size, block1_size,
values + row.cells[i].position, row.block.size, block1_size,
cell_info->values, r, c, row_stride, col_stride);
}
for (int j = i + 1; j < row.cells.size(); ++j) {
const int block2 = row.cells[j].block_id - num_eliminate_blocks_;
DCHECK_GE(block2, 0);
DCHECK_LT(block1, block2);
const int block2_size = bs->cols[row.cells[j].block_id].size;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block2,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
// block += b1.transpose() * b2;
CeresMutexLock l(&cell_info->m);
MatrixTransposeMatrixMultiply
<kRowBlockSize, kFBlockSize, kRowBlockSize, kFBlockSize, 1>(
values + row.cells[i].position, row.block.size, block1_size,
values + row.cells[j].position, row.block.size, block2_size,
cell_info->values, r, c, row_stride, col_stride);
}
}
}
}
} // namespace internal
} // namespace ceres
#endif // CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_
|
ten_tusscher_2004_epi_S2_12.c | //Original Ten Tusscher
#include <assert.h>
#include <stdlib.h>
#include "ten_tusscher_2004_epi_S2_12.h"
GET_CELL_MODEL_DATA(init_cell_model_data) {
assert(cell_model);
if(get_initial_v)
cell_model->initial_v = INITIAL_V;
if(get_neq)
cell_model->number_of_ode_equations = NEQ;
}
//TODO: this should be called only once for the whole mesh, like in the GPU code
SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) {
// Default initial conditions
/*
sv[0] = INITIAL_V; // V; millivolt
sv[1] = 0.f; //M
sv[2] = 0.75; //H
sv[3] = 0.75f; //J
sv[4] = 0.f; //Xr1
sv[5] = 1.f; //Xr2
sv[6] = 0.f; //Xs
sv[7] = 1.f; //S
sv[8] = 0.f; //R
sv[9] = 0.f; //D
sv[10] = 1.f; //F
sv[11] = 1.f; //FCa
sv[12] = 1.f; //G
sv[13] = 0.0002; //Cai
sv[14] = 0.2f; //CaSR
sv[15] = 11.6f; //Nai
sv[16] = 138.3f; //Ki
*/
// Elnaz's steady-state initial conditions
real sv_sst[]={-86.5384082987608,0.00129831811982894,0.778973907375400,0.778770359064450,0.000175617603671969,0.484779426120966,0.00294656185560798,0.999998338163124,1.94314968247144e-08,1.89860853576860e-05,0.999768890841901,1.00699067411443,0.999993647054558,4.76253466507928e-05,1.07498477804450,9.16427826493556,140.147002852970};
for (uint32_t i = 0; i < NEQ; i++)
sv[i] = sv_sst[i];
}
SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) {
uint32_t sv_id;
int i;
#pragma omp parallel for private(sv_id)
for (i = 0; i < num_cells_to_solve; i++) {
if(cells_to_solve)
sv_id = cells_to_solve[i];
else
sv_id = i;
for (int j = 0; j < num_steps; ++j) {
solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]);
}
}
}
void solve_model_ode_cpu(real dt, real *sv, real stim_current) {
assert(sv);
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu(rY, rDY, stim_current, dt);
for(int i = 0; i < NEQ; i++)
sv[i] = rDY[i];
}
void RHS_cpu(const real *sv, real *rDY_, real stim_current, real dt) {
// State variables
real svolt = sv[0];
real sm = sv[1];
real sh = sv[2];
real sj = sv[3];
real sxr1 = sv[4];
real sxr2 = sv[5];
real sxs = sv[6];
real ss = sv[7];
real sr = sv[8];
real sd = sv[9];
real sf = sv[10];
real sfca = sv[11];
real sg = sv[12];
real Cai = sv[13];
real CaSR = sv[14];
real Nai = sv[15];
real Ki = sv[16];
//External concentrations
real Ko=5.4;
real Cao=2.0;
real Nao=140.0;
//Intracellular volumes
real Vc=0.016404;
real Vsr=0.001094;
//Calcium dynamics
real Bufc=0.15f;
real Kbufc=0.001f;
real Bufsr=10.f;
real Kbufsr=0.3f;
real taufca=2.f;
real taug=2.f;
real Vmaxup=0.000425f;
real Kup=0.00025f;
//Constants
const real R = 8314.472f;
const real F = 96485.3415f;
const real T =310.0f;
real RTONF =(R*T)/F;
//Cellular capacitance
real CAPACITANCE=0.185;
//Parameters for currents
//Parameters for IKr
real Gkr=0.096;
//Parameters for Iks
real pKNa=0.03;
///#ifdef EPI
real Gks=0.245;
///#endif
///#ifdef ENDO
/// real Gks=0.245;
///#endif
///#ifdef MCELL
/// real Gks=0.062;
///#endif
//Parameters for Ik1
real GK1=5.405;
//Parameters for Ito
//#ifdef EPI
real Gto=0.294;
//#endif
// #ifdef ENDO
// real Gto=0.073;
//#endif
//#ifdef MCELL
// real Gto=0.294;
///#endif
//Parameters for INa
real GNa=14.838;
//Parameters for IbNa
real GbNa=0.00029;
//Parameters for INaK
real KmK=1.0;
real KmNa=40.0;
real knak=1.362;
//Parameters for ICaL
real GCaL=0.000175;
//Parameters for IbCa
real GbCa=0.000592;
//Parameters for INaCa
real knaca=1000;
real KmNai=87.5;
real KmCa=1.38;
real ksat=0.1;
real n=0.35;
//Parameters for IpCa
real GpCa=0.825;
real KpCa=0.0005;
//Parameters for IpK;
real GpK=0.0146;
real parameters []={13.6678942151156,0.000256568439836354,0.000168998708141810,0.000629430277377532,0.292179614925966,0.159025382216859,0.219408745068892,4.13026404897143,0.0228716387184266,2.64548400409568,1084.92169869363,0.000464164881016237,0.0900142389778237,0.0125301647159537,0.00898985291692117,1.90563632103728e-05};
GNa=parameters[0];
GbNa=parameters[1];
GCaL=parameters[2];
GbCa=parameters[3];
Gto=parameters[4];
Gkr=parameters[5];
Gks=parameters[6];
GK1=parameters[7];
GpK=parameters[8];
knak=parameters[9];
knaca=parameters[10];
Vmaxup=parameters[11];
GpCa=parameters[12];
real arel=parameters[13];
real crel=parameters[14];
real Vleak=parameters[15];
real IKr;
real IKs;
real IK1;
real Ito;
real INa;
real IbNa;
real ICaL;
real IbCa;
real INaCa;
real IpCa;
real IpK;
real INaK;
real Irel;
real Ileak;
real dNai;
real dKi;
real dCai;
real dCaSR;
real A;
// real BufferFactorc;
// real BufferFactorsr;
real SERCA;
real Caisquare;
real CaSRsquare;
real CaCurrent;
real CaSRCurrent;
real fcaold;
real gold;
real Ek;
real Ena;
real Eks;
real Eca;
real CaCSQN;
real bjsr;
real cjsr;
real CaBuf;
real bc;
real cc;
real Ak1;
real Bk1;
real rec_iK1;
real rec_ipK;
real rec_iNaK;
real AM;
real BM;
real AH_1;
real BH_1;
real AH_2;
real BH_2;
real AJ_1;
real BJ_1;
real AJ_2;
real BJ_2;
real M_INF;
real H_INF;
real J_INF;
real TAU_M;
real TAU_H;
real TAU_J;
real axr1;
real bxr1;
real axr2;
real bxr2;
real Xr1_INF;
real Xr2_INF;
real TAU_Xr1;
real TAU_Xr2;
real Axs;
real Bxs;
real Xs_INF;
real TAU_Xs;
real R_INF;
real TAU_R;
real S_INF;
real TAU_S;
real Ad;
real Bd;
real Cd;
real TAU_D;
real D_INF;
real TAU_F;
real F_INF;
real FCa_INF;
real G_INF;
real inverseVcF2=1/(2*Vc*F);
real inverseVcF=1./(Vc*F);
real Kupsquare=Kup*Kup;
// real BufcKbufc=Bufc*Kbufc;
// real Kbufcsquare=Kbufc*Kbufc;
// real Kbufc2=2*Kbufc;
// real BufsrKbufsr=Bufsr*Kbufsr;
// const real Kbufsrsquare=Kbufsr*Kbufsr;
// const real Kbufsr2=2*Kbufsr;
const real exptaufca=exp(-dt/taufca);
const real exptaug=exp(-dt/taug);
real sItot;
//Needed to compute currents
Ek=RTONF*(log((Ko/Ki)));
Ena=RTONF*(log((Nao/Nai)));
Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai)));
Eca=0.5*RTONF*(log((Cao/Cai)));
Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200)));
Bk1=(3.*exp(0.0002*(svolt-Ek+100))+
exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek)));
rec_iK1=Ak1/(Ak1+Bk1);
rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T))));
rec_ipK=1./(1.+exp((25-svolt)/5.98));
//Compute currents
INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena);
ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))*
(exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.);
Ito=Gto*sr*ss*(svolt-Ek);
IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek);
IKs=Gks*sxs*sxs*(svolt-Eks);
IK1=GK1*rec_iK1*(svolt-Ek);
INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))*
(1./(1+ksat*exp((n-1)*svolt*F/(R*T))))*
(exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao-
exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5);
INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK;
IpCa=GpCa*Cai/(KpCa+Cai);
IpK=GpK*rec_ipK*(svolt-Ek);
IbNa=GbNa*(svolt-Ena);
IbCa=GbCa*(svolt-Eca);
//Determine total current
(sItot) = IKr +
IKs +
IK1 +
Ito +
INa +
IbNa +
ICaL +
IbCa +
INaK +
INaCa +
IpCa +
IpK +
stim_current;
//update concentrations
Caisquare=Cai*Cai;
CaSRsquare=CaSR*CaSR;
CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE;
///A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f;
A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel;
Irel=A*sd*sg;
///Ileak=0.00008f*(CaSR-Cai);
Ileak=Vleak*(CaSR-Cai);
SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare));
CaSRCurrent=SERCA-Irel-Ileak;
CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr);
dCaSR=dt*(Vc/Vsr)*CaSRCurrent;
bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr;
cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR);
CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.;
CaBuf=Bufc*Cai/(Cai+Kbufc);
dCai=dt*(CaCurrent-CaSRCurrent);
bc=Bufc-CaBuf-dCai-Cai+Kbufc;
cc=Kbufc*(CaBuf+dCai+Cai);
Cai=(sqrt(bc*bc+4*cc)-bc)/2;
dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE;
Nai+=dt*dNai;
dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE;
Ki+=dt*dKi;
//compute steady state values and time constants
AM=1./(1.+exp((-60.-svolt)/5.));
BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.));
TAU_M=AM*BM;
M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03)));
if (svolt>=-40.)
{
AH_1=0.;
BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1))));
TAU_H= 1.0/(AH_1+BH_1);
}
else
{
AH_2=(0.057*exp(-(svolt+80.)/6.8));
BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt));
TAU_H=1.0/(AH_2+BH_2);
}
H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43)));
if(svolt>=-40.)
{
AJ_1=0.;
BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.))));
TAU_J= 1.0/(AJ_1+BJ_1);
}
else
{
AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)*
exp(-0.04391*svolt))*(svolt+37.78)/
(1.+exp(0.311*(svolt+79.23))));
BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14))));
TAU_J= 1.0/(AJ_2+BJ_2);
}
J_INF=H_INF;
Xr1_INF=1./(1.+exp((-26.-svolt)/7.));
axr1=450./(1.+exp((-45.-svolt)/10.));
bxr1=6./(1.+exp((svolt-(-30.))/11.5));
TAU_Xr1=axr1*bxr1;
Xr2_INF=1./(1.+exp((svolt-(-88.))/24.));
axr2=3./(1.+exp((-60.-svolt)/20.));
bxr2=1.12/(1.+exp((svolt-60.)/20.));
TAU_Xr2=axr2*bxr2;
Xs_INF=1./(1.+exp((-5.-svolt)/14.));
Axs=1100./(sqrt(1.+exp((-10.-svolt)/6)));
Bxs=1./(1.+exp((svolt-60.)/20.));
TAU_Xs=Axs*Bxs;
#ifdef EPI
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
#endif
#ifdef ENDO
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+28)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=1000.*exp(-(svolt+67)*(svolt+67)/1000.)+8.;
#endif
#ifdef MCELL
R_INF=1./(1.+exp((20-svolt)/6.));
S_INF=1./(1.+exp((svolt+20)/5.));
TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8;
TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.;
#endif
D_INF=1./(1.+exp((-5-svolt)/7.5));
Ad=1.4/(1.+exp((-35-svolt)/13))+0.25;
Bd=1.4/(1.+exp((svolt+5)/5));
Cd=1./(1.+exp((50-svolt)/20));
TAU_D=Ad*Bd+Cd;
F_INF=1./(1.+exp((svolt+20)/7));
TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10));
FCa_INF=(1./(1.+pow((Cai/0.000325),8))+
0.1/(1.+exp((Cai-0.0005)/0.0001))+
0.20/(1.+exp((Cai-0.00075)/0.0008))+
0.23 )/1.46;
if(Cai<0.00035)
G_INF=1./(1.+pow((Cai/0.00035),6));
else
G_INF=1./(1.+pow((Cai/0.00035),16));
//Update gates
rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M);
rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H);
rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J);
rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1);
rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2);
rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs);
rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S);
rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R);
rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D);
rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F);
fcaold= sfca;
sfca = FCa_INF-(FCa_INF-sfca)*exptaufca;
if(sfca>fcaold && (svolt)>-37.0)
sfca = fcaold;
gold = sg;
sg = G_INF-(G_INF-sg)*exptaug;
if(sg>gold && (svolt)>-37.0)
sg=gold;
//update voltage
rDY_[0] = svolt + dt*(-sItot);
rDY_[11] = sfca;
rDY_[12] = sg;
rDY_[13] = Cai;
rDY_[14] = CaSR;
rDY_[15] = Nai;
rDY_[16] = Ki;
}
|
vadd.base.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <omp.h>
double getClock()
{
struct timezone tzp;
struct timeval tp;
gettimeofday (&tp, &tzp);
return (tp.tv_sec + tp.tv_usec*1.0e-6);
}
int main(int argc, char *argv[])
{
double *y;
double *x1;
double *x2;
double *x3;
int n = N;
{
int i1;
y = (double*) malloc((n) * sizeof(double));
x1 = (double*) malloc((n) * sizeof(double));
x2 = (double*) malloc((n) * sizeof(double));
x3 = (double*) malloc((n) * sizeof(double));
for (i1=0; i1<n; i1++) {
x1[i1] = (i1+1) % 4 + 1;
x2[i1] = (i1+5) % 10 + 1;
x3[i1] = (i1+3) % 6 + 1;
y[i1] = 0;
}
}
double orio_t_start, orio_t_end, orio_t_total=0;
int orio_i;
int reps = REPS;
#ifdef TEST
reps = 1;
#endif
orio_t_start = getClock();
for (orio_i=0; orio_i<reps; orio_i++)
{
int i;
#pragma omp parallel for
for (i=0; i<=n-1; i++)
y[i]=x1[i]+x2[i]+x3[i];
}
orio_t_end = getClock();
orio_t_total = orio_t_end - orio_t_start;
orio_t_total = orio_t_total / REPS;
double mflops = (8.0*N)/(orio_t_total*1000000);
#ifdef TEST
{
int i;
for (i=0; i<=n-1; i++) {
if (i%10 == 0)
printf("\n");
printf("%f ",y[i]);
}
}
#else
printf("%f\t%f\n", orio_t_total, mflops);
#endif
return y[0];
}
|
eavlSourceTopologyMapOp.h | // Copyright 2010-2014 UT-Battelle, LLC. See LICENSE.txt for more information.
#ifndef EAVL_SOURCE_TOPOLOGY_MAP_OP_H
#define EAVL_SOURCE_TOPOLOGY_MAP_OP_H
#include "eavlCUDA.h"
#include "eavlCellSet.h"
#include "eavlCellSetExplicit.h"
#include "eavlCellSetAllStructured.h"
#include "eavlDataSet.h"
#include "eavlArray.h"
#include "eavlOpDispatch.h"
#include "eavlOperation.h"
#include "eavlTopology.h"
#include "eavlException.h"
#include <time.h>
#ifdef HAVE_OPENMP
#include <omp.h>
#endif
#ifndef DOXYGEN
template <class CONN>
struct eavlSourceTopologyMapOp_CPU
{
static inline eavlArray::Location location() { return eavlArray::HOST; }
template <class F, class IN, class OUT>
static void call(int nitems, CONN &conn,
const IN s_inputs, OUT outputs, F &functor)
{
int ids[MAX_LOCAL_TOPOLOGY_IDS];
#pragma omp parallel for private(ids)
for (int index = 0; index < nitems; ++index)
{
int nids;
int shapeType = conn.GetElementComponents(index, nids, ids);
collect(index, outputs) = functor(shapeType, nids, ids, s_inputs);
}
}
};
#if defined __CUDACC__
template <class CONN, class F, class IN, class OUT>
__global__ void
eavlSourceTopologyMapOp_kernel(int nitems, CONN conn,
const IN s_inputs, OUT outputs, F functor)
{
const int numThreads = blockDim.x * gridDim.x;
const int threadID = blockIdx.x * blockDim.x + threadIdx.x;
int ids[MAX_LOCAL_TOPOLOGY_IDS];
for (int index = threadID; index < nitems; index += numThreads)
{
int nids;
int shapeType = conn.GetElementComponents(index, nids, ids);
collect(index, outputs) = functor(shapeType, nids, ids, s_inputs);
}
}
template <class CONN>
struct eavlSourceTopologyMapOp_GPU
{
static inline eavlArray::Location location() { return eavlArray::DEVICE; }
template <class F, class IN, class OUT>
static void call(int nitems, CONN &conn,
const IN s_inputs, OUT outputs, F &functor)
{
int numThreads = 256;
dim3 threads(numThreads, 1, 1);
dim3 blocks (32, 1, 1);
eavlSourceTopologyMapOp_kernel<<< blocks, threads >>>(nitems, conn,
s_inputs, outputs, functor);
CUDA_CHECK_ERROR();
}
};
#endif
#endif
// ****************************************************************************
// Class: eavlSourceTopologyMapOp
//
// Purpose:
/// Map from one topological element in a mesh to another, with
/// input arrays on the source topology and with outputs
/// on the destination topology. (If you need inputs on the
/// destination topology as well, use eavlCombinedTopologyMap.)
//
// Programmer: Jeremy Meredith
// Creation: July 26, 2013
//
// Modifications:
// ****************************************************************************
template <class IS, class O, class F>
class eavlSourceTopologyMapOp : public eavlOperation
{
protected:
eavlCellSet *cells;
eavlTopology topology;
IS s_inputs;
O outputs;
F functor;
public:
eavlSourceTopologyMapOp(eavlCellSet *c, eavlTopology t,
IS is, O o, F f)
: cells(c), topology(t), s_inputs(is), outputs(o), functor(f)
{
}
virtual void GoCPU()
{
eavlCellSetExplicit *elExp = dynamic_cast<eavlCellSetExplicit*>(cells);
eavlCellSetAllStructured *elStr = dynamic_cast<eavlCellSetAllStructured*>(cells);
int n = outputs.first.length();
if (elExp)
{
eavlExplicitConnectivity &conn = elExp->GetConnectivity(topology);
eavlOpDispatch<eavlSourceTopologyMapOp_CPU<eavlExplicitConnectivity> >(n, conn, s_inputs, outputs, functor);
}
else if (elStr)
{
eavlRegularConnectivity conn = eavlRegularConnectivity(elStr->GetRegularStructure(),topology);
eavlOpDispatch<eavlSourceTopologyMapOp_CPU<eavlRegularConnectivity> >(n, conn, s_inputs, outputs, functor);
}
}
virtual void GoGPU()
{
#ifdef HAVE_CUDA
eavlCellSetExplicit *elExp = dynamic_cast<eavlCellSetExplicit*>(cells);
eavlCellSetAllStructured *elStr = dynamic_cast<eavlCellSetAllStructured*>(cells);
int n = outputs.first.length();
if (elExp)
{
eavlExplicitConnectivity &conn = elExp->GetConnectivity(topology);
conn.shapetype.NeedOnDevice();
conn.connectivity.NeedOnDevice();
conn.mapCellToIndex.NeedOnDevice();
eavlOpDispatch<eavlSourceTopologyMapOp_GPU<eavlExplicitConnectivity> >(n, conn, s_inputs, outputs, functor);
conn.shapetype.NeedOnHost();
conn.connectivity.NeedOnHost();
conn.mapCellToIndex.NeedOnHost();
}
else if (elStr)
{
eavlRegularConnectivity conn = eavlRegularConnectivity(elStr->GetRegularStructure(),topology);
eavlOpDispatch<eavlSourceTopologyMapOp_GPU<eavlRegularConnectivity> >(n, conn, s_inputs, outputs, functor);
}
#else
THROW(eavlException,"Executing GPU code without compiling under CUDA compiler.");
#endif
}
};
// helper function for type deduction
template <class IS, class O, class F>
eavlSourceTopologyMapOp<IS,O,F> *new_eavlSourceTopologyMapOp(eavlCellSet *c, eavlTopology t,
IS is, O o, F f)
{
return new eavlSourceTopologyMapOp<IS,O,F>(c,t,is,o,f);
}
#endif
|
GB_binop__second_int64.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__second_int64)
// A.*B function (eWiseMult): GB (_AemultB_08__second_int64)
// A.*B function (eWiseMult): GB (_AemultB_02__second_int64)
// A.*B function (eWiseMult): GB (_AemultB_04__second_int64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__second_int64)
// A*D function (colscale): GB (_AxD__second_int64)
// D*A function (rowscale): GB (_DxB__second_int64)
// C+=B function (dense accum): GB (_Cdense_accumB__second_int64)
// C+=b function (dense accum): GB (_Cdense_accumb__second_int64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__second_int64)
// C=scalar+B GB ((none))
// C=scalar+B' GB ((none))
// C=A+scalar GB ((none))
// C=A'+scalar GB ((none))
// C type: int64_t
// A type: int64_t
// A pattern? 1
// B type: int64_t
// B pattern? 0
// BinaryOp: cij = bij
#define GB_ATYPE \
int64_t
#define GB_BTYPE \
int64_t
#define GB_CTYPE \
int64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
;
// true if values of A are not used
#define GB_A_IS_PATTERN \
1 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int64_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = y ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
1
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_SECOND || GxB_NO_INT64 || GxB_NO_SECOND_INT64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__second_int64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__second_int64)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__second_int64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type int64_t
int64_t bwork = (*((int64_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__second_int64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *restrict Cx = (int64_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__second_int64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *restrict Cx = (int64_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__second_int64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
int64_t alpha_scalar ;
int64_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int64_t *) alpha_scalar_in)) ;
beta_scalar = (*((int64_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__second_int64)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__second_int64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__second_int64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__second_int64)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *Cx = (int64_t *) Cx_output ;
int64_t x = (*((int64_t *) x_input)) ;
int64_t *Bx = (int64_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
int64_t bij = GBX (Bx, p, false) ;
Cx [p] = bij ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
int64_t *Cx = (int64_t *) Cx_output ;
int64_t *Ax = (int64_t *) Ax_input ;
int64_t y = (*((int64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
; ;
Cx [p] = y ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = aij ; \
}
GrB_Info GB ((none))
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t x = (*((const int64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int64_t
}
#endif
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
; ; \
Cx [pC] = y ; \
}
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t y = (*((const int64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
#endif
|
core_zttmlq.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @precisions normal z -> c d s
*
**/
#include <plasma_core_blas.h>
#include "plasma_types.h"
#include "plasma_internal.h"
#include "core_lapack.h"
#include <omp.h>
/***************************************************************************//**
*
* @ingroup core_ttmlq
*
* Overwrites the general complex m1-by-n1 tile A1 and
* m2-by-n2 tile A2 with
*
* side = PlasmaLeft side = PlasmaRight
* trans = PlasmaNoTrans Q * | A1 | | A1 A2 | * Q
* | A2 |
*
* trans = Plasma_ConjTrans Q^H * | A1 | | A1 A2 | * Q^H
* | A2 |
*
* where Q is a complex unitary matrix defined as the product of k
* elementary reflectors
*
* Q = H(k)^H . . . H(2)^H H(1)^H
*
* as returned by plasma_core_zttlqt.
*
*******************************************************************************
*
* @param[in] side
* - PlasmaLeft : apply Q or Q^H from the Left;
* - PlasmaRight : apply Q or Q^H from the Right.
*
* @param[in] trans
* - PlasmaNoTrans : Apply Q;
* - Plasma_ConjTrans : Apply Q^H.
*
* @param[in] m1
* The number of rows of the tile A1. m1 >= 0.
*
* @param[in] n1
* The number of columns of the tile A1. n1 >= 0.
*
* @param[in] m2
* The number of rows of the tile A2. m2 >= 0.
*
* @param[in] n2
* The number of columns of the tile A2. n2 >= 0.
*
* @param[in] k
* The number of elementary reflectors whose product defines
* the matrix Q.
*
* @param[in] ib
* The inner-blocking size. ib >= 0.
*
* @param[in,out] A1
* On entry, the m1-by-n1 tile A1.
* On exit, A1 is overwritten by the application of Q.
*
* @param[in] lda1
* The leading dimension of the array A1. lda1 >= max(1,m1).
*
* @param[in,out] A2
* On entry, the m2-by-n2 tile A2.
* On exit, A2 is overwritten by the application of Q.
*
* @param[in] lda2
* The leading dimension of the tile A2. lda2 >= max(1,m2).
*
* @param[in] V
* The i-th row must contain the vector which defines the
* elementary reflector H(i), for i = 1,2,...,k, as returned by
* plasma_core_zttlqt in the first k rows of its array argument V.
*
* @param[in] ldv
* The leading dimension of the array V. ldv >= max(1,k).
*
* @param[out] T
* The ib-by-k triangular factor T of the block reflector.
* T is upper triangular by block (economic storage);
* The rest of the array is not referenced.
*
* @param[in] ldt
* The leading dimension of the array T. ldt >= ib.
*
* @param work
* Auxiliary workspace array of length
* ldwork-by-m1 if side == PlasmaLeft
* ldwork-by-ib if side == PlasmaRight
*
* @param[in] ldwork
* The leading dimension of the array work.
* ldwork >= max(1,ib) if side == PlasmaLeft
* ldwork >= max(1,n1) if side == PlasmaRight
*
*******************************************************************************
*
* @retval PlasmaSuccess successful exit
* @retval < 0 if -i, the i-th argument had an illegal value
*
******************************************************************************/
__attribute__((weak))
int plasma_core_zttmlq(plasma_enum_t side, plasma_enum_t trans,
int m1, int n1, int m2, int n2, int k, int ib,
plasma_complex64_t *A1, int lda1,
plasma_complex64_t *A2, int lda2,
const plasma_complex64_t *V, int ldv,
const plasma_complex64_t *T, int ldt,
plasma_complex64_t *work, int ldwork)
{
// Check input arguments.
if (side != PlasmaLeft && side != PlasmaRight) {
plasma_coreblas_error("illegal value of side");
return -1;
}
if (trans != PlasmaNoTrans && trans != Plasma_ConjTrans) {
plasma_coreblas_error("illegal value of trans");
return -2;
}
if (m1 < 0) {
plasma_coreblas_error("illegal value of m1");
return -3;
}
if (n1 < 0) {
plasma_coreblas_error("illegal value of n1");
return -4;
}
if (m2 < 0 || (m2 != m1 && side == PlasmaRight)) {
plasma_coreblas_error("illegal value of m2");
return -5;
}
if (n2 < 0 || (n2 != n1 && side == PlasmaLeft)) {
plasma_coreblas_error("illegal value of n2");
return -6;
}
if (k < 0 ||
(side == PlasmaLeft && k > m1 ) ||
(side == PlasmaRight && k > n1)) {
plasma_coreblas_error("illegal value of k");
return -7;
}
if (ib < 0) {
plasma_coreblas_error("illegal value of ib");
return -8;
}
if (A1 == NULL) {
plasma_coreblas_error("NULL A1");
return -9;
}
if (lda1 < imax(1, m1)) {
plasma_coreblas_error("illegal value of lda1");
return -10;
}
if (A2 == NULL) {
plasma_coreblas_error("NULL A2");
return -11;
}
if (lda2 < imax(1, m2)) {
plasma_coreblas_error("illegal value of lda2");
return -12;
}
if (V == NULL) {
plasma_coreblas_error("NULL V");
return -13;
}
if (ldv < imax(1, k)) {
plasma_coreblas_error("illegal value of ldv");
return -14;
}
if (T == NULL) {
plasma_coreblas_error("NULL T");
return -15;
}
if (ldt < imax(1, ib)) {
plasma_coreblas_error("illegal value of ldt");
return -16;
}
if (work == NULL) {
plasma_coreblas_error("NULL work");
return -17;
}
if (ldwork < imax(1, side == PlasmaLeft ? ib : n1)) {
plasma_coreblas_error("illegal value of ldwork");
return -18;
}
// quick return
if (m1 == 0 || n1 == 0 || m2 == 0 || n2 == 0 || k == 0 || ib == 0)
return PlasmaSuccess;
int i1, i3;
if (((side == PlasmaLeft) && (trans == PlasmaNoTrans)) ||
((side == PlasmaRight) && (trans != PlasmaNoTrans))) {
i1 = 0;
i3 = ib;
}
else {
i1 = ((k-1)/ib)*ib;
i3 = -ib;
}
if (trans == PlasmaNoTrans)
trans = Plasma_ConjTrans;
else
trans = PlasmaNoTrans;
for (int i = i1; (i > -1) && (i < k); i += i3) {
int kb = imin(ib, k-i);
int ic = 0;
int jc = 0;
int mi = m1;
int mi2 = m2;
int ni = n1;
int ni2 = n2;
int l;
if (side == PlasmaLeft) {
mi = kb; // m1 - i;
mi2 = imin(i+kb, m2);
l = imin(kb, imax(0, m2-i));
ic = i;
}
else {
ni = kb;
ni2 = imin(i+kb, n2);
l = imin(kb, imax(0, n2-i));
jc = i;
}
// Apply H or H^H.
plasma_core_zparfb(
side, trans, PlasmaForward, PlasmaRowwise,
mi, ni, mi2, ni2, kb, l,
&A1[lda1*jc+ic], lda1,
A2, lda2,
&V[i], ldv,
&T[ldt*i], ldt,
work, ldwork);
}
return PlasmaSuccess;
}
/******************************************************************************/
void plasma_core_omp_zttmlq(plasma_enum_t side, plasma_enum_t trans,
int m1, int n1, int m2, int n2, int k, int ib,
plasma_complex64_t *A1, int lda1,
plasma_complex64_t *A2, int lda2,
const plasma_complex64_t *V, int ldv,
const plasma_complex64_t *T, int ldt,
plasma_workspace_t work,
plasma_sequence_t *sequence, plasma_request_t *request)
{
#pragma omp task depend(inout:A1[0:lda1*n1]) \
depend(inout:A2[0:lda2*n2]) \
depend(in:V[0:ldv*n2]) \
depend(in:T[0:ib*k])
{
if (sequence->status == PlasmaSuccess) {
// Prepare workspaces.
int tid = omp_get_thread_num();
plasma_complex64_t *W = (plasma_complex64_t*)work.spaces[tid];
int ldwork = side == PlasmaLeft ? ib : n1; // TODO: double check
// Call the kernel.
int info = plasma_core_zttmlq(side, trans,
m1, n1, m2, n2, k, ib,
A1, lda1,
A2, lda2,
V, ldv,
T, ldt,
W, ldwork);
if (info != PlasmaSuccess) {
plasma_error("core_zttmlq() failed");
plasma_request_fail(sequence, request, PlasmaErrorInternal);
}
}
}
}
|
npdot.c | /* Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*
* Author: Qiming Sun <osirpt.sun@gmail.com>
*/
#include <stdlib.h>
#include <string.h>
#include <complex.h>
//#include <omp.h>
#include "config.h"
#include "vhf/fblas.h"
#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
/*
* numpy.dot may call unoptimized blas
*/
void NPdgemm(const char trans_a, const char trans_b,
const int m, const int n, const int k,
const int lda, const int ldb, const int ldc,
const int offseta, const int offsetb, const int offsetc,
double *a, double *b, double *c,
const double alpha, const double beta)
{
const size_t dimc = ldc;
int i, j;
if (m == 0 || n == 0) {
return;
} else if (k == 0) {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
c[i*dimc+j] = 0;
} }
return;
}
a += offseta;
b += offsetb;
c += offsetc;
if ((k/m) > 3 && (k/n) > 3) { // parallelize k
if (beta == 0) {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
c[i*dimc+j] = 0;
}
}
} else {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
c[i*dimc+j] *= beta;
}
}
}
#pragma omp parallel default(none) shared(a, b, c) \
private(i, j)
{
int nthread = omp_get_num_threads();
int nblk = MAX((k+nthread-1) / nthread, 1);
double D0 = 0;
double *cpriv = malloc(sizeof(double) * (m*n+2));
int di;
size_t ij;
size_t astride = nblk;
size_t bstride = nblk;
if (trans_a == 'N') {
astride *= lda;
}
if (trans_b != 'N') {
bstride *= ldb;
}
#pragma omp for
for (i = 0; i < nthread; i++) {
di = MIN(nblk, k-i*nblk);
if (di > 0) {
dgemm_(&trans_a, &trans_b, &m, &n, &di,
&alpha, a+astride*i, &lda,
b+bstride*i, &ldb,
&D0, cpriv, &m);
}
}
#pragma omp critical
if (di > 0) {
for (ij = 0, i = 0; i < n; i++) {
for (j = 0; j < m; j++, ij++) {
c[i*dimc+j] += cpriv[ij];
}
}
}
free(cpriv);
}
} else if (m > n*2) { // parallelize m
#pragma omp parallel default(none) shared(a, b, c)
{
int nthread = omp_get_num_threads();
int nblk = MAX((m+nthread-1) / nthread, 1);
nthread = (m+nblk-1) / nblk;
int di;
size_t bstride = nblk;
if (trans_a != 'N') {
bstride *= lda;
}
#pragma omp for
for (i = 0; i < nthread; i++) {
di = MIN(nblk, m-i*nblk);
if (di > 0) {
dgemm_(&trans_a, &trans_b, &di, &n, &k,
&alpha, a+bstride*i, &lda, b, &ldb,
&beta, c+i*nblk, &ldc);
}
}
}
} else { // parallelize n
#pragma omp parallel default(none) shared(a, b, c)
{
int nthread = omp_get_num_threads();
int nblk = MAX((n+nthread-1) / nthread, 1);
nthread = (n+nblk-1) / nblk;
int di;
size_t bstride = nblk;
size_t cstride = dimc * nblk;
if (trans_b == 'N') {
bstride *= ldb;
}
#pragma omp for
for (i = 0; i < nthread; i++) {
di = MIN(nblk, n-i*nblk);
if (di > 0) {
dgemm_(&trans_a, &trans_b, &m, &di, &k,
&alpha, a, &lda, b+bstride*i, &ldb,
&beta, c+cstride*i, &ldc);
}
}
}
}
}
void NPzgemm(const char trans_a, const char trans_b,
const int m, const int n, const int k,
const int lda, const int ldb, const int ldc,
const int offseta, const int offsetb, const int offsetc,
double complex *a, double complex *b, double complex *c,
const double complex *alpha, const double complex *beta)
{
const size_t dimc = ldc;
int i, j;
if (m == 0 || n == 0) {
return;
} else if (k == 0) {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
c[i*dimc+j] = 0;
} }
return;
}
a += offseta;
b += offsetb;
c += offsetc;
if ((k/m) > 3 && (k/n) > 3) { // parallelize k
if (creal(*beta) == 0 && cimag(*beta) == 0) {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
c[i*dimc+j] = 0;
}
}
} else {
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
c[i*dimc+j] *= beta[0];
}
}
}
#pragma omp parallel default(none) shared(a, b, c, alpha) \
private(i, j)
{
int nthread = omp_get_num_threads();
int nblk = MAX((k+nthread-1) / nthread, 1);
double complex Z0 = 0;
double complex *cpriv = malloc(sizeof(double complex) * (m*n+2));
int di;
size_t ij;
size_t astride = nblk;
size_t bstride = nblk;
if (trans_a == 'N') {
astride *= lda;
}
if (trans_b != 'N') {
bstride *= ldb;
}
#pragma omp for
for (i = 0; i < nthread; i++) {
di = MIN(nblk, k-i*nblk);
if (di > 0) {
zgemm_(&trans_a, &trans_b, &m, &n, &di,
alpha, a+astride*i, &lda,
b+bstride*i, &ldb,
&Z0, cpriv, &m);
}
}
#pragma omp critical
if (di > 0) {
for (ij = 0, i = 0; i < n; i++) {
for (j = 0; j < m; j++, ij++) {
c[i*dimc+j] += cpriv[ij];
}
}
}
free(cpriv);
}
} else if (m > n*2) { // parallelize m
#pragma omp parallel default(none) shared(a, b, c, alpha, beta)
{
int nthread = omp_get_num_threads();
int nblk = MAX((m+nthread-1) / nthread, 1);
nthread = (m+nblk-1) / nblk;
int di;
size_t bstride = nblk;
if (trans_a != 'N') {
bstride *= lda;
}
#pragma omp for
for (i = 0; i < nthread; i++) {
di = MIN(nblk, m-i*nblk);
if (di > 0) {
zgemm_(&trans_a, &trans_b, &di, &n, &k,
alpha, a+bstride*i, &lda, b, &ldb,
beta, c+i*nblk, &ldc);
}
}
}
} else { // parallelize n
#pragma omp parallel default(none) shared(a, b, c, alpha, beta)
{
int nthread = omp_get_num_threads();
int nblk = MAX((n+nthread-1) / nthread, 1);
nthread = (n+nblk-1) / nblk;
int di;
size_t bstride = nblk;
size_t cstride = dimc * nblk;
if (trans_b == 'N') {
bstride *= ldb;
}
#pragma omp for
for (i = 0; i < nthread; i++) {
di = MIN(nblk, n-i*nblk);
if (di > 0) {
zgemm_(&trans_a, &trans_b, &m, &di, &k,
alpha, a, &lda, b+bstride*i, &ldb,
beta, c+cstride*i, &ldc);
}
}
}
}
}
|
GB_binop__minus_int32.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB_AaddB__minus_int32
// A.*B function (eWiseMult): GB_AemultB__minus_int32
// A*D function (colscale): GB_AxD__minus_int32
// D*A function (rowscale): GB_DxB__minus_int32
// C+=B function (dense accum): GB_Cdense_accumB__minus_int32
// C+=b function (dense accum): GB_Cdense_accumb__minus_int32
// C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__minus_int32
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__minus_int32
// C=scalar+B GB_bind1st__minus_int32
// C=scalar+B' GB_bind1st_tran__minus_int32
// C=A+scalar GB_bind2nd__minus_int32
// C=A'+scalar GB_bind2nd_tran__minus_int32
// C type: int32_t
// A type: int32_t
// B,b type: int32_t
// BinaryOp: cij = (aij - bij)
#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) \
int32_t 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, i, j) \
z = (x - y) ;
// op is second
#define GB_OP_IS_SECOND \
0
// op is plus_fp32 or plus_fp64
#define GB_OP_IS_PLUS_REAL \
0
// op is minus_fp32 or minus_fp64
#define GB_OP_IS_MINUS_REAL \
0
// GB_cblas_*axpy gateway routine, if it exists for this operator and type:
#define GB_CBLAS_AXPY \
(none)
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINUS || GxB_NO_INT32 || GxB_NO_MINUS_INT32)
//------------------------------------------------------------------------------
// 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__minus_int32
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__minus_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__minus_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
{
#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__minus_int32
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type int32_t
int32_t bwork = (*((int32_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__minus_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__minus_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
//------------------------------------------------------------------------------
#undef GB_FREE_ALL
#define GB_FREE_ALL \
{ \
GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \
GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \
GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \
}
GrB_Info GB_AaddB__minus_int32
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ;
int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ;
int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ;
#include "GB_add_template.c"
GB_FREE_ALL ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB_AemultB__minus_int32
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ;
int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ;
int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ;
#include "GB_emult_template.c"
GB_FREE_ALL ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB_bind1st__minus_int32
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *GB_RESTRICT Bb,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
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++)
{
if (!GBB (Bb, p)) continue ;
int32_t bij = Bx [p] ;
Cx [p] = (x - bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__minus_int32
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *GB_RESTRICT Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
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++)
{
if (!GBB (Ab, p)) continue ;
int32_t aij = Ax [p] ;
Cx [p] = (aij - y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int32_t aij = Ax [pA] ; \
Cx [pC] = (x - aij) ; \
}
GrB_Info GB_bind1st_tran__minus_int32
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_RESTRICT A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t x = (*((const int32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int32_t aij = Ax [pA] ; \
Cx [pC] = (aij - y) ; \
}
GrB_Info GB_bind2nd_tran__minus_int32
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_RESTRICT A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t y = (*((const int32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
project.c | //-----------------------------------------------------------------------------
// project.c
//
// Project: EPA SWMM5
// Version: 5.1
// Date: 03/19/14 (Build 5.1.000)
// 04/14/14 (Build 5.1.004)
// 09/15/14 (Build 5.1.007)
// 03/19/15 (Build 5.1.008)
// 04/30/15 (Build 5.1.009)
// 08/01/16 (Build 5.1.011)
// 03/14/17 (Build 5.1.012)
// 05/10/18 (Build 5.1.013)
// Author: L. Rossman
//
// Project management functions.
//
// This module provides project-related services such as:
// o opening a new project and reading its input data
// o allocating and freeing memory for project objects
// o setting default values for object properties and options
// o initializing the internal state of all objects
// o managing hash tables for identifying objects by ID name
//
// Build 5.1.004:
// - Ignore RDII option added.
//
// Build 5.1.007:
// - Default monthly adjustments for climate variables included.
// - User-supplied GW flow equations initialized to NULL.
// - Storage node exfiltration object initialized to NULL.
// - Freeing of memory used for storage node exfiltration included.
//
// Build 5.1.008:
// - Constants used for dynamic wave routing moved to dynwave.c.
// - Input processing of minimum time step & number of
// parallel threads for dynamic wave routing added.
// - Default values of hyd. conductivity adjustments added.
// - Freeing of memory used for outfall pollutant load added.
//
// Build 5.1.009:
// - Fixed bug in computing total duration introduced in 5.1.008.
//
// Build 5.1.011:
// - Memory management of hydraulic event dates array added.
//
// Build 5.1.012:
// - Minimum conduit slope option initialized to 0 (none).
// - NO/YES no longer accepted as options for NORMAL_FLOW_LIMITED.
//
// Build 5.1.013:
// - omp_get_num_threads function protected against lack of compiler
// support for OpenMP.
// - Rain gage validation now performed after subcatchment validation.
// - More robust parsing of MinSurfarea option provided.
// - Support added for new RuleStep analysis option.
//
//-----------------------------------------------------------------------------
#define _CRT_SECURE_NO_DEPRECATE
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#if defined(_OPENMP) //(5.1.013)
#include <omp.h> //
#else //
int omp_get_num_threads(void) { return 1;} //
#endif //
#include "headers.h"
#include "lid.h"
#include "hash.h"
#include "mempool.h"
//-----------------------------------------------------------------------------
// Shared variables
//-----------------------------------------------------------------------------
static HTtable* Htable[MAX_OBJ_TYPES]; // Hash tables for object ID names
static char MemPoolAllocated; // TRUE if memory pool allocated
//-----------------------------------------------------------------------------
// External Functions (declared in funcs.h)
//-----------------------------------------------------------------------------
// project_open (called from swmm_open in swmm5.c)
// project_close (called from swmm_close in swmm5.c)
// project_readInput (called from swmm_open in swmm5.c)
// project_readOption (called from readOption in input.c)
// project_validate (called from swmm_open in swmm5.c)
// project_init (called from swmm_start in swmm5.c)
// project_addObject (called from addObject in input.c)
// project_createMatrix (called from openFileForInput in iface.c)
// project_freeMatrix (called from iface_closeRoutingFiles)
// project_findObject
// project_findID
//-----------------------------------------------------------------------------
// Function declarations
//-----------------------------------------------------------------------------
static void initPointers(void);
static void setDefaults(void);
static void openFiles(char *f1, char *f2, char *f3);
static void createObjects(void);
static void deleteObjects(void);
static void createHashTables(void);
static void deleteHashTables(void);
//=============================================================================
void project_open(char *f1, char *f2, char *f3)
//
// Input: f1 = pointer to name of input file
// f2 = pointer to name of report file
// f3 = pointer to name of binary output file
// Output: none
// Purpose: opens a new SWMM project.
//
{
initPointers();
setDefaults();
openFiles(f1, f2, f3);
}
//=============================================================================
void project_readInput()
//
// Input: none
// Output: none
// Purpose: retrieves project data from input file.
//
{
// --- create hash tables for fast retrieval of objects by ID names
createHashTables();
// --- count number of objects in input file and create them
input_countObjects();
createObjects();
// --- read project data from input file
input_readData();
if ( ErrorCode ) return;
// --- establish starting & ending date/time
StartDateTime = StartDate + StartTime;
EndDateTime = EndDate + EndTime;
ReportStart = ReportStartDate + ReportStartTime;
ReportStart = MAX(ReportStart, StartDateTime);
// --- check for valid starting & ending date/times
if ( EndDateTime <= StartDateTime )
{
report_writeErrorMsg(ERR_START_DATE, "");
}
else if ( EndDateTime <= ReportStart )
{
report_writeErrorMsg(ERR_REPORT_DATE, "");
}
else
{
// --- compute total duration of simulation in seconds
double durationDate = EndDate - StartDate;
double durationTime = EndTime - StartTime;
TotalDuration = floor(durationDate * SECperDAY + durationTime * SECperDAY);
// --- reporting step must be <= total duration
if ( (double)ReportStep > TotalDuration )
{
ReportStep = (int)(TotalDuration);
}
// --- reporting step can't be < routing step
if ( (double)ReportStep < RouteStep )
{
report_writeErrorMsg(ERR_REPORT_STEP, "");
}
// --- convert total duration to milliseconds
TotalDuration *= 1000.0;
}
}
//=============================================================================
void project_validate()
//
// Input: none
// Output: none
// Purpose: checks validity of project data.
//
{
int i;
int j;
int err;
// --- validate Curves and TimeSeries
for ( i=0; i<Nobjects[CURVE]; i++ )
{
err = table_validate(&Curve[i]);
if ( err ) report_writeErrorMsg(ERR_CURVE_SEQUENCE, Curve[i].ID);
}
for ( i=0; i<Nobjects[TSERIES]; i++ )
{
err = table_validate(&Tseries[i]);
if ( err ) report_writeTseriesErrorMsg(err, &Tseries[i]);
}
// --- validate hydrology objects
// (NOTE: order is important !!!!)
climate_validate();
lid_validate();
if ( Nobjects[SNOWMELT] == 0 ) IgnoreSnowmelt = TRUE;
if ( Nobjects[AQUIFER] == 0 ) IgnoreGwater = TRUE;
for ( i=0; i<Nobjects[AQUIFER]; i++ ) gwater_validateAquifer(i);
for ( i=0; i<Nobjects[SUBCATCH]; i++ ) subcatch_validate(i);
for ( i=0; i<Nobjects[GAGE]; i++ ) gage_validate(i); //(5.1.013)
for ( i=0; i<Nobjects[SNOWMELT]; i++ ) snow_validateSnowmelt(i);
// --- compute geometry tables for each shape curve
j = 0;
for ( i=0; i<Nobjects[CURVE]; i++ )
{
if ( Curve[i].curveType == SHAPE_CURVE )
{
Curve[i].refersTo = j;
Shape[j].curve = i;
if ( !shape_validate(&Shape[j], &Curve[i]) )
report_writeErrorMsg(ERR_CURVE_SEQUENCE, Curve[i].ID);
j++;
}
}
// --- validate links before nodes, since the latter can
// result in adjustment of node depths
for ( i=0; i<Nobjects[NODE]; i++) Node[i].oldDepth = Node[i].fullDepth;
for ( i=0; i<Nobjects[LINK]; i++) link_validate(i);
for ( i=0; i<Nobjects[NODE]; i++) node_validate(i);
// --- adjust time steps if necessary
if ( DryStep < WetStep )
{
report_writeWarningMsg(WARN06, "");
DryStep = WetStep;
}
if ( RouteStep > (double)WetStep )
{
report_writeWarningMsg(WARN07, "");
RouteStep = WetStep;
}
// --- adjust individual reporting flags to match global reporting flag
if ( RptFlags.subcatchments == ALL )
for (i=0; i<Nobjects[SUBCATCH]; i++) Subcatch[i].rptFlag = TRUE;
if ( RptFlags.nodes == ALL )
for (i=0; i<Nobjects[NODE]; i++) Node[i].rptFlag = TRUE;
if ( RptFlags.links == ALL )
for (i=0; i<Nobjects[LINK]; i++) Link[i].rptFlag = TRUE;
// --- validate dynamic wave options
if ( RouteModel == DW ) dynwave_validate();
// --- adjust number of parallel threads to be used //(5.1.013)
#pragma omp parallel //(5.1.008)
{
if ( NumThreads == 0 ) NumThreads = omp_get_num_threads(); //(5.1.008)
else NumThreads = MIN(NumThreads, omp_get_num_threads()); //(5.1.008)
}
if ( Nobjects[LINK] < 4 * NumThreads ) NumThreads = 1; //(5.1.008)
}
//=============================================================================
void project_close()
//
// Input: none
// Output: none
// Purpose: closes a SWMM project.
//
{
deleteObjects();
deleteHashTables();
}
//=============================================================================
int project_init(void)
//
// Input: none
// Output: returns an error code
// Purpose: initializes the internal state of all objects.
//
{
int j;
climate_initState();
lid_initState();
for (j=0; j<Nobjects[TSERIES]; j++) table_tseriesInit(&Tseries[j]);
for (j=0; j<Nobjects[GAGE]; j++) gage_initState(j);
for (j=0; j<Nobjects[SUBCATCH]; j++) subcatch_initState(j);
for (j=0; j<Nobjects[NODE]; j++) node_initState(j);
for (j=0; j<Nobjects[LINK]; j++) link_initState(j);
return ErrorCode;
}
//=============================================================================
int project_addObject(int type, char *id, int n)
//
// Input: type = object type
// id = object ID string
// n = object index
// Output: returns 0 if object already added, 1 if not, -1 if hashing fails
// Purpose: adds an object ID to a hash table
//
{
int result;
int len;
char *newID;
// --- do nothing if object already placed in hash table
if ( project_findObject(type, id) >= 0 ) return 0;
// --- use memory from the hash tables' common memory pool to store
// a copy of the object's ID string
len = strlen(id) + 1;
newID = (char *) Alloc(len*sizeof(char));
strcpy(newID, id);
// --- insert object's ID into the hash table for that type of object
result = HTinsert(Htable[type], newID, n);
if ( result == 0 ) result = -1;
return result;
}
//=============================================================================
int project_findObject(int type, char *id)
//
// Input: type = object type
// id = object ID
// Output: returns index of object with given ID, or -1 if ID not found
// Purpose: uses hash table to find index of an object with a given ID.
//
{
return HTfind(Htable[type], id);
}
//=============================================================================
char *project_findID(int type, char *id)
//
// Input: type = object type
// id = ID name being sought
// Output: returns pointer to location where object's ID string is stored
// Purpose: uses hash table to find address of given string entry.
//
{
return HTfindKey(Htable[type], id);
}
//=============================================================================
double ** project_createMatrix(int nrows, int ncols)
//
// Input: nrows = number of rows (0-based)
// ncols = number of columns (0-based)
// Output: returns a pointer to a matrix
// Purpose: allocates memory for a matrix of doubles.
//
{
int i,j;
double **a;
// --- allocate pointers to rows
a = (double **) malloc(nrows * sizeof(double *));
if ( !a ) return NULL;
// --- allocate rows and set pointers to them
a[0] = (double *) malloc (nrows * ncols * sizeof(double));
if ( !a[0] ) return NULL;
for ( i = 1; i < nrows; i++ ) a[i] = a[i-1] + ncols;
for ( i = 0; i < nrows; i++)
{
for ( j = 0; j < ncols; j++) a[i][j] = 0.0;
}
// --- return pointer to array of pointers to rows
return a;
}
//=============================================================================
void project_freeMatrix(double **a)
//
// Input: a = matrix of floats
// Output: none
// Purpose: frees memory allocated for a matrix of doubles.
//
{
if ( a != NULL )
{
if ( a[0] != NULL ) free( a[0] );
free( a );
}
}
//=============================================================================
int project_readOption(char* s1, char* s2)
//
// Input: s1 = option keyword
// s2 = string representation of option's value
// Output: returns error code
// Purpose: reads a project option from a pair of string tokens.
//
// NOTE: all project options have default values assigned in setDefaults().
//
{
int k, m, h, s;
double tStep;
char strDate[25];
DateTime aTime;
DateTime aDate;
// --- determine which option is being read
k = findmatch(s1, OptionWords);
if ( k < 0 ) return error_setInpError(ERR_KEYWORD, s1);
switch ( k )
{
// --- choice of flow units
case FLOW_UNITS:
m = findmatch(s2, FlowUnitWords);
if ( m < 0 ) return error_setInpError(ERR_KEYWORD, s2);
FlowUnits = m;
if ( FlowUnits <= MGD ) UnitSystem = US;
else UnitSystem = SI;
break;
// --- choice of infiltration modeling method
case INFIL_MODEL:
m = findmatch(s2, InfilModelWords);
if ( m < 0 ) return error_setInpError(ERR_KEYWORD, s2);
InfilModel = m;
break;
// --- choice of runoff model
case RUNOFF_MODEL:
m = findmatch(s2, RunoffModelWords);
if ( m < 0 ) return error_setInpError(ERR_KEYWORD, s2);
RunoffModel = m;
break;
// --- choice of flow routing method
case ROUTE_MODEL:
m = findmatch(s2, RouteModelWords);
if ( m < 0 ) m = findmatch(s2, OldRouteModelWords);
if ( m < 0 ) return error_setInpError(ERR_KEYWORD, s2);
if ( m == NO_ROUTING ) IgnoreRouting = TRUE;
else RouteModel = m;
if ( RouteModel == EKW ) RouteModel = KW;
break;
// --- simulation start date
case START_DATE:
if ( !datetime_strToDate(s2, &StartDate) )
{
return error_setInpError(ERR_DATETIME, s2);
}
break;
// --- simulation start time of day
case START_TIME:
if ( !datetime_strToTime(s2, &StartTime) )
{
return error_setInpError(ERR_DATETIME, s2);
}
break;
// --- simulation ending date
case END_DATE:
if ( !datetime_strToDate(s2, &EndDate) )
{
return error_setInpError(ERR_DATETIME, s2);
}
break;
// --- simulation ending time of day
case END_TIME:
if ( !datetime_strToTime(s2, &EndTime) )
{
return error_setInpError(ERR_DATETIME, s2);
}
break;
// --- reporting start date
case REPORT_START_DATE:
if ( !datetime_strToDate(s2, &ReportStartDate) )
{
return error_setInpError(ERR_DATETIME, s2);
}
break;
// --- reporting start time of day
case REPORT_START_TIME:
if ( !datetime_strToTime(s2, &ReportStartTime) )
{
return error_setInpError(ERR_DATETIME, s2);
}
break;
// --- day of year when street sweeping begins or when it ends
// (year is arbitrarily set to 1947 so that the dayOfYear
// function can be applied)
case SWEEP_START:
case SWEEP_END:
strcpy(strDate, s2);
strcat(strDate, "/1947");
if ( !datetime_strToDate(strDate, &aDate) )
{
return error_setInpError(ERR_DATETIME, s2);
}
m = datetime_dayOfYear(aDate);
if ( k == SWEEP_START ) SweepStart = m;
else SweepEnd = m;
break;
// --- number of antecedent dry days
case START_DRY_DAYS:
StartDryDays = atof(s2);
if ( StartDryDays < 0.0 )
{
return error_setInpError(ERR_NUMBER, s2);
}
break;
// --- runoff or reporting time steps
// (input is in hrs:min:sec format, time step saved as seconds)
case WET_STEP:
case DRY_STEP:
case REPORT_STEP:
case RULE_STEP: //(5.1.013)
if ( !datetime_strToTime(s2, &aTime) )
{
return error_setInpError(ERR_DATETIME, s2);
}
datetime_decodeTime(aTime, &h, &m, &s);
h += 24*(int)aTime;
s = s + 60*m + 3600*h;
// --- RuleStep allowed to be 0 while other time steps must be > 0 //(5.1.013)
if (k == RULE_STEP) //
{ //
if (s < 0) return error_setInpError(ERR_NUMBER, s2); //
} //
else if ( s <= 0 ) return error_setInpError(ERR_NUMBER, s2); //
switch ( k )
{
case WET_STEP: WetStep = s; break;
case DRY_STEP: DryStep = s; break;
case REPORT_STEP: ReportStep = s; break;
case RULE_STEP: RuleStep = s; break; //(5.1.013)
}
break;
// --- type of damping applied to inertial terms of dynamic wave routing
case INERT_DAMPING:
m = findmatch(s2, InertDampingWords);
if ( m < 0 ) return error_setInpError(ERR_KEYWORD, s2);
else InertDamping = m;
break;
// --- Yes/No options (NO = 0, YES = 1)
case ALLOW_PONDING:
case SLOPE_WEIGHTING:
case SKIP_STEADY_STATE:
case IGNORE_RAINFALL:
case IGNORE_SNOWMELT:
case IGNORE_GWATER:
case IGNORE_ROUTING:
case IGNORE_QUALITY:
case IGNORE_RDII:
m = findmatch(s2, NoYesWords);
if ( m < 0 ) return error_setInpError(ERR_KEYWORD, s2);
switch ( k )
{
case ALLOW_PONDING: AllowPonding = m; break;
case SLOPE_WEIGHTING: SlopeWeighting = m; break;
case SKIP_STEADY_STATE: SkipSteadyState = m; break;
case IGNORE_RAINFALL: IgnoreRainfall = m; break;
case IGNORE_SNOWMELT: IgnoreSnowmelt = m; break;
case IGNORE_GWATER: IgnoreGwater = m; break;
case IGNORE_ROUTING: IgnoreRouting = m; break;
case IGNORE_QUALITY: IgnoreQuality = m; break;
case IGNORE_RDII: IgnoreRDII = m; break;
}
break;
case NORMAL_FLOW_LTD:
m = findmatch(s2, NormalFlowWords);
if ( m < 0 ) return error_setInpError(ERR_KEYWORD, s2);
NormalFlowLtd = m;
break;
case FORCE_MAIN_EQN:
m = findmatch(s2, ForceMainEqnWords);
if ( m < 0 ) return error_setInpError(ERR_KEYWORD, s2);
ForceMainEqn = m;
break;
case LINK_OFFSETS:
m = findmatch(s2, LinkOffsetWords);
if ( m < 0 ) return error_setInpError(ERR_KEYWORD, s2);
LinkOffsets = m;
break;
// --- compatibility option for selecting solution method for
// dynamic wave flow routing (NOT CURRENTLY USED)
case COMPATIBILITY:
if ( strcomp(s2, "3") ) Compatibility = SWMM3;
else if ( strcomp(s2, "4") ) Compatibility = SWMM4;
else if ( strcomp(s2, "5") ) Compatibility = SWMM5;
else return error_setInpError(ERR_KEYWORD, s2);
break;
// --- routing or lengthening time step (in decimal seconds)
// (lengthening time step is used in Courant stability formula
// to artificially lengthen conduits for dynamic wave flow routing
// (a value of 0 means that no lengthening is used))
case ROUTE_STEP:
case LENGTHENING_STEP:
if ( !getDouble(s2, &tStep) )
{
if ( !datetime_strToTime(s2, &aTime) )
{
return error_setInpError(ERR_NUMBER, s2);
}
else
{
datetime_decodeTime(aTime, &h, &m, &s);
h += 24*(int)aTime;
s = s + 60*m + 3600*h;
tStep = s;
}
}
if ( k == ROUTE_STEP )
{
if ( tStep <= 0.0 ) return error_setInpError(ERR_NUMBER, s2);
RouteStep = tStep;
}
else LengtheningStep = MAX(0.0, tStep);
break;
// --- minimum variable time step for dynamic wave routing
case MIN_ROUTE_STEP:
if ( !getDouble(s2, &MinRouteStep) || MinRouteStep < 0.0 )
return error_setInpError(ERR_NUMBER, s2);
break;
case NUM_THREADS:
m = atoi(s2);
if ( m < 0 ) return error_setInpError(ERR_NUMBER, s2);
NumThreads = m;
break;
// --- safety factor applied to variable time step estimates under
// dynamic wave flow routing (value of 0 indicates that variable
// time step option not used)
case VARIABLE_STEP:
if ( !getDouble(s2, &CourantFactor) )
return error_setInpError(ERR_NUMBER, s2);
if ( CourantFactor < 0.0 || CourantFactor > 2.0 )
return error_setInpError(ERR_NUMBER, s2);
break;
// --- minimum surface area (ft2 or sq. meters) associated with nodes
// under dynamic wave flow routing
case MIN_SURFAREA:
if (!getDouble(s2, &MinSurfArea)) //(5.1.013)
return error_setInpError(ERR_NUMBER, s2); //(5.1.013)
if (MinSurfArea < 0.0) //(5.1.013)
return error_setInpError(ERR_NUMBER, s2); //(5.1.013)
break;
// --- minimum conduit slope (%)
case MIN_SLOPE:
if ( !getDouble(s2, &MinSlope) )
return error_setInpError(ERR_NUMBER, s2);
if ( MinSlope < 0.0 || MinSlope >= 100 )
return error_setInpError(ERR_NUMBER, s2);
MinSlope /= 100.0;
break;
// --- maximum trials / time step for dynamic wave routing
case MAX_TRIALS:
m = atoi(s2);
if ( m < 0 ) return error_setInpError(ERR_NUMBER, s2);
MaxTrials = m;
break;
// --- head convergence tolerance for dynamic wave routing
case HEAD_TOL:
if ( !getDouble(s2, &HeadTol) )
{
return error_setInpError(ERR_NUMBER, s2);
}
break;
// --- steady state tolerance on system inflow - outflow
case SYS_FLOW_TOL:
if ( !getDouble(s2, &SysFlowTol) )
{
return error_setInpError(ERR_NUMBER, s2);
}
SysFlowTol /= 100.0;
break;
// --- steady state tolerance on nodal lateral inflow
case LAT_FLOW_TOL:
if ( !getDouble(s2, &LatFlowTol) )
{
return error_setInpError(ERR_NUMBER, s2);
}
LatFlowTol /= 100.0;
break;
// --- method used for surcharging in dynamic wave flow routing //(5.1.013)
case SURCHARGE_METHOD:
m = findmatch(s2, SurchargeWords);
if (m < 0) return error_setInpError(ERR_KEYWORD, s2);
SurchargeMethod = m;
break;
case TEMPDIR: // Temporary Directory
sstrncpy(TempDir, s2, MAXFNAME);
break;
}
return 0;
}
//=============================================================================
void initPointers()
//
// Input: none
// Output: none
// Purpose: assigns NULL to all dynamic arrays for a new project.
//
{
Gage = NULL;
Subcatch = NULL;
Node = NULL;
Outfall = NULL;
Divider = NULL;
Storage = NULL;
Link = NULL;
Conduit = NULL;
Pump = NULL;
Orifice = NULL;
Weir = NULL;
Outlet = NULL;
Pollut = NULL;
Landuse = NULL;
Pattern = NULL;
Curve = NULL;
Tseries = NULL;
Transect = NULL;
Shape = NULL;
Aquifer = NULL;
UnitHyd = NULL;
Snowmelt = NULL;
Event = NULL;
MemPoolAllocated = FALSE;
}
//=============================================================================
void setDefaults()
//
// Input: none
// Output: none
// Purpose: assigns default values to project variables.
//
{
int i, j;
// Project title & temp. file path
for (i = 0; i < MAXTITLE; i++) strcpy(Title[i], "");
strcpy(TempDir, "");
// Interface files
Frain.mode = SCRATCH_FILE; // Use scratch rainfall file
Fclimate.mode = NO_FILE;
Frunoff.mode = NO_FILE;
Frdii.mode = NO_FILE;
Fhotstart1.mode = NO_FILE;
Fhotstart2.mode = NO_FILE;
Finflows.mode = NO_FILE;
Foutflows.mode = NO_FILE;
Frain.file = NULL;
Fclimate.file = NULL;
Frunoff.file = NULL;
Frdii.file = NULL;
Fhotstart1.file = NULL;
Fhotstart2.file = NULL;
Finflows.file = NULL;
Foutflows.file = NULL;
Fout.file = NULL;
Fout.mode = NO_FILE;
// Analysis options
UnitSystem = US; // US unit system
FlowUnits = CFS; // CFS flow units
InfilModel = HORTON; // Horton infiltration method
RouteModel = KW; // Kin. wave flow routing method
RunoffModel = MANNING; // Nash Cascade runoff method
SurchargeMethod = EXTRAN; // Use EXTRAN method for surcharging //(5.1.013)
CrownCutoff = 0.96; //(5.1.013)
AllowPonding = FALSE; // No ponding at nodes
InertDamping = SOME; // Partial inertial damping
NormalFlowLtd = BOTH; // Default normal flow limitation
ForceMainEqn = H_W; // Hazen-Williams eqn. for force mains
LinkOffsets = DEPTH_OFFSET; // Use depth for link offsets
LengtheningStep = 0; // No lengthening of conduits
CourantFactor = 0.0; // No variable time step
MinSurfArea = 0.0; // Force use of default min. surface area
MinSlope = 0.0; // No user supplied minimum conduit slope
SkipSteadyState = FALSE; // Do flow routing in steady state periods
IgnoreRainfall = FALSE; // Analyze rainfall/runoff
IgnoreRDII = FALSE; // Analyze RDII
IgnoreSnowmelt = FALSE; // Analyze snowmelt
IgnoreGwater = FALSE; // Analyze groundwater
IgnoreRouting = FALSE; // Analyze flow routing
IgnoreQuality = FALSE; // Analyze water quality
WetStep = 300; // Runoff wet time step (secs)
DryStep = 3600; // Runoff dry time step (secs)
RuleStep = 0; // Rules evaluated at each routing step
RouteStep = 300.0; // Routing time step (secs)
MinRouteStep = 0.5; // Minimum variable time step (sec)
ReportStep = 900; // Reporting time step (secs)
StartDryDays = 0.0; // Antecedent dry days
MaxTrials = 0; // Force use of default max. trials
HeadTol = 0.0; // Force use of default head tolerance
SysFlowTol = 0.05; // System flow tolerance for steady state
LatFlowTol = 0.05; // Lateral flow tolerance for steady state
NumThreads = 0; // Number of parallel threads to use
NumEvents = 0; // Number of detailed routing events
// Deprecated options
SlopeWeighting = TRUE; // Use slope weighting
Compatibility = SWMM4; // Use SWMM 4 up/dn weighting method
// Starting & ending date/time
StartDate = datetime_encodeDate(2004, 1, 1);
StartTime = datetime_encodeTime(0,0,0);
StartDateTime = StartDate + StartTime;
EndDate = StartDate;
EndTime = 0.0;
ReportStartDate = NO_DATE;
ReportStartTime = NO_DATE;
SweepStart = 1;
SweepEnd = 365;
// Reporting options
RptFlags.input = FALSE;
RptFlags.continuity = TRUE;
RptFlags.flowStats = TRUE;
RptFlags.controls = FALSE;
RptFlags.subcatchments = FALSE;
RptFlags.nodes = FALSE;
RptFlags.links = FALSE;
RptFlags.nodeStats = FALSE;
RptFlags.averages = FALSE;
// Temperature data
Temp.dataSource = NO_TEMP;
Temp.tSeries = -1;
Temp.ta = 70.0;
Temp.elev = 0.0;
Temp.anglat = 40.0;
Temp.dtlong = 0.0;
Temp.tmax = MISSING;
// Wind speed data
Wind.type = MONTHLY_WIND;
for ( i=0; i<12; i++ ) Wind.aws[i] = 0.0;
// Snowmelt parameters
Snow.snotmp = 34.0;
Snow.tipm = 0.5;
Snow.rnm = 0.6;
// Snow areal depletion curves for pervious and impervious surfaces
for ( i=0; i<2; i++ )
{
for ( j=0; j<10; j++) Snow.adc[i][j] = 1.0;
}
// Evaporation rates
Evap.type = CONSTANT_EVAP;
for (i=0; i<12; i++)
{
Evap.monthlyEvap[i] = 0.0;
Evap.panCoeff[i] = 1.0;
}
Evap.recoveryPattern = -1;
Evap.recoveryFactor = 1.0;
Evap.tSeries = -1;
Evap.dryOnly = FALSE;
// Climate adjustments
for (i = 0; i < 12; i++)
{
Adjust.temp[i] = 0.0; // additive adjustments
Adjust.evap[i] = 0.0; // additive adjustments
Adjust.rain[i] = 1.0; // multiplicative adjustments
Adjust.hydcon[i] = 1.0; // hyd. conductivity adjustments
}
Adjust.rainFactor = 1.0;
Adjust.hydconFactor = 1.0;
}
//=============================================================================
void openFiles(char *f1, char *f2, char *f3)
//
// Input: f1 = name of input file
// f2 = name of report file
// f3 = name of binary output file
// Output: none
// Purpose: opens a project's input and report files.
//
{
// --- initialize file pointers to NULL
Finp.file = NULL;
Frpt.file = NULL;
Fout.file = NULL;
// --- save file names
sstrncpy(Finp.name, f1, MAXFNAME);
sstrncpy(Frpt.name, f2, MAXFNAME);
sstrncpy(Fout.name, f3, MAXFNAME);
// --- check that file names are not identical
if (strcomp(f1, f2) || strcomp(f1, f3) || strcomp(f2, f3))
{
writecon(FMT11);
ErrorCode = ERR_FILE_NAME;
return;
}
// --- open input and report files
if ((Finp.file = fopen(f1,"rt")) == NULL)
{
writecon(FMT12);
writecon(f1);
ErrorCode = ERR_INP_FILE;
return;
}
if ((Frpt.file = fopen(f2,"wt")) == NULL)
{
writecon(FMT13);
ErrorCode = ERR_RPT_FILE;
return;
}
}
//=============================================================================
void createObjects()
//
// Input: none
// Output: none
// Purpose: allocates memory for project's objects.
//
// NOTE: number of each type of object has already been determined in
// project_readInput().
//
{
int j, k;
// --- allocate memory for each category of object
if ( ErrorCode ) return;
Gage = (TGage *) calloc(Nobjects[GAGE], sizeof(TGage));
Subcatch = (TSubcatch *) calloc(Nobjects[SUBCATCH], sizeof(TSubcatch));
Node = (TNode *) calloc(Nobjects[NODE], sizeof(TNode));
Outfall = (TOutfall *) calloc(Nnodes[OUTFALL], sizeof(TOutfall));
Divider = (TDivider *) calloc(Nnodes[DIVIDER], sizeof(TDivider));
Storage = (TStorage *) calloc(Nnodes[STORAGE], sizeof(TStorage));
Link = (TLink *) calloc(Nobjects[LINK], sizeof(TLink));
Conduit = (TConduit *) calloc(Nlinks[CONDUIT], sizeof(TConduit));
Pump = (TPump *) calloc(Nlinks[PUMP], sizeof(TPump));
Orifice = (TOrifice *) calloc(Nlinks[ORIFICE], sizeof(TOrifice));
Weir = (TWeir *) calloc(Nlinks[WEIR], sizeof(TWeir));
Outlet = (TOutlet *) calloc(Nlinks[OUTLET], sizeof(TOutlet));
Pollut = (TPollut *) calloc(Nobjects[POLLUT], sizeof(TPollut));
Landuse = (TLanduse *) calloc(Nobjects[LANDUSE], sizeof(TLanduse));
Pattern = (TPattern *) calloc(Nobjects[TIMEPATTERN], sizeof(TPattern));
Curve = (TTable *) calloc(Nobjects[CURVE], sizeof(TTable));
Tseries = (TTable *) calloc(Nobjects[TSERIES], sizeof(TTable));
Aquifer = (TAquifer *) calloc(Nobjects[AQUIFER], sizeof(TAquifer));
UnitHyd = (TUnitHyd *) calloc(Nobjects[UNITHYD], sizeof(TUnitHyd));
Snowmelt = (TSnowmelt *) calloc(Nobjects[SNOWMELT], sizeof(TSnowmelt));
Shape = (TShape *) calloc(Nobjects[SHAPE], sizeof(TShape));
// --- create array of detailed routing event periods
Event = (TEvent *) calloc(NumEvents+1, sizeof(TEvent));
Event[NumEvents].start = BIG;
Event[NumEvents].end = BIG + 1.0;
// --- create LID objects
lid_create(Nobjects[LID], Nobjects[SUBCATCH]);
// --- create control rules
ErrorCode = controls_create(Nobjects[CONTROL]);
if ( ErrorCode ) return;
// --- create cross section transects
ErrorCode = transect_create(Nobjects[TRANSECT]);
if ( ErrorCode ) return;
// --- allocate memory for infiltration data
infil_create(Nobjects[SUBCATCH], InfilModel);
// --- allocate memory for water quality state variables
for (j = 0; j < Nobjects[SUBCATCH]; j++)
{
Subcatch[j].initBuildup =
(double *) calloc(Nobjects[POLLUT], sizeof(double));
Subcatch[j].oldQual = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Subcatch[j].newQual = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Subcatch[j].pondedQual = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Subcatch[j].concPonded = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Subcatch[j].totalLoad = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Subcatch[j].surfaceBuildup = (double *) calloc(Nobjects[POLLUT], sizeof(double));
}
for (j = 0; j < Nobjects[NODE]; j++)
{
Node[j].oldQual = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Node[j].newQual = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Node[j].extQual = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Node[j].inQual = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Node[j].reactorQual = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Node[j].extPollutFlag = (int *) calloc(Nobjects[POLLUT], sizeof(int));
Node[j].extInflow = NULL;
Node[j].dwfInflow = NULL;
Node[j].rdiiInflow = NULL;
Node[j].treatment = NULL;
}
for (j = 0; j < Nobjects[LINK]; j++)
{
Link[j].oldQual = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Link[j].newQual = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Link[j].extQual = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Link[j].totalLoad = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Link[j].reactorQual = (double *) calloc(Nobjects[POLLUT], sizeof(double));
Link[j].extPollutFlag = (int *) calloc(Nobjects[POLLUT], sizeof(int));
}
// --- allocate memory for land use buildup/washoff functions
for (j = 0; j < Nobjects[LANDUSE]; j++)
{
Landuse[j].buildupFunc =
(TBuildup *) calloc(Nobjects[POLLUT], sizeof(TBuildup));
Landuse[j].washoffFunc =
(TWashoff *) calloc(Nobjects[POLLUT], sizeof(TWashoff));
}
// --- allocate memory for subcatchment landuse factors
for (j = 0; j < Nobjects[SUBCATCH]; j++)
{
Subcatch[j].landFactor =
(TLandFactor *) calloc(Nobjects[LANDUSE], sizeof(TLandFactor));
for (k = 0; k < Nobjects[LANDUSE]; k++)
{
Subcatch[j].landFactor[k].buildup =
(double *) calloc(Nobjects[POLLUT], sizeof(double));
}
}
// --- initialize buildup & washoff functions
for (j = 0; j < Nobjects[LANDUSE]; j++)
{
for (k = 0; k < Nobjects[POLLUT]; k++)
{
Landuse[j].buildupFunc[k].funcType = NO_BUILDUP;
Landuse[j].buildupFunc[k].normalizer = PER_AREA;
Landuse[j].washoffFunc[k].funcType = NO_WASHOFF;
}
}
// --- initialize rain gage properties
for (j = 0; j < Nobjects[GAGE]; j++)
{
Gage[j].tSeries = -1;
strcpy(Gage[j].fname, "");
}
// --- initialize subcatchment properties
for (j = 0; j < Nobjects[SUBCATCH]; j++)
{
Subcatch[j].outSubcatch = -1;
Subcatch[j].outNode = -1;
Subcatch[j].infil = -1;
Subcatch[j].groundwater = NULL;
Subcatch[j].gwLatFlowExpr = NULL;
Subcatch[j].gwDeepFlowExpr = NULL;
Subcatch[j].snowpack = NULL;
Subcatch[j].lidArea = 0.0;
for (k = 0; k < Nobjects[POLLUT]; k++)
{
Subcatch[j].initBuildup[k] = 0.0;
}
}
// --- initialize RDII unit hydrograph properties
for ( j = 0; j < Nobjects[UNITHYD]; j++ ) rdii_initUnitHyd(j);
// --- initialize snowmelt properties
for ( j = 0; j < Nobjects[SNOWMELT]; j++ ) snow_initSnowmelt(j);
// --- initialize storage node exfiltration
for (j = 0; j < Nnodes[STORAGE]; j++) Storage[j].exfil = NULL;
// --- initialize link properties
for (j = 0; j < Nobjects[LINK]; j++)
{
Link[j].xsect.type = -1;
Link[j].cLossInlet = 0.0;
Link[j].cLossOutlet = 0.0;
Link[j].cLossAvg = 0.0;
Link[j].hasFlapGate = FALSE;
}
for (j = 0; j < Nlinks[PUMP]; j++) Pump[j].pumpCurve = -1;
// --- initialize reporting flags
for (j = 0; j < Nobjects[SUBCATCH]; j++) Subcatch[j].rptFlag = FALSE;
for (j = 0; j < Nobjects[NODE]; j++) Node[j].rptFlag = FALSE;
for (j = 0; j < Nobjects[LINK]; j++) Link[j].rptFlag = FALSE;
// --- initialize curves, time series, and time patterns
for (j = 0; j < Nobjects[CURVE]; j++) table_init(&Curve[j]);
for (j = 0; j < Nobjects[TSERIES]; j++) table_init(&Tseries[j]);
for (j = 0; j < Nobjects[TIMEPATTERN]; j++) inflow_initDwfPattern(j);
}
//=============================================================================
void deleteObjects()
//
// Input: none
// Output: none
// Purpose: frees memory allocated for a project's objects.
//
// NOTE: care is taken to first free objects that are properties of another
// object before the latter is freed (e.g., we must free a
// subcatchment's land use factors before freeing the subcatchment).
//
{
int j, k;
// --- free memory for landuse factors & groundwater
if ( Subcatch ) for (j = 0; j < Nobjects[SUBCATCH]; j++)
{
for (k = 0; k < Nobjects[LANDUSE]; k++)
{
FREE(Subcatch[j].landFactor[k].buildup);
}
FREE(Subcatch[j].landFactor);
FREE(Subcatch[j].groundwater);
gwater_deleteFlowExpression(j);
FREE(Subcatch[j].snowpack);
}
// --- free memory for buildup/washoff functions
if ( Landuse ) for (j = 0; j < Nobjects[LANDUSE]; j++)
{
FREE(Landuse[j].buildupFunc);
FREE(Landuse[j].washoffFunc)
}
// --- free memory for water quality state variables
if ( Subcatch ) for (j = 0; j < Nobjects[SUBCATCH]; j++)
{
FREE(Subcatch[j].initBuildup);
FREE(Subcatch[j].oldQual);
FREE(Subcatch[j].newQual);
FREE(Subcatch[j].pondedQual);
FREE(Subcatch[j].totalLoad);
}
if ( Node ) for (j = 0; j < Nobjects[NODE]; j++)
{
FREE(Node[j].oldQual);
FREE(Node[j].newQual);
}
if ( Link ) for (j = 0; j < Nobjects[LINK]; j++)
{
FREE(Link[j].oldQual);
FREE(Link[j].newQual);
FREE(Link[j].totalLoad);
}
// --- free memory used for rainfall infiltration
infil_delete();
// --- free memory used for storage exfiltration
if ( Node ) for (j = 0; j < Nnodes[STORAGE]; j++)
{
if ( Storage[j].exfil )
{
FREE(Storage[j].exfil->btmExfil);
FREE(Storage[j].exfil->bankExfil);
FREE(Storage[j].exfil);
}
}
// --- free memory used for outfall pollutants loads
if ( Node ) for (j = 0; j < Nnodes[OUTFALL]; j++)
FREE(Outfall[j].wRouted);
// --- free memory used for nodal inflows & treatment functions
if ( Node ) for (j = 0; j < Nobjects[NODE]; j++)
{
inflow_deleteExtInflows(j);
inflow_deleteDwfInflows(j);
rdii_deleteRdiiInflow(j);
treatmnt_delete(j);
}
// --- delete table entries for curves and time series
if ( Tseries ) for (j = 0; j < Nobjects[TSERIES]; j++)
table_deleteEntries(&Tseries[j]);
if ( Curve ) for (j = 0; j < Nobjects[CURVE]; j++)
table_deleteEntries(&Curve[j]);
// --- delete cross section transects
transect_delete();
// --- delete control rules
controls_delete();
// --- delete LIDs
lid_delete();
// --- now free each major category of object
FREE(Gage);
FREE(Subcatch);
FREE(Node);
FREE(Outfall);
FREE(Divider);
FREE(Storage);
FREE(Link);
FREE(Conduit);
FREE(Pump);
FREE(Orifice);
FREE(Weir);
FREE(Outlet);
FREE(Pollut);
FREE(Landuse);
FREE(Pattern);
FREE(Curve);
FREE(Tseries);
FREE(Aquifer);
FREE(UnitHyd);
FREE(Snowmelt);
FREE(Shape);
FREE(Event);
}
//=============================================================================
void createHashTables()
//
// Input: none
// Output: returns error code
// Purpose: allocates memory for object ID hash tables
//
{ int j;
MemPoolAllocated = FALSE;
for (j = 0; j < MAX_OBJ_TYPES ; j++)
{
Htable[j] = HTcreate();
if ( Htable[j] == NULL ) report_writeErrorMsg(ERR_MEMORY, "");
}
// --- initialize memory pool used to store object ID's
if ( AllocInit() == NULL ) report_writeErrorMsg(ERR_MEMORY, "");
else MemPoolAllocated = TRUE;
}
//=============================================================================
void deleteHashTables()
//
// Input: none
// Output: none
// Purpose: frees memory allocated for object ID hash tables
//
{
int j;
for (j = 0; j < MAX_OBJ_TYPES; j++)
{
if ( Htable[j] != NULL ) HTfree(Htable[j]);
}
// --- free object ID memory pool
if ( MemPoolAllocated ) AllocFreePool();
}
//=============================================================================
|
primes.c | /*
Copyright (c) 2014, Ben Buhrow
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 OWNER 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 views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
#include "phi_ecm.h"
#include "omp.h"
#include <immintrin.h>
uint32_t **gbl_bitmap;
base_t * tiny_soe2(base_t limit, base_t *nump)
{
//simple sieve of erathosthenes for small limits - not efficient
//for large limits. use to generate sieve primes.
uint8_t *flags;
base_t *primes;
base_t prime;
base_t i,j;
int it;
//allocate flags
flags = (uint8_t *)malloc(limit/2 * sizeof(uint8_t));
if (flags == NULL)
printf("error allocating flags\n");
memset(flags,1,limit/2);
//find the sieving primes, don't bother with offsets, we'll need to find those
//separately for each line in the main sieve.
//sieve using primes less than the sqrt of the desired limit
//flags are created only for odd numbers (mod2)
for (i = 1; i < (uint32_t)(sqrt(limit)/2+1); i++)
{
if (flags[i] > 0)
{
prime = (uint32_t)(2*i + 1);
for (j = i + prime; j < limit/2; j += prime)
{
flags[j] = 0;
}
}
}
//now find the rest of the prime flags and compute the sieving primes
for (i = 0, it = 0; i < limit/2; i++)
{
if (flags[i] == 1)
{
it++;
}
}
primes = (base_t *)xmalloc_align(it * sizeof(base_t));
primes[0] = 2;
for (i = 1, it = 1; i < limit/2; i++)
{
if (flags[i] == 1)
{
primes[it++] = 2 * i + 1;
}
}
*nump = it;
free(flags);
return primes;
}
#define threadsPerBlock 224
#define startprime 3
uint32_t _step5[5] = { 2418280706, 604570176, 151142544, 37785636, 1083188233 };
uint32_t _step7[7] = { 1107363844, 69210240, 2151809288, 134488080,
276840961, 17302560, 537952322 };
uint32_t _step11[11] = { 33816584, 1073774848, 135266336, 132096, 541065345,
528384, 2164261380, 2113536, 67110928, 8454146, 268443712 };
uint32_t _step13[13] = { 1075838992, 16809984, 262656, 536875016, 8388672,
67239937, 1050624, 2147500064, 33554688, 268959748, 4202496,
65664, 134218754 };
uint32_t _step17[17] = { 268435488, 1073741952, 512, 2049, 8196, 32784, 131136,
524544, 2098176, 8392704, 33570816, 134283264, 537133056,
2148532224, 4194304, 16777218, 67108872 };
uint32_t _step19[19] = { 2147483712, 4096, 262176, 16779264, 1073872896, 8388608,
536870928, 1024, 65544, 4194816, 268468224, 2097152, 134217732,
256, 16386, 1048704, 67117056, 524288, 33554433 };
uint32_t _step23[23] = { 128, 2097216, 1048576, 8, 131076, 2147549184, 1073741824, 8192,
134221824, 67108864, 512, 8388864, 4194304, 32, 524304, 262144,
2, 32769, 536887296, 268435456, 2048, 33555456, 16777216 };
uint32_t _step29[29] = { 512, 65536, 8, 536871936, 0, 8388624, 1073741824,
131072, 16777216, 2048, 262144, 32, 2147487744, 0,
33554496, 0, 524289, 67108864, 8192, 1048576, 128,
16384, 2, 134217984, 0, 2097156, 268435456, 32768, 4194304 };
uint32_t _step31[31] = { 1024, 524288, 256, 131072, 64, 32768, 16, 8192, 4, 2048,
1, 1073742336, 0, 268435584, 0, 67108896, 0, 16777224, 0,
4194306, 2147483648, 1048576, 536870912, 262144, 134217728,
65536, 33554432, 16384, 8388608, 4096, 2097152 };
// here is probably the best way to do it:
// have each thread sieve a different block.
// within each thread-block, do vectorized sieving of 16 primes at a time.
// since a single thread is involved in each block, the block can
// be bit-packed and we can use mod 30 or mod 210 and sieve by lines.
// re-compute offsets for each new set of blocks.
// after each set of blocks, each threads counts primes in its block.
// based on counts, an offset into a large list of primes can be computed for each thread.
// each thread can then compute and simultaneously write to the large list.
// timings for comparison (M2050 Tesla GPU):
//3.222000 milliseconds for big sieve
//5761455 big primes(< 100000000) found
//
//36.381001 milliseconds for big sieve
//50847534 big primes(< 1000000000) found
//
//543.804993 milliseconds for big sieve
//455052511 big primes(< 10000000000) found
// currently at (3121P)
// 257 milliseconds for 10^7
// 257 milliseconds for 10^8
// 281 milliseconds for 10^9
// 648 milliseconds for 10^10
/*
#define VEC_SIZE 16
#define NLINES 8
#define BSIZE 8192 // both 4096 and 16384 were slower...
int _64_MOD_P[9] = { 4, 1, 9, 12, 13, 7, 18, 6, 2 };
// 512 mod 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53
int _512_MOD_P[14] = { 4, 1, 6, 5, 2, 18, 6, 19, 16, 31, 20, 39, 42, 35 };
// pid = 3
uint64_t _7_MASKS_512[7*8] = {
0x7efdfbf7efdfbf7eULL, 0xbf7efdfbf7efdfbfULL, 0xdfbf7efdfbf7efdfULL, 0xefdfbf7efdfbf7efULL, 0xf7efdfbf7efdfbf7ULL, 0xfbf7efdfbf7efdfbULL, 0xfdfbf7efdfbf7efdULL, 0x7efdfbf7efdfbf7eULL,
0xfdfbf7efdfbf7efdULL, 0x7efdfbf7efdfbf7eULL, 0xbf7efdfbf7efdfbfULL, 0xdfbf7efdfbf7efdfULL, 0xefdfbf7efdfbf7efULL, 0xf7efdfbf7efdfbf7ULL, 0xfbf7efdfbf7efdfbULL, 0xfdfbf7efdfbf7efdULL,
0xfbf7efdfbf7efdfbULL, 0xfdfbf7efdfbf7efdULL, 0x7efdfbf7efdfbf7eULL, 0xbf7efdfbf7efdfbfULL, 0xdfbf7efdfbf7efdfULL, 0xefdfbf7efdfbf7efULL, 0xf7efdfbf7efdfbf7ULL, 0xfbf7efdfbf7efdfbULL,
0xf7efdfbf7efdfbf7ULL, 0xfbf7efdfbf7efdfbULL, 0xfdfbf7efdfbf7efdULL, 0x7efdfbf7efdfbf7eULL, 0xbf7efdfbf7efdfbfULL, 0xdfbf7efdfbf7efdfULL, 0xefdfbf7efdfbf7efULL, 0xf7efdfbf7efdfbf7ULL,
0xefdfbf7efdfbf7efULL, 0xf7efdfbf7efdfbf7ULL, 0xfbf7efdfbf7efdfbULL, 0xfdfbf7efdfbf7efdULL, 0x7efdfbf7efdfbf7eULL, 0xbf7efdfbf7efdfbfULL, 0xdfbf7efdfbf7efdfULL, 0xefdfbf7efdfbf7efULL,
0xdfbf7efdfbf7efdfULL, 0xefdfbf7efdfbf7efULL, 0xf7efdfbf7efdfbf7ULL, 0xfbf7efdfbf7efdfbULL, 0xfdfbf7efdfbf7efdULL, 0x7efdfbf7efdfbf7eULL, 0xbf7efdfbf7efdfbfULL, 0xdfbf7efdfbf7efdfULL,
0xbf7efdfbf7efdfbfULL, 0xdfbf7efdfbf7efdfULL, 0xefdfbf7efdfbf7efULL, 0xf7efdfbf7efdfbf7ULL, 0xfbf7efdfbf7efdfbULL, 0xfdfbf7efdfbf7efdULL, 0x7efdfbf7efdfbf7eULL, 0xbf7efdfbf7efdfbfULL};
// pid = 4
uint64_t _11_MASKS_512[11 * 8] = {
0xff7feffdffbff7feULL, 0xfdffbff7feffdffbULL, 0xf7feffdffbff7fefULL, 0xdffbff7feffdffbfULL, 0x7feffdffbff7feffULL, 0xffbff7feffdffbffULL, 0xfeffdffbff7feffdULL, 0xfbff7feffdffbff7ULL,
0xfeffdffbff7feffdULL, 0xfbff7feffdffbff7ULL, 0xeffdffbff7feffdfULL, 0xbff7feffdffbff7fULL, 0xffdffbff7feffdffULL, 0xff7feffdffbff7feULL, 0xfdffbff7feffdffbULL, 0xf7feffdffbff7fefULL,
0xfdffbff7feffdffbULL, 0xf7feffdffbff7fefULL, 0xdffbff7feffdffbfULL, 0x7feffdffbff7feffULL, 0xffbff7feffdffbffULL, 0xfeffdffbff7feffdULL, 0xfbff7feffdffbff7ULL, 0xeffdffbff7feffdfULL,
0xfbff7feffdffbff7ULL, 0xeffdffbff7feffdfULL, 0xbff7feffdffbff7fULL, 0xffdffbff7feffdffULL, 0xff7feffdffbff7feULL, 0xfdffbff7feffdffbULL, 0xf7feffdffbff7fefULL, 0xdffbff7feffdffbfULL,
0xf7feffdffbff7fefULL, 0xdffbff7feffdffbfULL, 0x7feffdffbff7feffULL, 0xffbff7feffdffbffULL, 0xfeffdffbff7feffdULL, 0xfbff7feffdffbff7ULL, 0xeffdffbff7feffdfULL, 0xbff7feffdffbff7fULL,
0xeffdffbff7feffdfULL, 0xbff7feffdffbff7fULL, 0xffdffbff7feffdffULL, 0xff7feffdffbff7feULL, 0xfdffbff7feffdffbULL, 0xf7feffdffbff7fefULL, 0xdffbff7feffdffbfULL, 0x7feffdffbff7feffULL,
0xdffbff7feffdffbfULL, 0x7feffdffbff7feffULL, 0xffbff7feffdffbffULL, 0xfeffdffbff7feffdULL, 0xfbff7feffdffbff7ULL, 0xeffdffbff7feffdfULL, 0xbff7feffdffbff7fULL, 0xffdffbff7feffdffULL,
0xbff7feffdffbff7fULL, 0xffdffbff7feffdffULL, 0xff7feffdffbff7feULL, 0xfdffbff7feffdffbULL, 0xf7feffdffbff7fefULL, 0xdffbff7feffdffbfULL, 0x7feffdffbff7feffULL, 0xffbff7feffdffbffULL,
0x7feffdffbff7feffULL, 0xffbff7feffdffbffULL, 0xfeffdffbff7feffdULL, 0xfbff7feffdffbff7ULL, 0xeffdffbff7feffdfULL, 0xbff7feffdffbff7fULL, 0xffdffbff7feffdffULL, 0xff7feffdffbff7feULL,
0xffdffbff7feffdffULL, 0xff7feffdffbff7feULL, 0xfdffbff7feffdffbULL, 0xf7feffdffbff7fefULL, 0xdffbff7feffdffbfULL, 0x7feffdffbff7feffULL, 0xffbff7feffdffbffULL, 0xfeffdffbff7feffdULL,
0xffbff7feffdffbffULL, 0xfeffdffbff7feffdULL, 0xfbff7feffdffbff7ULL, 0xeffdffbff7feffdfULL, 0xbff7feffdffbff7fULL, 0xffdffbff7feffdffULL, 0xff7feffdffbff7feULL, 0xfdffbff7feffdffbULL};
// pid = 5
uint64_t _13_MASKS_512[13 * 8] = {
0xffefff7ffbffdffeULL, 0xffdffefff7ffbffdULL, 0xffbffdffefff7ffbULL, 0xff7ffbffdffefff7ULL, 0xfefff7ffbffdffefULL, 0xfdffefff7ffbffdfULL, 0xfbffdffefff7ffbfULL, 0xf7ffbffdffefff7fULL,
0xffdffefff7ffbffdULL, 0xffbffdffefff7ffbULL, 0xff7ffbffdffefff7ULL, 0xfefff7ffbffdffefULL, 0xfdffefff7ffbffdfULL, 0xfbffdffefff7ffbfULL, 0xf7ffbffdffefff7fULL, 0xefff7ffbffdffeffULL,
0xffbffdffefff7ffbULL, 0xff7ffbffdffefff7ULL, 0xfefff7ffbffdffefULL, 0xfdffefff7ffbffdfULL, 0xfbffdffefff7ffbfULL, 0xf7ffbffdffefff7fULL, 0xefff7ffbffdffeffULL, 0xdffefff7ffbffdffULL,
0xff7ffbffdffefff7ULL, 0xfefff7ffbffdffefULL, 0xfdffefff7ffbffdfULL, 0xfbffdffefff7ffbfULL, 0xf7ffbffdffefff7fULL, 0xefff7ffbffdffeffULL, 0xdffefff7ffbffdffULL, 0xbffdffefff7ffbffULL,
0xfefff7ffbffdffefULL, 0xfdffefff7ffbffdfULL, 0xfbffdffefff7ffbfULL, 0xf7ffbffdffefff7fULL, 0xefff7ffbffdffeffULL, 0xdffefff7ffbffdffULL, 0xbffdffefff7ffbffULL, 0x7ffbffdffefff7ffULL,
0xfdffefff7ffbffdfULL, 0xfbffdffefff7ffbfULL, 0xf7ffbffdffefff7fULL, 0xefff7ffbffdffeffULL, 0xdffefff7ffbffdffULL, 0xbffdffefff7ffbffULL, 0x7ffbffdffefff7ffULL, 0xfff7ffbffdffefffULL,
0xfbffdffefff7ffbfULL, 0xf7ffbffdffefff7fULL, 0xefff7ffbffdffeffULL, 0xdffefff7ffbffdffULL, 0xbffdffefff7ffbffULL, 0x7ffbffdffefff7ffULL, 0xfff7ffbffdffefffULL, 0xffefff7ffbffdffeULL,
0xf7ffbffdffefff7fULL, 0xefff7ffbffdffeffULL, 0xdffefff7ffbffdffULL, 0xbffdffefff7ffbffULL, 0x7ffbffdffefff7ffULL, 0xfff7ffbffdffefffULL, 0xffefff7ffbffdffeULL, 0xffdffefff7ffbffdULL,
0xefff7ffbffdffeffULL, 0xdffefff7ffbffdffULL, 0xbffdffefff7ffbffULL, 0x7ffbffdffefff7ffULL, 0xfff7ffbffdffefffULL, 0xffefff7ffbffdffeULL, 0xffdffefff7ffbffdULL, 0xffbffdffefff7ffbULL,
0xdffefff7ffbffdffULL, 0xbffdffefff7ffbffULL, 0x7ffbffdffefff7ffULL, 0xfff7ffbffdffefffULL, 0xffefff7ffbffdffeULL, 0xffdffefff7ffbffdULL, 0xffbffdffefff7ffbULL, 0xff7ffbffdffefff7ULL,
0xbffdffefff7ffbffULL, 0x7ffbffdffefff7ffULL, 0xfff7ffbffdffefffULL, 0xffefff7ffbffdffeULL, 0xffdffefff7ffbffdULL, 0xffbffdffefff7ffbULL, 0xff7ffbffdffefff7ULL, 0xfefff7ffbffdffefULL,
0x7ffbffdffefff7ffULL, 0xfff7ffbffdffefffULL, 0xffefff7ffbffdffeULL, 0xffdffefff7ffbffdULL, 0xffbffdffefff7ffbULL, 0xff7ffbffdffefff7ULL, 0xfefff7ffbffdffefULL, 0xfdffefff7ffbffdfULL,
0xfff7ffbffdffefffULL, 0xffefff7ffbffdffeULL, 0xffdffefff7ffbffdULL, 0xffbffdffefff7ffbULL, 0xff7ffbffdffefff7ULL, 0xfefff7ffbffdffefULL, 0xfdffefff7ffbffdfULL, 0xfbffdffefff7ffbfULL};
// pid = 6
uint64_t _17_MASKS_512[17 * 8] = {
0xfff7fffbfffdfffeULL, 0xff7fffbfffdfffefULL, 0xf7fffbfffdfffeffULL, 0x7fffbfffdfffefffULL, 0xfffbfffdfffeffffULL, 0xffbfffdfffeffff7ULL, 0xfbfffdfffeffff7fULL, 0xbfffdfffeffff7ffULL,
0xffeffff7fffbfffdULL, 0xfeffff7fffbfffdfULL, 0xeffff7fffbfffdffULL, 0xffff7fffbfffdfffULL, 0xfff7fffbfffdfffeULL, 0xff7fffbfffdfffefULL, 0xf7fffbfffdfffeffULL, 0x7fffbfffdfffefffULL,
0xffdfffeffff7fffbULL, 0xfdfffeffff7fffbfULL, 0xdfffeffff7fffbffULL, 0xfffeffff7fffbfffULL, 0xffeffff7fffbfffdULL, 0xfeffff7fffbfffdfULL, 0xeffff7fffbfffdffULL, 0xffff7fffbfffdfffULL,
0xffbfffdfffeffff7ULL, 0xfbfffdfffeffff7fULL, 0xbfffdfffeffff7ffULL, 0xfffdfffeffff7fffULL, 0xffdfffeffff7fffbULL, 0xfdfffeffff7fffbfULL, 0xdfffeffff7fffbffULL, 0xfffeffff7fffbfffULL,
0xff7fffbfffdfffefULL, 0xf7fffbfffdfffeffULL, 0x7fffbfffdfffefffULL, 0xfffbfffdfffeffffULL, 0xffbfffdfffeffff7ULL, 0xfbfffdfffeffff7fULL, 0xbfffdfffeffff7ffULL, 0xfffdfffeffff7fffULL,
0xfeffff7fffbfffdfULL, 0xeffff7fffbfffdffULL, 0xffff7fffbfffdfffULL, 0xfff7fffbfffdfffeULL, 0xff7fffbfffdfffefULL, 0xf7fffbfffdfffeffULL, 0x7fffbfffdfffefffULL, 0xfffbfffdfffeffffULL,
0xfdfffeffff7fffbfULL, 0xdfffeffff7fffbffULL, 0xfffeffff7fffbfffULL, 0xffeffff7fffbfffdULL, 0xfeffff7fffbfffdfULL, 0xeffff7fffbfffdffULL, 0xffff7fffbfffdfffULL, 0xfff7fffbfffdfffeULL,
0xfbfffdfffeffff7fULL, 0xbfffdfffeffff7ffULL, 0xfffdfffeffff7fffULL, 0xffdfffeffff7fffbULL, 0xfdfffeffff7fffbfULL, 0xdfffeffff7fffbffULL, 0xfffeffff7fffbfffULL, 0xffeffff7fffbfffdULL,
0xf7fffbfffdfffeffULL, 0x7fffbfffdfffefffULL, 0xfffbfffdfffeffffULL, 0xffbfffdfffeffff7ULL, 0xfbfffdfffeffff7fULL, 0xbfffdfffeffff7ffULL, 0xfffdfffeffff7fffULL, 0xffdfffeffff7fffbULL,
0xeffff7fffbfffdffULL, 0xffff7fffbfffdfffULL, 0xfff7fffbfffdfffeULL, 0xff7fffbfffdfffefULL, 0xf7fffbfffdfffeffULL, 0x7fffbfffdfffefffULL, 0xfffbfffdfffeffffULL, 0xffbfffdfffeffff7ULL,
0xdfffeffff7fffbffULL, 0xfffeffff7fffbfffULL, 0xffeffff7fffbfffdULL, 0xfeffff7fffbfffdfULL, 0xeffff7fffbfffdffULL, 0xffff7fffbfffdfffULL, 0xfff7fffbfffdfffeULL, 0xff7fffbfffdfffefULL,
0xbfffdfffeffff7ffULL, 0xfffdfffeffff7fffULL, 0xffdfffeffff7fffbULL, 0xfdfffeffff7fffbfULL, 0xdfffeffff7fffbffULL, 0xfffeffff7fffbfffULL, 0xffeffff7fffbfffdULL, 0xfeffff7fffbfffdfULL,
0x7fffbfffdfffefffULL, 0xfffbfffdfffeffffULL, 0xffbfffdfffeffff7ULL, 0xfbfffdfffeffff7fULL, 0xbfffdfffeffff7ffULL, 0xfffdfffeffff7fffULL, 0xffdfffeffff7fffbULL, 0xfdfffeffff7fffbfULL,
0xffff7fffbfffdfffULL, 0xfff7fffbfffdfffeULL, 0xff7fffbfffdfffefULL, 0xf7fffbfffdfffeffULL, 0x7fffbfffdfffefffULL, 0xfffbfffdfffeffffULL, 0xffbfffdfffeffff7ULL, 0xfbfffdfffeffff7fULL,
0xfffeffff7fffbfffULL, 0xffeffff7fffbfffdULL, 0xfeffff7fffbfffdfULL, 0xeffff7fffbfffdffULL, 0xffff7fffbfffdfffULL, 0xfff7fffbfffdfffeULL, 0xff7fffbfffdfffefULL, 0xf7fffbfffdfffeffULL,
0xfffdfffeffff7fffULL, 0xffdfffeffff7fffbULL, 0xfdfffeffff7fffbfULL, 0xdfffeffff7fffbffULL, 0xfffeffff7fffbfffULL, 0xffeffff7fffbfffdULL, 0xfeffff7fffbfffdfULL, 0xeffff7fffbfffdffULL,
0xfffbfffdfffeffffULL, 0xffbfffdfffeffff7ULL, 0xfbfffdfffeffff7fULL, 0xbfffdfffeffff7ffULL, 0xfffdfffeffff7fffULL, 0xffdfffeffff7fffbULL, 0xfdfffeffff7fffbfULL, 0xdfffeffff7fffbffULL};
// pid = 7
uint64_t _19_MASKS_512[19 * 8] = {
0xfdffffbffff7fffeULL, 0xfffbffff7fffefffULL, 0xbffff7fffeffffdfULL, 0xff7fffeffffdffffULL, 0xfffeffffdffffbffULL, 0xeffffdffffbffff7ULL, 0xffdffffbffff7fffULL, 0xffffbffff7fffeffULL,
0xfbffff7fffeffffdULL, 0xfff7fffeffffdfffULL, 0x7fffeffffdffffbfULL, 0xfeffffdffffbffffULL, 0xfffdffffbffff7ffULL, 0xdffffbffff7fffefULL, 0xffbffff7fffeffffULL, 0xffff7fffeffffdffULL,
0xf7fffeffffdffffbULL, 0xffeffffdffffbfffULL, 0xffffdffffbffff7fULL, 0xfdffffbffff7fffeULL, 0xfffbffff7fffefffULL, 0xbffff7fffeffffdfULL, 0xff7fffeffffdffffULL, 0xfffeffffdffffbffULL,
0xeffffdffffbffff7ULL, 0xffdffffbffff7fffULL, 0xffffbffff7fffeffULL, 0xfbffff7fffeffffdULL, 0xfff7fffeffffdfffULL, 0x7fffeffffdffffbfULL, 0xfeffffdffffbffffULL, 0xfffdffffbffff7ffULL,
0xdffffbffff7fffefULL, 0xffbffff7fffeffffULL, 0xffff7fffeffffdffULL, 0xf7fffeffffdffffbULL, 0xffeffffdffffbfffULL, 0xffffdffffbffff7fULL, 0xfdffffbffff7fffeULL, 0xfffbffff7fffefffULL,
0xbffff7fffeffffdfULL, 0xff7fffeffffdffffULL, 0xfffeffffdffffbffULL, 0xeffffdffffbffff7ULL, 0xffdffffbffff7fffULL, 0xffffbffff7fffeffULL, 0xfbffff7fffeffffdULL, 0xfff7fffeffffdfffULL,
0x7fffeffffdffffbfULL, 0xfeffffdffffbffffULL, 0xfffdffffbffff7ffULL, 0xdffffbffff7fffefULL, 0xffbffff7fffeffffULL, 0xffff7fffeffffdffULL, 0xf7fffeffffdffffbULL, 0xffeffffdffffbfffULL,
0xffffdffffbffff7fULL, 0xfdffffbffff7fffeULL, 0xfffbffff7fffefffULL, 0xbffff7fffeffffdfULL, 0xff7fffeffffdffffULL, 0xfffeffffdffffbffULL, 0xeffffdffffbffff7ULL, 0xffdffffbffff7fffULL,
0xffffbffff7fffeffULL, 0xfbffff7fffeffffdULL, 0xfff7fffeffffdfffULL, 0x7fffeffffdffffbfULL, 0xfeffffdffffbffffULL, 0xfffdffffbffff7ffULL, 0xdffffbffff7fffefULL, 0xffbffff7fffeffffULL,
0xffff7fffeffffdffULL, 0xf7fffeffffdffffbULL, 0xffeffffdffffbfffULL, 0xffffdffffbffff7fULL, 0xfdffffbffff7fffeULL, 0xfffbffff7fffefffULL, 0xbffff7fffeffffdfULL, 0xff7fffeffffdffffULL,
0xfffeffffdffffbffULL, 0xeffffdffffbffff7ULL, 0xffdffffbffff7fffULL, 0xffffbffff7fffeffULL, 0xfbffff7fffeffffdULL, 0xfff7fffeffffdfffULL, 0x7fffeffffdffffbfULL, 0xfeffffdffffbffffULL,
0xfffdffffbffff7ffULL, 0xdffffbffff7fffefULL, 0xffbffff7fffeffffULL, 0xffff7fffeffffdffULL, 0xf7fffeffffdffffbULL, 0xffeffffdffffbfffULL, 0xffffdffffbffff7fULL, 0xfdffffbffff7fffeULL,
0xfffbffff7fffefffULL, 0xbffff7fffeffffdfULL, 0xff7fffeffffdffffULL, 0xfffeffffdffffbffULL, 0xeffffdffffbffff7ULL, 0xffdffffbffff7fffULL, 0xffffbffff7fffeffULL, 0xfbffff7fffeffffdULL,
0xfff7fffeffffdfffULL, 0x7fffeffffdffffbfULL, 0xfeffffdffffbffffULL, 0xfffdffffbffff7ffULL, 0xdffffbffff7fffefULL, 0xffbffff7fffeffffULL, 0xffff7fffeffffdffULL, 0xf7fffeffffdffffbULL,
0xffeffffdffffbfffULL, 0xffffdffffbffff7fULL, 0xfdffffbffff7fffeULL, 0xfffbffff7fffefffULL, 0xbffff7fffeffffdfULL, 0xff7fffeffffdffffULL, 0xfffeffffdffffbffULL, 0xeffffdffffbffff7ULL,
0xffdffffbffff7fffULL, 0xffffbffff7fffeffULL, 0xfbffff7fffeffffdULL, 0xfff7fffeffffdfffULL, 0x7fffeffffdffffbfULL, 0xfeffffdffffbffffULL, 0xfffdffffbffff7ffULL, 0xdffffbffff7fffefULL,
0xffbffff7fffeffffULL, 0xffff7fffeffffdffULL, 0xf7fffeffffdffffbULL, 0xffeffffdffffbfffULL, 0xffffdffffbffff7fULL, 0xfdffffbffff7fffeULL, 0xfffbffff7fffefffULL, 0xbffff7fffeffffdfULL,
0xff7fffeffffdffffULL, 0xfffeffffdffffbffULL, 0xeffffdffffbffff7ULL, 0xffdffffbffff7fffULL, 0xffffbffff7fffeffULL, 0xfbffff7fffeffffdULL, 0xfff7fffeffffdfffULL, 0x7fffeffffdffffbfULL,
0xfeffffdffffbffffULL, 0xfffdffffbffff7ffULL, 0xdffffbffff7fffefULL, 0xffbffff7fffeffffULL, 0xffff7fffeffffdffULL, 0xf7fffeffffdffffbULL, 0xffeffffdffffbfffULL, 0xffffdffffbffff7fULL};
// pid = 8
uint64_t _23_MASKS_512[23 * 8] = {
0xffffbfffff7ffffeULL, 0xfff7ffffefffffdfULL, 0xfefffffdfffffbffULL, 0xdfffffbfffff7fffULL, 0xfffff7ffffefffffULL, 0xfffefffffdfffffbULL, 0xffdfffffbfffff7fULL, 0xfbfffff7ffffefffULL,
0xffff7ffffefffffdULL, 0xffefffffdfffffbfULL, 0xfdfffffbfffff7ffULL, 0xbfffff7ffffeffffULL, 0xffffefffffdfffffULL, 0xfffdfffffbfffff7ULL, 0xffbfffff7ffffeffULL, 0xf7ffffefffffdfffULL,
0xfffefffffdfffffbULL, 0xffdfffffbfffff7fULL, 0xfbfffff7ffffefffULL, 0x7ffffefffffdffffULL, 0xffffdfffffbfffffULL, 0xfffbfffff7ffffefULL, 0xff7ffffefffffdffULL, 0xefffffdfffffbfffULL,
0xfffdfffffbfffff7ULL, 0xffbfffff7ffffeffULL, 0xf7ffffefffffdfffULL, 0xfffffdfffffbffffULL, 0xffffbfffff7ffffeULL, 0xfff7ffffefffffdfULL, 0xfefffffdfffffbffULL, 0xdfffffbfffff7fffULL,
0xfffbfffff7ffffefULL, 0xff7ffffefffffdffULL, 0xefffffdfffffbfffULL, 0xfffffbfffff7ffffULL, 0xffff7ffffefffffdULL, 0xffefffffdfffffbfULL, 0xfdfffffbfffff7ffULL, 0xbfffff7ffffeffffULL,
0xfff7ffffefffffdfULL, 0xfefffffdfffffbffULL, 0xdfffffbfffff7fffULL, 0xfffff7ffffefffffULL, 0xfffefffffdfffffbULL, 0xffdfffffbfffff7fULL, 0xfbfffff7ffffefffULL, 0x7ffffefffffdffffULL,
0xffefffffdfffffbfULL, 0xfdfffffbfffff7ffULL, 0xbfffff7ffffeffffULL, 0xffffefffffdfffffULL, 0xfffdfffffbfffff7ULL, 0xffbfffff7ffffeffULL, 0xf7ffffefffffdfffULL, 0xfffffdfffffbffffULL,
0xffdfffffbfffff7fULL, 0xfbfffff7ffffefffULL, 0x7ffffefffffdffffULL, 0xffffdfffffbfffffULL, 0xfffbfffff7ffffefULL, 0xff7ffffefffffdffULL, 0xefffffdfffffbfffULL, 0xfffffbfffff7ffffULL,
0xffbfffff7ffffeffULL, 0xf7ffffefffffdfffULL, 0xfffffdfffffbffffULL, 0xffffbfffff7ffffeULL, 0xfff7ffffefffffdfULL, 0xfefffffdfffffbffULL, 0xdfffffbfffff7fffULL, 0xfffff7ffffefffffULL,
0xff7ffffefffffdffULL, 0xefffffdfffffbfffULL, 0xfffffbfffff7ffffULL, 0xffff7ffffefffffdULL, 0xffefffffdfffffbfULL, 0xfdfffffbfffff7ffULL, 0xbfffff7ffffeffffULL, 0xffffefffffdfffffULL,
0xfefffffdfffffbffULL, 0xdfffffbfffff7fffULL, 0xfffff7ffffefffffULL, 0xfffefffffdfffffbULL, 0xffdfffffbfffff7fULL, 0xfbfffff7ffffefffULL, 0x7ffffefffffdffffULL, 0xffffdfffffbfffffULL,
0xfdfffffbfffff7ffULL, 0xbfffff7ffffeffffULL, 0xffffefffffdfffffULL, 0xfffdfffffbfffff7ULL, 0xffbfffff7ffffeffULL, 0xf7ffffefffffdfffULL, 0xfffffdfffffbffffULL, 0xffffbfffff7ffffeULL,
0xfbfffff7ffffefffULL, 0x7ffffefffffdffffULL, 0xffffdfffffbfffffULL, 0xfffbfffff7ffffefULL, 0xff7ffffefffffdffULL, 0xefffffdfffffbfffULL, 0xfffffbfffff7ffffULL, 0xffff7ffffefffffdULL,
0xf7ffffefffffdfffULL, 0xfffffdfffffbffffULL, 0xffffbfffff7ffffeULL, 0xfff7ffffefffffdfULL, 0xfefffffdfffffbffULL, 0xdfffffbfffff7fffULL, 0xfffff7ffffefffffULL, 0xfffefffffdfffffbULL,
0xefffffdfffffbfffULL, 0xfffffbfffff7ffffULL, 0xffff7ffffefffffdULL, 0xffefffffdfffffbfULL, 0xfdfffffbfffff7ffULL, 0xbfffff7ffffeffffULL, 0xffffefffffdfffffULL, 0xfffdfffffbfffff7ULL,
0xdfffffbfffff7fffULL, 0xfffff7ffffefffffULL, 0xfffefffffdfffffbULL, 0xffdfffffbfffff7fULL, 0xfbfffff7ffffefffULL, 0x7ffffefffffdffffULL, 0xffffdfffffbfffffULL, 0xfffbfffff7ffffefULL,
0xbfffff7ffffeffffULL, 0xffffefffffdfffffULL, 0xfffdfffffbfffff7ULL, 0xffbfffff7ffffeffULL, 0xf7ffffefffffdfffULL, 0xfffffdfffffbffffULL, 0xffffbfffff7ffffeULL, 0xfff7ffffefffffdfULL,
0x7ffffefffffdffffULL, 0xffffdfffffbfffffULL, 0xfffbfffff7ffffefULL, 0xff7ffffefffffdffULL, 0xefffffdfffffbfffULL, 0xfffffbfffff7ffffULL, 0xffff7ffffefffffdULL, 0xffefffffdfffffbfULL,
0xfffffdfffffbffffULL, 0xffffbfffff7ffffeULL, 0xfff7ffffefffffdfULL, 0xfefffffdfffffbffULL, 0xdfffffbfffff7fffULL, 0xfffff7ffffefffffULL, 0xfffefffffdfffffbULL, 0xffdfffffbfffff7fULL,
0xfffffbfffff7ffffULL, 0xffff7ffffefffffdULL, 0xffefffffdfffffbfULL, 0xfdfffffbfffff7ffULL, 0xbfffff7ffffeffffULL, 0xffffefffffdfffffULL, 0xfffdfffffbfffff7ULL, 0xffbfffff7ffffeffULL,
0xfffff7ffffefffffULL, 0xfffefffffdfffffbULL, 0xffdfffffbfffff7fULL, 0xfbfffff7ffffefffULL, 0x7ffffefffffdffffULL, 0xffffdfffffbfffffULL, 0xfffbfffff7ffffefULL, 0xff7ffffefffffdffULL,
0xffffefffffdfffffULL, 0xfffdfffffbfffff7ULL, 0xffbfffff7ffffeffULL, 0xf7ffffefffffdfffULL, 0xfffffdfffffbffffULL, 0xffffbfffff7ffffeULL, 0xfff7ffffefffffdfULL, 0xfefffffdfffffbffULL,
0xffffdfffffbfffffULL, 0xfffbfffff7ffffefULL, 0xff7ffffefffffdffULL, 0xefffffdfffffbfffULL, 0xfffffbfffff7ffffULL, 0xffff7ffffefffffdULL, 0xffefffffdfffffbfULL, 0xfdfffffbfffff7ffULL};
// pid = 9
uint64_t _29_MASKS_512[29 * 8] = {
0xfbffffffdffffffeULL, 0xffefffffff7fffffULL, 0xffffbffffffdffffULL, 0xfffffefffffff7ffULL, 0x7ffffffbffffffdfULL, 0xfdffffffefffffffULL, 0xfff7ffffffbfffffULL, 0xffffdffffffeffffULL,
0xf7ffffffbffffffdULL, 0xffdffffffeffffffULL, 0xffff7ffffffbffffULL, 0xfffffdffffffefffULL, 0xfffffff7ffffffbfULL, 0xfbffffffdffffffeULL, 0xffefffffff7fffffULL, 0xffffbffffffdffffULL,
0xefffffff7ffffffbULL, 0xffbffffffdffffffULL, 0xfffefffffff7ffffULL, 0xfffffbffffffdfffULL, 0xffffffefffffff7fULL, 0xf7ffffffbffffffdULL, 0xffdffffffeffffffULL, 0xffff7ffffffbffffULL,
0xdffffffefffffff7ULL, 0xff7ffffffbffffffULL, 0xfffdffffffefffffULL, 0xfffff7ffffffbfffULL, 0xffffffdffffffeffULL, 0xefffffff7ffffffbULL, 0xffbffffffdffffffULL, 0xfffefffffff7ffffULL,
0xbffffffdffffffefULL, 0xfefffffff7ffffffULL, 0xfffbffffffdfffffULL, 0xffffefffffff7fffULL, 0xffffffbffffffdffULL, 0xdffffffefffffff7ULL, 0xff7ffffffbffffffULL, 0xfffdffffffefffffULL,
0x7ffffffbffffffdfULL, 0xfdffffffefffffffULL, 0xfff7ffffffbfffffULL, 0xffffdffffffeffffULL, 0xffffff7ffffffbffULL, 0xbffffffdffffffefULL, 0xfefffffff7ffffffULL, 0xfffbffffffdfffffULL,
0xfffffff7ffffffbfULL, 0xfbffffffdffffffeULL, 0xffefffffff7fffffULL, 0xffffbffffffdffffULL, 0xfffffefffffff7ffULL, 0x7ffffffbffffffdfULL, 0xfdffffffefffffffULL, 0xfff7ffffffbfffffULL,
0xffffffefffffff7fULL, 0xf7ffffffbffffffdULL, 0xffdffffffeffffffULL, 0xffff7ffffffbffffULL, 0xfffffdffffffefffULL, 0xfffffff7ffffffbfULL, 0xfbffffffdffffffeULL, 0xffefffffff7fffffULL,
0xffffffdffffffeffULL, 0xefffffff7ffffffbULL, 0xffbffffffdffffffULL, 0xfffefffffff7ffffULL, 0xfffffbffffffdfffULL, 0xffffffefffffff7fULL, 0xf7ffffffbffffffdULL, 0xffdffffffeffffffULL,
0xffffffbffffffdffULL, 0xdffffffefffffff7ULL, 0xff7ffffffbffffffULL, 0xfffdffffffefffffULL, 0xfffff7ffffffbfffULL, 0xffffffdffffffeffULL, 0xefffffff7ffffffbULL, 0xffbffffffdffffffULL,
0xffffff7ffffffbffULL, 0xbffffffdffffffefULL, 0xfefffffff7ffffffULL, 0xfffbffffffdfffffULL, 0xffffefffffff7fffULL, 0xffffffbffffffdffULL, 0xdffffffefffffff7ULL, 0xff7ffffffbffffffULL,
0xfffffefffffff7ffULL, 0x7ffffffbffffffdfULL, 0xfdffffffefffffffULL, 0xfff7ffffffbfffffULL, 0xffffdffffffeffffULL, 0xffffff7ffffffbffULL, 0xbffffffdffffffefULL, 0xfefffffff7ffffffULL,
0xfffffdffffffefffULL, 0xfffffff7ffffffbfULL, 0xfbffffffdffffffeULL, 0xffefffffff7fffffULL, 0xffffbffffffdffffULL, 0xfffffefffffff7ffULL, 0x7ffffffbffffffdfULL, 0xfdffffffefffffffULL,
0xfffffbffffffdfffULL, 0xffffffefffffff7fULL, 0xf7ffffffbffffffdULL, 0xffdffffffeffffffULL, 0xffff7ffffffbffffULL, 0xfffffdffffffefffULL, 0xfffffff7ffffffbfULL, 0xfbffffffdffffffeULL,
0xfffff7ffffffbfffULL, 0xffffffdffffffeffULL, 0xefffffff7ffffffbULL, 0xffbffffffdffffffULL, 0xfffefffffff7ffffULL, 0xfffffbffffffdfffULL, 0xffffffefffffff7fULL, 0xf7ffffffbffffffdULL,
0xffffefffffff7fffULL, 0xffffffbffffffdffULL, 0xdffffffefffffff7ULL, 0xff7ffffffbffffffULL, 0xfffdffffffefffffULL, 0xfffff7ffffffbfffULL, 0xffffffdffffffeffULL, 0xefffffff7ffffffbULL,
0xffffdffffffeffffULL, 0xffffff7ffffffbffULL, 0xbffffffdffffffefULL, 0xfefffffff7ffffffULL, 0xfffbffffffdfffffULL, 0xffffefffffff7fffULL, 0xffffffbffffffdffULL, 0xdffffffefffffff7ULL,
0xffffbffffffdffffULL, 0xfffffefffffff7ffULL, 0x7ffffffbffffffdfULL, 0xfdffffffefffffffULL, 0xfff7ffffffbfffffULL, 0xffffdffffffeffffULL, 0xffffff7ffffffbffULL, 0xbffffffdffffffefULL,
0xffff7ffffffbffffULL, 0xfffffdffffffefffULL, 0xfffffff7ffffffbfULL, 0xfbffffffdffffffeULL, 0xffefffffff7fffffULL, 0xffffbffffffdffffULL, 0xfffffefffffff7ffULL, 0x7ffffffbffffffdfULL,
0xfffefffffff7ffffULL, 0xfffffbffffffdfffULL, 0xffffffefffffff7fULL, 0xf7ffffffbffffffdULL, 0xffdffffffeffffffULL, 0xffff7ffffffbffffULL, 0xfffffdffffffefffULL, 0xfffffff7ffffffbfULL,
0xfffdffffffefffffULL, 0xfffff7ffffffbfffULL, 0xffffffdffffffeffULL, 0xefffffff7ffffffbULL, 0xffbffffffdffffffULL, 0xfffefffffff7ffffULL, 0xfffffbffffffdfffULL, 0xffffffefffffff7fULL,
0xfffbffffffdfffffULL, 0xffffefffffff7fffULL, 0xffffffbffffffdffULL, 0xdffffffefffffff7ULL, 0xff7ffffffbffffffULL, 0xfffdffffffefffffULL, 0xfffff7ffffffbfffULL, 0xffffffdffffffeffULL,
0xfff7ffffffbfffffULL, 0xffffdffffffeffffULL, 0xffffff7ffffffbffULL, 0xbffffffdffffffefULL, 0xfefffffff7ffffffULL, 0xfffbffffffdfffffULL, 0xffffefffffff7fffULL, 0xffffffbffffffdffULL,
0xffefffffff7fffffULL, 0xffffbffffffdffffULL, 0xfffffefffffff7ffULL, 0x7ffffffbffffffdfULL, 0xfdffffffefffffffULL, 0xfff7ffffffbfffffULL, 0xffffdffffffeffffULL, 0xffffff7ffffffbffULL,
0xffdffffffeffffffULL, 0xffff7ffffffbffffULL, 0xfffffdffffffefffULL, 0xfffffff7ffffffbfULL, 0xfbffffffdffffffeULL, 0xffefffffff7fffffULL, 0xffffbffffffdffffULL, 0xfffffefffffff7ffULL,
0xffbffffffdffffffULL, 0xfffefffffff7ffffULL, 0xfffffbffffffdfffULL, 0xffffffefffffff7fULL, 0xf7ffffffbffffffdULL, 0xffdffffffeffffffULL, 0xffff7ffffffbffffULL, 0xfffffdffffffefffULL,
0xff7ffffffbffffffULL, 0xfffdffffffefffffULL, 0xfffff7ffffffbfffULL, 0xffffffdffffffeffULL, 0xefffffff7ffffffbULL, 0xffbffffffdffffffULL, 0xfffefffffff7ffffULL, 0xfffffbffffffdfffULL,
0xfefffffff7ffffffULL, 0xfffbffffffdfffffULL, 0xffffefffffff7fffULL, 0xffffffbffffffdffULL, 0xdffffffefffffff7ULL, 0xff7ffffffbffffffULL, 0xfffdffffffefffffULL, 0xfffff7ffffffbfffULL,
0xfdffffffefffffffULL, 0xfff7ffffffbfffffULL, 0xffffdffffffeffffULL, 0xffffff7ffffffbffULL, 0xbffffffdffffffefULL, 0xfefffffff7ffffffULL, 0xfffbffffffdfffffULL, 0xffffefffffff7fffULL};
// pid = 10
uint64_t _31_MASKS_512[31 * 8] = {
0xbfffffff7ffffffeULL, 0xefffffffdfffffffULL, 0xfbfffffff7ffffffULL, 0xfefffffffdffffffULL, 0xffbfffffff7fffffULL, 0xffefffffffdfffffULL, 0xfffbfffffff7ffffULL, 0xfffefffffffdffffULL,
0x7ffffffefffffffdULL, 0xdfffffffbfffffffULL, 0xf7ffffffefffffffULL, 0xfdfffffffbffffffULL, 0xff7ffffffeffffffULL, 0xffdfffffffbfffffULL, 0xfff7ffffffefffffULL, 0xfffdfffffffbffffULL,
0xfffffffdfffffffbULL, 0xbfffffff7ffffffeULL, 0xefffffffdfffffffULL, 0xfbfffffff7ffffffULL, 0xfefffffffdffffffULL, 0xffbfffffff7fffffULL, 0xffefffffffdfffffULL, 0xfffbfffffff7ffffULL,
0xfffffffbfffffff7ULL, 0x7ffffffefffffffdULL, 0xdfffffffbfffffffULL, 0xf7ffffffefffffffULL, 0xfdfffffffbffffffULL, 0xff7ffffffeffffffULL, 0xffdfffffffbfffffULL, 0xfff7ffffffefffffULL,
0xfffffff7ffffffefULL, 0xfffffffdfffffffbULL, 0xbfffffff7ffffffeULL, 0xefffffffdfffffffULL, 0xfbfffffff7ffffffULL, 0xfefffffffdffffffULL, 0xffbfffffff7fffffULL, 0xffefffffffdfffffULL,
0xffffffefffffffdfULL, 0xfffffffbfffffff7ULL, 0x7ffffffefffffffdULL, 0xdfffffffbfffffffULL, 0xf7ffffffefffffffULL, 0xfdfffffffbffffffULL, 0xff7ffffffeffffffULL, 0xffdfffffffbfffffULL,
0xffffffdfffffffbfULL, 0xfffffff7ffffffefULL, 0xfffffffdfffffffbULL, 0xbfffffff7ffffffeULL, 0xefffffffdfffffffULL, 0xfbfffffff7ffffffULL, 0xfefffffffdffffffULL, 0xffbfffffff7fffffULL,
0xffffffbfffffff7fULL, 0xffffffefffffffdfULL, 0xfffffffbfffffff7ULL, 0x7ffffffefffffffdULL, 0xdfffffffbfffffffULL, 0xf7ffffffefffffffULL, 0xfdfffffffbffffffULL, 0xff7ffffffeffffffULL,
0xffffff7ffffffeffULL, 0xffffffdfffffffbfULL, 0xfffffff7ffffffefULL, 0xfffffffdfffffffbULL, 0xbfffffff7ffffffeULL, 0xefffffffdfffffffULL, 0xfbfffffff7ffffffULL, 0xfefffffffdffffffULL,
0xfffffefffffffdffULL, 0xffffffbfffffff7fULL, 0xffffffefffffffdfULL, 0xfffffffbfffffff7ULL, 0x7ffffffefffffffdULL, 0xdfffffffbfffffffULL, 0xf7ffffffefffffffULL, 0xfdfffffffbffffffULL,
0xfffffdfffffffbffULL, 0xffffff7ffffffeffULL, 0xffffffdfffffffbfULL, 0xfffffff7ffffffefULL, 0xfffffffdfffffffbULL, 0xbfffffff7ffffffeULL, 0xefffffffdfffffffULL, 0xfbfffffff7ffffffULL,
0xfffffbfffffff7ffULL, 0xfffffefffffffdffULL, 0xffffffbfffffff7fULL, 0xffffffefffffffdfULL, 0xfffffffbfffffff7ULL, 0x7ffffffefffffffdULL, 0xdfffffffbfffffffULL, 0xf7ffffffefffffffULL,
0xfffff7ffffffefffULL, 0xfffffdfffffffbffULL, 0xffffff7ffffffeffULL, 0xffffffdfffffffbfULL, 0xfffffff7ffffffefULL, 0xfffffffdfffffffbULL, 0xbfffffff7ffffffeULL, 0xefffffffdfffffffULL,
0xffffefffffffdfffULL, 0xfffffbfffffff7ffULL, 0xfffffefffffffdffULL, 0xffffffbfffffff7fULL, 0xffffffefffffffdfULL, 0xfffffffbfffffff7ULL, 0x7ffffffefffffffdULL, 0xdfffffffbfffffffULL,
0xffffdfffffffbfffULL, 0xfffff7ffffffefffULL, 0xfffffdfffffffbffULL, 0xffffff7ffffffeffULL, 0xffffffdfffffffbfULL, 0xfffffff7ffffffefULL, 0xfffffffdfffffffbULL, 0xbfffffff7ffffffeULL,
0xffffbfffffff7fffULL, 0xffffefffffffdfffULL, 0xfffffbfffffff7ffULL, 0xfffffefffffffdffULL, 0xffffffbfffffff7fULL, 0xffffffefffffffdfULL, 0xfffffffbfffffff7ULL, 0x7ffffffefffffffdULL,
0xffff7ffffffeffffULL, 0xffffdfffffffbfffULL, 0xfffff7ffffffefffULL, 0xfffffdfffffffbffULL, 0xffffff7ffffffeffULL, 0xffffffdfffffffbfULL, 0xfffffff7ffffffefULL, 0xfffffffdfffffffbULL,
0xfffefffffffdffffULL, 0xffffbfffffff7fffULL, 0xffffefffffffdfffULL, 0xfffffbfffffff7ffULL, 0xfffffefffffffdffULL, 0xffffffbfffffff7fULL, 0xffffffefffffffdfULL, 0xfffffffbfffffff7ULL,
0xfffdfffffffbffffULL, 0xffff7ffffffeffffULL, 0xffffdfffffffbfffULL, 0xfffff7ffffffefffULL, 0xfffffdfffffffbffULL, 0xffffff7ffffffeffULL, 0xffffffdfffffffbfULL, 0xfffffff7ffffffefULL,
0xfffbfffffff7ffffULL, 0xfffefffffffdffffULL, 0xffffbfffffff7fffULL, 0xffffefffffffdfffULL, 0xfffffbfffffff7ffULL, 0xfffffefffffffdffULL, 0xffffffbfffffff7fULL, 0xffffffefffffffdfULL,
0xfff7ffffffefffffULL, 0xfffdfffffffbffffULL, 0xffff7ffffffeffffULL, 0xffffdfffffffbfffULL, 0xfffff7ffffffefffULL, 0xfffffdfffffffbffULL, 0xffffff7ffffffeffULL, 0xffffffdfffffffbfULL,
0xffefffffffdfffffULL, 0xfffbfffffff7ffffULL, 0xfffefffffffdffffULL, 0xffffbfffffff7fffULL, 0xffffefffffffdfffULL, 0xfffffbfffffff7ffULL, 0xfffffefffffffdffULL, 0xffffffbfffffff7fULL,
0xffdfffffffbfffffULL, 0xfff7ffffffefffffULL, 0xfffdfffffffbffffULL, 0xffff7ffffffeffffULL, 0xffffdfffffffbfffULL, 0xfffff7ffffffefffULL, 0xfffffdfffffffbffULL, 0xffffff7ffffffeffULL,
0xffbfffffff7fffffULL, 0xffefffffffdfffffULL, 0xfffbfffffff7ffffULL, 0xfffefffffffdffffULL, 0xffffbfffffff7fffULL, 0xffffefffffffdfffULL, 0xfffffbfffffff7ffULL, 0xfffffefffffffdffULL,
0xff7ffffffeffffffULL, 0xffdfffffffbfffffULL, 0xfff7ffffffefffffULL, 0xfffdfffffffbffffULL, 0xffff7ffffffeffffULL, 0xffffdfffffffbfffULL, 0xfffff7ffffffefffULL, 0xfffffdfffffffbffULL,
0xfefffffffdffffffULL, 0xffbfffffff7fffffULL, 0xffefffffffdfffffULL, 0xfffbfffffff7ffffULL, 0xfffefffffffdffffULL, 0xffffbfffffff7fffULL, 0xffffefffffffdfffULL, 0xfffffbfffffff7ffULL,
0xfdfffffffbffffffULL, 0xff7ffffffeffffffULL, 0xffdfffffffbfffffULL, 0xfff7ffffffefffffULL, 0xfffdfffffffbffffULL, 0xffff7ffffffeffffULL, 0xffffdfffffffbfffULL, 0xfffff7ffffffefffULL,
0xfbfffffff7ffffffULL, 0xfefffffffdffffffULL, 0xffbfffffff7fffffULL, 0xffefffffffdfffffULL, 0xfffbfffffff7ffffULL, 0xfffefffffffdffffULL, 0xffffbfffffff7fffULL, 0xffffefffffffdfffULL,
0xf7ffffffefffffffULL, 0xfdfffffffbffffffULL, 0xff7ffffffeffffffULL, 0xffdfffffffbfffffULL, 0xfff7ffffffefffffULL, 0xfffdfffffffbffffULL, 0xffff7ffffffeffffULL, 0xffffdfffffffbfffULL,
0xefffffffdfffffffULL, 0xfbfffffff7ffffffULL, 0xfefffffffdffffffULL, 0xffbfffffff7fffffULL, 0xffefffffffdfffffULL, 0xfffbfffffff7ffffULL, 0xfffefffffffdffffULL, 0xffffbfffffff7fffULL,
0xdfffffffbfffffffULL, 0xf7ffffffefffffffULL, 0xfdfffffffbffffffULL, 0xff7ffffffeffffffULL, 0xffdfffffffbfffffULL, 0xfff7ffffffefffffULL, 0xfffdfffffffbffffULL, 0xffff7ffffffeffffULL};
// pid = 11 (p = 37, 2368 bytes)
uint64_t _37_MASKS_512[37 * 8] = {
0xffffffdffffffffeULL, 0xffff7ffffffffbffULL, 0xfdffffffffefffffULL, 0xffffffffbfffffffULL, 0xfffffefffffffff7ULL, 0xfffbffffffffdfffULL, 0xefffffffff7fffffULL, 0xfffffffdffffffffULL,
0xffffffbffffffffdULL, 0xfffefffffffff7ffULL, 0xfbffffffffdfffffULL, 0xffffffff7fffffffULL, 0xfffffdffffffffefULL, 0xfff7ffffffffbfffULL, 0xdffffffffeffffffULL, 0xfffffffbffffffffULL,
0xffffff7ffffffffbULL, 0xfffdffffffffefffULL, 0xf7ffffffffbfffffULL, 0xfffffffeffffffffULL, 0xfffffbffffffffdfULL, 0xffefffffffff7fffULL, 0xbffffffffdffffffULL, 0xfffffff7ffffffffULL,
0xfffffefffffffff7ULL, 0xfffbffffffffdfffULL, 0xefffffffff7fffffULL, 0xfffffffdffffffffULL, 0xfffff7ffffffffbfULL, 0xffdffffffffeffffULL, 0x7ffffffffbffffffULL, 0xffffffefffffffffULL,
0xfffffdffffffffefULL, 0xfff7ffffffffbfffULL, 0xdffffffffeffffffULL, 0xfffffffbffffffffULL, 0xffffefffffffff7fULL, 0xffbffffffffdffffULL, 0xfffffffff7ffffffULL, 0xffffffdffffffffeULL,
0xfffffbffffffffdfULL, 0xffefffffffff7fffULL, 0xbffffffffdffffffULL, 0xfffffff7ffffffffULL, 0xffffdffffffffeffULL, 0xff7ffffffffbffffULL, 0xffffffffefffffffULL, 0xffffffbffffffffdULL,
0xfffff7ffffffffbfULL, 0xffdffffffffeffffULL, 0x7ffffffffbffffffULL, 0xffffffefffffffffULL, 0xffffbffffffffdffULL, 0xfefffffffff7ffffULL, 0xffffffffdfffffffULL, 0xffffff7ffffffffbULL,
0xffffefffffffff7fULL, 0xffbffffffffdffffULL, 0xfffffffff7ffffffULL, 0xffffffdffffffffeULL, 0xffff7ffffffffbffULL, 0xfdffffffffefffffULL, 0xffffffffbfffffffULL, 0xfffffefffffffff7ULL,
0xffffdffffffffeffULL, 0xff7ffffffffbffffULL, 0xffffffffefffffffULL, 0xffffffbffffffffdULL, 0xfffefffffffff7ffULL, 0xfbffffffffdfffffULL, 0xffffffff7fffffffULL, 0xfffffdffffffffefULL,
0xffffbffffffffdffULL, 0xfefffffffff7ffffULL, 0xffffffffdfffffffULL, 0xffffff7ffffffffbULL, 0xfffdffffffffefffULL, 0xf7ffffffffbfffffULL, 0xfffffffeffffffffULL, 0xfffffbffffffffdfULL,
0xffff7ffffffffbffULL, 0xfdffffffffefffffULL, 0xffffffffbfffffffULL, 0xfffffefffffffff7ULL, 0xfffbffffffffdfffULL, 0xefffffffff7fffffULL, 0xfffffffdffffffffULL, 0xfffff7ffffffffbfULL,
0xfffefffffffff7ffULL, 0xfbffffffffdfffffULL, 0xffffffff7fffffffULL, 0xfffffdffffffffefULL, 0xfff7ffffffffbfffULL, 0xdffffffffeffffffULL, 0xfffffffbffffffffULL, 0xffffefffffffff7fULL,
0xfffdffffffffefffULL, 0xf7ffffffffbfffffULL, 0xfffffffeffffffffULL, 0xfffffbffffffffdfULL, 0xffefffffffff7fffULL, 0xbffffffffdffffffULL, 0xfffffff7ffffffffULL, 0xffffdffffffffeffULL,
0xfffbffffffffdfffULL, 0xefffffffff7fffffULL, 0xfffffffdffffffffULL, 0xfffff7ffffffffbfULL, 0xffdffffffffeffffULL, 0x7ffffffffbffffffULL, 0xffffffefffffffffULL, 0xffffbffffffffdffULL,
0xfff7ffffffffbfffULL, 0xdffffffffeffffffULL, 0xfffffffbffffffffULL, 0xffffefffffffff7fULL, 0xffbffffffffdffffULL, 0xfffffffff7ffffffULL, 0xffffffdffffffffeULL, 0xffff7ffffffffbffULL,
0xffefffffffff7fffULL, 0xbffffffffdffffffULL, 0xfffffff7ffffffffULL, 0xffffdffffffffeffULL, 0xff7ffffffffbffffULL, 0xffffffffefffffffULL, 0xffffffbffffffffdULL, 0xfffefffffffff7ffULL,
0xffdffffffffeffffULL, 0x7ffffffffbffffffULL, 0xffffffefffffffffULL, 0xffffbffffffffdffULL, 0xfefffffffff7ffffULL, 0xffffffffdfffffffULL, 0xffffff7ffffffffbULL, 0xfffdffffffffefffULL,
0xffbffffffffdffffULL, 0xfffffffff7ffffffULL, 0xffffffdffffffffeULL, 0xffff7ffffffffbffULL, 0xfdffffffffefffffULL, 0xffffffffbfffffffULL, 0xfffffefffffffff7ULL, 0xfffbffffffffdfffULL,
0xff7ffffffffbffffULL, 0xffffffffefffffffULL, 0xffffffbffffffffdULL, 0xfffefffffffff7ffULL, 0xfbffffffffdfffffULL, 0xffffffff7fffffffULL, 0xfffffdffffffffefULL, 0xfff7ffffffffbfffULL,
0xfefffffffff7ffffULL, 0xffffffffdfffffffULL, 0xffffff7ffffffffbULL, 0xfffdffffffffefffULL, 0xf7ffffffffbfffffULL, 0xfffffffeffffffffULL, 0xfffffbffffffffdfULL, 0xffefffffffff7fffULL,
0xfdffffffffefffffULL, 0xffffffffbfffffffULL, 0xfffffefffffffff7ULL, 0xfffbffffffffdfffULL, 0xefffffffff7fffffULL, 0xfffffffdffffffffULL, 0xfffff7ffffffffbfULL, 0xffdffffffffeffffULL,
0xfbffffffffdfffffULL, 0xffffffff7fffffffULL, 0xfffffdffffffffefULL, 0xfff7ffffffffbfffULL, 0xdffffffffeffffffULL, 0xfffffffbffffffffULL, 0xffffefffffffff7fULL, 0xffbffffffffdffffULL,
0xf7ffffffffbfffffULL, 0xfffffffeffffffffULL, 0xfffffbffffffffdfULL, 0xffefffffffff7fffULL, 0xbffffffffdffffffULL, 0xfffffff7ffffffffULL, 0xffffdffffffffeffULL, 0xff7ffffffffbffffULL,
0xefffffffff7fffffULL, 0xfffffffdffffffffULL, 0xfffff7ffffffffbfULL, 0xffdffffffffeffffULL, 0x7ffffffffbffffffULL, 0xffffffefffffffffULL, 0xffffbffffffffdffULL, 0xfefffffffff7ffffULL,
0xdffffffffeffffffULL, 0xfffffffbffffffffULL, 0xffffefffffffff7fULL, 0xffbffffffffdffffULL, 0xfffffffff7ffffffULL, 0xffffffdffffffffeULL, 0xffff7ffffffffbffULL, 0xfdffffffffefffffULL,
0xbffffffffdffffffULL, 0xfffffff7ffffffffULL, 0xffffdffffffffeffULL, 0xff7ffffffffbffffULL, 0xffffffffefffffffULL, 0xffffffbffffffffdULL, 0xfffefffffffff7ffULL, 0xfbffffffffdfffffULL,
0x7ffffffffbffffffULL, 0xffffffefffffffffULL, 0xffffbffffffffdffULL, 0xfefffffffff7ffffULL, 0xffffffffdfffffffULL, 0xffffff7ffffffffbULL, 0xfffdffffffffefffULL, 0xf7ffffffffbfffffULL,
0xfffffffff7ffffffULL, 0xffffffdffffffffeULL, 0xffff7ffffffffbffULL, 0xfdffffffffefffffULL, 0xffffffffbfffffffULL, 0xfffffefffffffff7ULL, 0xfffbffffffffdfffULL, 0xefffffffff7fffffULL,
0xffffffffefffffffULL, 0xffffffbffffffffdULL, 0xfffefffffffff7ffULL, 0xfbffffffffdfffffULL, 0xffffffff7fffffffULL, 0xfffffdffffffffefULL, 0xfff7ffffffffbfffULL, 0xdffffffffeffffffULL,
0xffffffffdfffffffULL, 0xffffff7ffffffffbULL, 0xfffdffffffffefffULL, 0xf7ffffffffbfffffULL, 0xfffffffeffffffffULL, 0xfffffbffffffffdfULL, 0xffefffffffff7fffULL, 0xbffffffffdffffffULL,
0xffffffffbfffffffULL, 0xfffffefffffffff7ULL, 0xfffbffffffffdfffULL, 0xefffffffff7fffffULL, 0xfffffffdffffffffULL, 0xfffff7ffffffffbfULL, 0xffdffffffffeffffULL, 0x7ffffffffbffffffULL,
0xffffffff7fffffffULL, 0xfffffdffffffffefULL, 0xfff7ffffffffbfffULL, 0xdffffffffeffffffULL, 0xfffffffbffffffffULL, 0xffffefffffffff7fULL, 0xffbffffffffdffffULL, 0xfffffffff7ffffffULL,
0xfffffffeffffffffULL, 0xfffffbffffffffdfULL, 0xffefffffffff7fffULL, 0xbffffffffdffffffULL, 0xfffffff7ffffffffULL, 0xffffdffffffffeffULL, 0xff7ffffffffbffffULL, 0xffffffffefffffffULL,
0xfffffffdffffffffULL, 0xfffff7ffffffffbfULL, 0xffdffffffffeffffULL, 0x7ffffffffbffffffULL, 0xffffffefffffffffULL, 0xffffbffffffffdffULL, 0xfefffffffff7ffffULL, 0xffffffffdfffffffULL,
0xfffffffbffffffffULL, 0xffffefffffffff7fULL, 0xffbffffffffdffffULL, 0xfffffffff7ffffffULL, 0xffffffdffffffffeULL, 0xffff7ffffffffbffULL, 0xfdffffffffefffffULL, 0xffffffffbfffffffULL,
0xfffffff7ffffffffULL, 0xffffdffffffffeffULL, 0xff7ffffffffbffffULL, 0xffffffffefffffffULL, 0xffffffbffffffffdULL, 0xfffefffffffff7ffULL, 0xfbffffffffdfffffULL, 0xffffffff7fffffffULL,
0xffffffefffffffffULL, 0xffffbffffffffdffULL, 0xfefffffffff7ffffULL, 0xffffffffdfffffffULL, 0xffffff7ffffffffbULL, 0xfffdffffffffefffULL, 0xf7ffffffffbfffffULL, 0xfffffffeffffffffULL};
// pid = 12 (p = 41, 2624 bytes)
uint64_t _41_MASKS_512[41 * 8] = {
0xfffffdfffffffffeULL, 0xf7fffffffffbffffULL, 0xffffffefffffffffULL, 0xffbfffffffffdfffULL, 0xffffffff7fffffffULL, 0xfffdfffffffffeffULL, 0xfffffffffbffffffULL, 0xffffeffffffffff7ULL,
0xfffffbfffffffffdULL, 0xeffffffffff7ffffULL, 0xffffffdfffffffffULL, 0xff7fffffffffbfffULL, 0xfffffffeffffffffULL, 0xfffbfffffffffdffULL, 0xfffffffff7ffffffULL, 0xffffdfffffffffefULL,
0xfffff7fffffffffbULL, 0xdfffffffffefffffULL, 0xffffffbfffffffffULL, 0xfeffffffffff7fffULL, 0xfffffffdffffffffULL, 0xfff7fffffffffbffULL, 0xffffffffefffffffULL, 0xffffbfffffffffdfULL,
0xffffeffffffffff7ULL, 0xbfffffffffdfffffULL, 0xffffff7fffffffffULL, 0xfdfffffffffeffffULL, 0xfffffffbffffffffULL, 0xffeffffffffff7ffULL, 0xffffffffdfffffffULL, 0xffff7fffffffffbfULL,
0xffffdfffffffffefULL, 0x7fffffffffbfffffULL, 0xfffffeffffffffffULL, 0xfbfffffffffdffffULL, 0xfffffff7ffffffffULL, 0xffdfffffffffefffULL, 0xffffffffbfffffffULL, 0xfffeffffffffff7fULL,
0xffffbfffffffffdfULL, 0xffffffffff7fffffULL, 0xfffffdfffffffffeULL, 0xf7fffffffffbffffULL, 0xffffffefffffffffULL, 0xffbfffffffffdfffULL, 0xffffffff7fffffffULL, 0xfffdfffffffffeffULL,
0xffff7fffffffffbfULL, 0xfffffffffeffffffULL, 0xfffffbfffffffffdULL, 0xeffffffffff7ffffULL, 0xffffffdfffffffffULL, 0xff7fffffffffbfffULL, 0xfffffffeffffffffULL, 0xfffbfffffffffdffULL,
0xfffeffffffffff7fULL, 0xfffffffffdffffffULL, 0xfffff7fffffffffbULL, 0xdfffffffffefffffULL, 0xffffffbfffffffffULL, 0xfeffffffffff7fffULL, 0xfffffffdffffffffULL, 0xfff7fffffffffbffULL,
0xfffdfffffffffeffULL, 0xfffffffffbffffffULL, 0xffffeffffffffff7ULL, 0xbfffffffffdfffffULL, 0xffffff7fffffffffULL, 0xfdfffffffffeffffULL, 0xfffffffbffffffffULL, 0xffeffffffffff7ffULL,
0xfffbfffffffffdffULL, 0xfffffffff7ffffffULL, 0xffffdfffffffffefULL, 0x7fffffffffbfffffULL, 0xfffffeffffffffffULL, 0xfbfffffffffdffffULL, 0xfffffff7ffffffffULL, 0xffdfffffffffefffULL,
0xfff7fffffffffbffULL, 0xffffffffefffffffULL, 0xffffbfffffffffdfULL, 0xffffffffff7fffffULL, 0xfffffdfffffffffeULL, 0xf7fffffffffbffffULL, 0xffffffefffffffffULL, 0xffbfffffffffdfffULL,
0xffeffffffffff7ffULL, 0xffffffffdfffffffULL, 0xffff7fffffffffbfULL, 0xfffffffffeffffffULL, 0xfffffbfffffffffdULL, 0xeffffffffff7ffffULL, 0xffffffdfffffffffULL, 0xff7fffffffffbfffULL,
0xffdfffffffffefffULL, 0xffffffffbfffffffULL, 0xfffeffffffffff7fULL, 0xfffffffffdffffffULL, 0xfffff7fffffffffbULL, 0xdfffffffffefffffULL, 0xffffffbfffffffffULL, 0xfeffffffffff7fffULL,
0xffbfffffffffdfffULL, 0xffffffff7fffffffULL, 0xfffdfffffffffeffULL, 0xfffffffffbffffffULL, 0xffffeffffffffff7ULL, 0xbfffffffffdfffffULL, 0xffffff7fffffffffULL, 0xfdfffffffffeffffULL,
0xff7fffffffffbfffULL, 0xfffffffeffffffffULL, 0xfffbfffffffffdffULL, 0xfffffffff7ffffffULL, 0xffffdfffffffffefULL, 0x7fffffffffbfffffULL, 0xfffffeffffffffffULL, 0xfbfffffffffdffffULL,
0xfeffffffffff7fffULL, 0xfffffffdffffffffULL, 0xfff7fffffffffbffULL, 0xffffffffefffffffULL, 0xffffbfffffffffdfULL, 0xffffffffff7fffffULL, 0xfffffdfffffffffeULL, 0xf7fffffffffbffffULL,
0xfdfffffffffeffffULL, 0xfffffffbffffffffULL, 0xffeffffffffff7ffULL, 0xffffffffdfffffffULL, 0xffff7fffffffffbfULL, 0xfffffffffeffffffULL, 0xfffffbfffffffffdULL, 0xeffffffffff7ffffULL,
0xfbfffffffffdffffULL, 0xfffffff7ffffffffULL, 0xffdfffffffffefffULL, 0xffffffffbfffffffULL, 0xfffeffffffffff7fULL, 0xfffffffffdffffffULL, 0xfffff7fffffffffbULL, 0xdfffffffffefffffULL,
0xf7fffffffffbffffULL, 0xffffffefffffffffULL, 0xffbfffffffffdfffULL, 0xffffffff7fffffffULL, 0xfffdfffffffffeffULL, 0xfffffffffbffffffULL, 0xffffeffffffffff7ULL, 0xbfffffffffdfffffULL,
0xeffffffffff7ffffULL, 0xffffffdfffffffffULL, 0xff7fffffffffbfffULL, 0xfffffffeffffffffULL, 0xfffbfffffffffdffULL, 0xfffffffff7ffffffULL, 0xffffdfffffffffefULL, 0x7fffffffffbfffffULL,
0xdfffffffffefffffULL, 0xffffffbfffffffffULL, 0xfeffffffffff7fffULL, 0xfffffffdffffffffULL, 0xfff7fffffffffbffULL, 0xffffffffefffffffULL, 0xffffbfffffffffdfULL, 0xffffffffff7fffffULL,
0xbfffffffffdfffffULL, 0xffffff7fffffffffULL, 0xfdfffffffffeffffULL, 0xfffffffbffffffffULL, 0xffeffffffffff7ffULL, 0xffffffffdfffffffULL, 0xffff7fffffffffbfULL, 0xfffffffffeffffffULL,
0x7fffffffffbfffffULL, 0xfffffeffffffffffULL, 0xfbfffffffffdffffULL, 0xfffffff7ffffffffULL, 0xffdfffffffffefffULL, 0xffffffffbfffffffULL, 0xfffeffffffffff7fULL, 0xfffffffffdffffffULL,
0xffffffffff7fffffULL, 0xfffffdfffffffffeULL, 0xf7fffffffffbffffULL, 0xffffffefffffffffULL, 0xffbfffffffffdfffULL, 0xffffffff7fffffffULL, 0xfffdfffffffffeffULL, 0xfffffffffbffffffULL,
0xfffffffffeffffffULL, 0xfffffbfffffffffdULL, 0xeffffffffff7ffffULL, 0xffffffdfffffffffULL, 0xff7fffffffffbfffULL, 0xfffffffeffffffffULL, 0xfffbfffffffffdffULL, 0xfffffffff7ffffffULL,
0xfffffffffdffffffULL, 0xfffff7fffffffffbULL, 0xdfffffffffefffffULL, 0xffffffbfffffffffULL, 0xfeffffffffff7fffULL, 0xfffffffdffffffffULL, 0xfff7fffffffffbffULL, 0xffffffffefffffffULL,
0xfffffffffbffffffULL, 0xffffeffffffffff7ULL, 0xbfffffffffdfffffULL, 0xffffff7fffffffffULL, 0xfdfffffffffeffffULL, 0xfffffffbffffffffULL, 0xffeffffffffff7ffULL, 0xffffffffdfffffffULL,
0xfffffffff7ffffffULL, 0xffffdfffffffffefULL, 0x7fffffffffbfffffULL, 0xfffffeffffffffffULL, 0xfbfffffffffdffffULL, 0xfffffff7ffffffffULL, 0xffdfffffffffefffULL, 0xffffffffbfffffffULL,
0xffffffffefffffffULL, 0xffffbfffffffffdfULL, 0xffffffffff7fffffULL, 0xfffffdfffffffffeULL, 0xf7fffffffffbffffULL, 0xffffffefffffffffULL, 0xffbfffffffffdfffULL, 0xffffffff7fffffffULL,
0xffffffffdfffffffULL, 0xffff7fffffffffbfULL, 0xfffffffffeffffffULL, 0xfffffbfffffffffdULL, 0xeffffffffff7ffffULL, 0xffffffdfffffffffULL, 0xff7fffffffffbfffULL, 0xfffffffeffffffffULL,
0xffffffffbfffffffULL, 0xfffeffffffffff7fULL, 0xfffffffffdffffffULL, 0xfffff7fffffffffbULL, 0xdfffffffffefffffULL, 0xffffffbfffffffffULL, 0xfeffffffffff7fffULL, 0xfffffffdffffffffULL,
0xffffffff7fffffffULL, 0xfffdfffffffffeffULL, 0xfffffffffbffffffULL, 0xffffeffffffffff7ULL, 0xbfffffffffdfffffULL, 0xffffff7fffffffffULL, 0xfdfffffffffeffffULL, 0xfffffffbffffffffULL,
0xfffffffeffffffffULL, 0xfffbfffffffffdffULL, 0xfffffffff7ffffffULL, 0xffffdfffffffffefULL, 0x7fffffffffbfffffULL, 0xfffffeffffffffffULL, 0xfbfffffffffdffffULL, 0xfffffff7ffffffffULL,
0xfffffffdffffffffULL, 0xfff7fffffffffbffULL, 0xffffffffefffffffULL, 0xffffbfffffffffdfULL, 0xffffffffff7fffffULL, 0xfffffdfffffffffeULL, 0xf7fffffffffbffffULL, 0xffffffefffffffffULL,
0xfffffffbffffffffULL, 0xffeffffffffff7ffULL, 0xffffffffdfffffffULL, 0xffff7fffffffffbfULL, 0xfffffffffeffffffULL, 0xfffffbfffffffffdULL, 0xeffffffffff7ffffULL, 0xffffffdfffffffffULL,
0xfffffff7ffffffffULL, 0xffdfffffffffefffULL, 0xffffffffbfffffffULL, 0xfffeffffffffff7fULL, 0xfffffffffdffffffULL, 0xfffff7fffffffffbULL, 0xdfffffffffefffffULL, 0xffffffbfffffffffULL,
0xffffffefffffffffULL, 0xffbfffffffffdfffULL, 0xffffffff7fffffffULL, 0xfffdfffffffffeffULL, 0xfffffffffbffffffULL, 0xffffeffffffffff7ULL, 0xbfffffffffdfffffULL, 0xffffff7fffffffffULL,
0xffffffdfffffffffULL, 0xff7fffffffffbfffULL, 0xfffffffeffffffffULL, 0xfffbfffffffffdffULL, 0xfffffffff7ffffffULL, 0xffffdfffffffffefULL, 0x7fffffffffbfffffULL, 0xfffffeffffffffffULL,
0xffffffbfffffffffULL, 0xfeffffffffff7fffULL, 0xfffffffdffffffffULL, 0xfff7fffffffffbffULL, 0xffffffffefffffffULL, 0xffffbfffffffffdfULL, 0xffffffffff7fffffULL, 0xfffffdfffffffffeULL,
0xffffff7fffffffffULL, 0xfdfffffffffeffffULL, 0xfffffffbffffffffULL, 0xffeffffffffff7ffULL, 0xffffffffdfffffffULL, 0xffff7fffffffffbfULL, 0xfffffffffeffffffULL, 0xfffffbfffffffffdULL,
0xfffffeffffffffffULL, 0xfbfffffffffdffffULL, 0xfffffff7ffffffffULL, 0xffdfffffffffefffULL, 0xffffffffbfffffffULL, 0xfffeffffffffff7fULL, 0xfffffffffdffffffULL, 0xfffff7fffffffffbULL};
// pid = 13 (p = 43, 2752 bytes)
uint64_t _43_MASKS_512[43 * 8] = {
0xfffff7fffffffffeULL, 0xffffffffffbfffffULL, 0xffffeffffffffffdULL, 0xffffffffff7fffffULL, 0xffffdffffffffffbULL, 0xfffffffffeffffffULL, 0xffffbffffffffff7ULL, 0xfffffffffdffffffULL,
0xffffeffffffffffdULL, 0xffffffffff7fffffULL, 0xffffdffffffffffbULL, 0xfffffffffeffffffULL, 0xffffbffffffffff7ULL, 0xfffffffffdffffffULL, 0xffff7fffffffffefULL, 0xfffffffffbffffffULL,
0xffffdffffffffffbULL, 0xfffffffffeffffffULL, 0xffffbffffffffff7ULL, 0xfffffffffdffffffULL, 0xffff7fffffffffefULL, 0xfffffffffbffffffULL, 0xfffeffffffffffdfULL, 0xfffffffff7ffffffULL,
0xffffbffffffffff7ULL, 0xfffffffffdffffffULL, 0xffff7fffffffffefULL, 0xfffffffffbffffffULL, 0xfffeffffffffffdfULL, 0xfffffffff7ffffffULL, 0xfffdffffffffffbfULL, 0xffffffffefffffffULL,
0xffff7fffffffffefULL, 0xfffffffffbffffffULL, 0xfffeffffffffffdfULL, 0xfffffffff7ffffffULL, 0xfffdffffffffffbfULL, 0xffffffffefffffffULL, 0xfffbffffffffff7fULL, 0xffffffffdfffffffULL,
0xfffeffffffffffdfULL, 0xfffffffff7ffffffULL, 0xfffdffffffffffbfULL, 0xffffffffefffffffULL, 0xfffbffffffffff7fULL, 0xffffffffdfffffffULL, 0xfff7fffffffffeffULL, 0xffffffffbfffffffULL,
0xfffdffffffffffbfULL, 0xffffffffefffffffULL, 0xfffbffffffffff7fULL, 0xffffffffdfffffffULL, 0xfff7fffffffffeffULL, 0xffffffffbfffffffULL, 0xffeffffffffffdffULL, 0xffffffff7fffffffULL,
0xfffbffffffffff7fULL, 0xffffffffdfffffffULL, 0xfff7fffffffffeffULL, 0xffffffffbfffffffULL, 0xffeffffffffffdffULL, 0xffffffff7fffffffULL, 0xffdffffffffffbffULL, 0xfffffffeffffffffULL,
0xfff7fffffffffeffULL, 0xffffffffbfffffffULL, 0xffeffffffffffdffULL, 0xffffffff7fffffffULL, 0xffdffffffffffbffULL, 0xfffffffeffffffffULL, 0xffbffffffffff7ffULL, 0xfffffffdffffffffULL,
0xffeffffffffffdffULL, 0xffffffff7fffffffULL, 0xffdffffffffffbffULL, 0xfffffffeffffffffULL, 0xffbffffffffff7ffULL, 0xfffffffdffffffffULL, 0xff7fffffffffefffULL, 0xfffffffbffffffffULL,
0xffdffffffffffbffULL, 0xfffffffeffffffffULL, 0xffbffffffffff7ffULL, 0xfffffffdffffffffULL, 0xff7fffffffffefffULL, 0xfffffffbffffffffULL, 0xfeffffffffffdfffULL, 0xfffffff7ffffffffULL,
0xffbffffffffff7ffULL, 0xfffffffdffffffffULL, 0xff7fffffffffefffULL, 0xfffffffbffffffffULL, 0xfeffffffffffdfffULL, 0xfffffff7ffffffffULL, 0xfdffffffffffbfffULL, 0xffffffefffffffffULL,
0xff7fffffffffefffULL, 0xfffffffbffffffffULL, 0xfeffffffffffdfffULL, 0xfffffff7ffffffffULL, 0xfdffffffffffbfffULL, 0xffffffefffffffffULL, 0xfbffffffffff7fffULL, 0xffffffdfffffffffULL,
0xfeffffffffffdfffULL, 0xfffffff7ffffffffULL, 0xfdffffffffffbfffULL, 0xffffffefffffffffULL, 0xfbffffffffff7fffULL, 0xffffffdfffffffffULL, 0xf7fffffffffeffffULL, 0xffffffbfffffffffULL,
0xfdffffffffffbfffULL, 0xffffffefffffffffULL, 0xfbffffffffff7fffULL, 0xffffffdfffffffffULL, 0xf7fffffffffeffffULL, 0xffffffbfffffffffULL, 0xeffffffffffdffffULL, 0xffffff7fffffffffULL,
0xfbffffffffff7fffULL, 0xffffffdfffffffffULL, 0xf7fffffffffeffffULL, 0xffffffbfffffffffULL, 0xeffffffffffdffffULL, 0xffffff7fffffffffULL, 0xdffffffffffbffffULL, 0xfffffeffffffffffULL,
0xf7fffffffffeffffULL, 0xffffffbfffffffffULL, 0xeffffffffffdffffULL, 0xffffff7fffffffffULL, 0xdffffffffffbffffULL, 0xfffffeffffffffffULL, 0xbffffffffff7ffffULL, 0xfffffdffffffffffULL,
0xeffffffffffdffffULL, 0xffffff7fffffffffULL, 0xdffffffffffbffffULL, 0xfffffeffffffffffULL, 0xbffffffffff7ffffULL, 0xfffffdffffffffffULL, 0x7fffffffffefffffULL, 0xfffffbffffffffffULL,
0xdffffffffffbffffULL, 0xfffffeffffffffffULL, 0xbffffffffff7ffffULL, 0xfffffdffffffffffULL, 0x7fffffffffefffffULL, 0xfffffbffffffffffULL, 0xffffffffffdfffffULL, 0xfffff7fffffffffeULL,
0xbffffffffff7ffffULL, 0xfffffdffffffffffULL, 0x7fffffffffefffffULL, 0xfffffbffffffffffULL, 0xffffffffffdfffffULL, 0xfffff7fffffffffeULL, 0xffffffffffbfffffULL, 0xffffeffffffffffdULL,
0x7fffffffffefffffULL, 0xfffffbffffffffffULL, 0xffffffffffdfffffULL, 0xfffff7fffffffffeULL, 0xffffffffffbfffffULL, 0xffffeffffffffffdULL, 0xffffffffff7fffffULL, 0xffffdffffffffffbULL,
0xffffffffffdfffffULL, 0xfffff7fffffffffeULL, 0xffffffffffbfffffULL, 0xffffeffffffffffdULL, 0xffffffffff7fffffULL, 0xffffdffffffffffbULL, 0xfffffffffeffffffULL, 0xffffbffffffffff7ULL,
0xffffffffffbfffffULL, 0xffffeffffffffffdULL, 0xffffffffff7fffffULL, 0xffffdffffffffffbULL, 0xfffffffffeffffffULL, 0xffffbffffffffff7ULL, 0xfffffffffdffffffULL, 0xffff7fffffffffefULL,
0xffffffffff7fffffULL, 0xffffdffffffffffbULL, 0xfffffffffeffffffULL, 0xffffbffffffffff7ULL, 0xfffffffffdffffffULL, 0xffff7fffffffffefULL, 0xfffffffffbffffffULL, 0xfffeffffffffffdfULL,
0xfffffffffeffffffULL, 0xffffbffffffffff7ULL, 0xfffffffffdffffffULL, 0xffff7fffffffffefULL, 0xfffffffffbffffffULL, 0xfffeffffffffffdfULL, 0xfffffffff7ffffffULL, 0xfffdffffffffffbfULL,
0xfffffffffdffffffULL, 0xffff7fffffffffefULL, 0xfffffffffbffffffULL, 0xfffeffffffffffdfULL, 0xfffffffff7ffffffULL, 0xfffdffffffffffbfULL, 0xffffffffefffffffULL, 0xfffbffffffffff7fULL,
0xfffffffffbffffffULL, 0xfffeffffffffffdfULL, 0xfffffffff7ffffffULL, 0xfffdffffffffffbfULL, 0xffffffffefffffffULL, 0xfffbffffffffff7fULL, 0xffffffffdfffffffULL, 0xfff7fffffffffeffULL,
0xfffffffff7ffffffULL, 0xfffdffffffffffbfULL, 0xffffffffefffffffULL, 0xfffbffffffffff7fULL, 0xffffffffdfffffffULL, 0xfff7fffffffffeffULL, 0xffffffffbfffffffULL, 0xffeffffffffffdffULL,
0xffffffffefffffffULL, 0xfffbffffffffff7fULL, 0xffffffffdfffffffULL, 0xfff7fffffffffeffULL, 0xffffffffbfffffffULL, 0xffeffffffffffdffULL, 0xffffffff7fffffffULL, 0xffdffffffffffbffULL,
0xffffffffdfffffffULL, 0xfff7fffffffffeffULL, 0xffffffffbfffffffULL, 0xffeffffffffffdffULL, 0xffffffff7fffffffULL, 0xffdffffffffffbffULL, 0xfffffffeffffffffULL, 0xffbffffffffff7ffULL,
0xffffffffbfffffffULL, 0xffeffffffffffdffULL, 0xffffffff7fffffffULL, 0xffdffffffffffbffULL, 0xfffffffeffffffffULL, 0xffbffffffffff7ffULL, 0xfffffffdffffffffULL, 0xff7fffffffffefffULL,
0xffffffff7fffffffULL, 0xffdffffffffffbffULL, 0xfffffffeffffffffULL, 0xffbffffffffff7ffULL, 0xfffffffdffffffffULL, 0xff7fffffffffefffULL, 0xfffffffbffffffffULL, 0xfeffffffffffdfffULL,
0xfffffffeffffffffULL, 0xffbffffffffff7ffULL, 0xfffffffdffffffffULL, 0xff7fffffffffefffULL, 0xfffffffbffffffffULL, 0xfeffffffffffdfffULL, 0xfffffff7ffffffffULL, 0xfdffffffffffbfffULL,
0xfffffffdffffffffULL, 0xff7fffffffffefffULL, 0xfffffffbffffffffULL, 0xfeffffffffffdfffULL, 0xfffffff7ffffffffULL, 0xfdffffffffffbfffULL, 0xffffffefffffffffULL, 0xfbffffffffff7fffULL,
0xfffffffbffffffffULL, 0xfeffffffffffdfffULL, 0xfffffff7ffffffffULL, 0xfdffffffffffbfffULL, 0xffffffefffffffffULL, 0xfbffffffffff7fffULL, 0xffffffdfffffffffULL, 0xf7fffffffffeffffULL,
0xfffffff7ffffffffULL, 0xfdffffffffffbfffULL, 0xffffffefffffffffULL, 0xfbffffffffff7fffULL, 0xffffffdfffffffffULL, 0xf7fffffffffeffffULL, 0xffffffbfffffffffULL, 0xeffffffffffdffffULL,
0xffffffefffffffffULL, 0xfbffffffffff7fffULL, 0xffffffdfffffffffULL, 0xf7fffffffffeffffULL, 0xffffffbfffffffffULL, 0xeffffffffffdffffULL, 0xffffff7fffffffffULL, 0xdffffffffffbffffULL,
0xffffffdfffffffffULL, 0xf7fffffffffeffffULL, 0xffffffbfffffffffULL, 0xeffffffffffdffffULL, 0xffffff7fffffffffULL, 0xdffffffffffbffffULL, 0xfffffeffffffffffULL, 0xbffffffffff7ffffULL,
0xffffffbfffffffffULL, 0xeffffffffffdffffULL, 0xffffff7fffffffffULL, 0xdffffffffffbffffULL, 0xfffffeffffffffffULL, 0xbffffffffff7ffffULL, 0xfffffdffffffffffULL, 0x7fffffffffefffffULL,
0xffffff7fffffffffULL, 0xdffffffffffbffffULL, 0xfffffeffffffffffULL, 0xbffffffffff7ffffULL, 0xfffffdffffffffffULL, 0x7fffffffffefffffULL, 0xfffffbffffffffffULL, 0xffffffffffdfffffULL,
0xfffffeffffffffffULL, 0xbffffffffff7ffffULL, 0xfffffdffffffffffULL, 0x7fffffffffefffffULL, 0xfffffbffffffffffULL, 0xffffffffffdfffffULL, 0xfffff7fffffffffeULL, 0xffffffffffbfffffULL,
0xfffffdffffffffffULL, 0x7fffffffffefffffULL, 0xfffffbffffffffffULL, 0xffffffffffdfffffULL, 0xfffff7fffffffffeULL, 0xffffffffffbfffffULL, 0xffffeffffffffffdULL, 0xffffffffff7fffffULL,
0xfffffbffffffffffULL, 0xffffffffffdfffffULL, 0xfffff7fffffffffeULL, 0xffffffffffbfffffULL, 0xffffeffffffffffdULL, 0xffffffffff7fffffULL, 0xffffdffffffffffbULL, 0xfffffffffeffffffULL};
// pid = 14 (p = 47, 3008 bytes)
uint64_t _47_MASKS_512[47 * 8] = {
0xffff7ffffffffffeULL, 0xffffffffbfffffffULL, 0xefffffffffffdfffULL, 0xfffff7ffffffffffULL, 0xfffffffffbffffffULL, 0xfefffffffffffdffULL, 0xffffff7fffffffffULL, 0xffffffffffbfffffULL,
0xfffefffffffffffdULL, 0xffffffff7fffffffULL, 0xdfffffffffffbfffULL, 0xffffefffffffffffULL, 0xfffffffff7ffffffULL, 0xfdfffffffffffbffULL, 0xfffffeffffffffffULL, 0xffffffffff7fffffULL,
0xfffdfffffffffffbULL, 0xfffffffeffffffffULL, 0xbfffffffffff7fffULL, 0xffffdfffffffffffULL, 0xffffffffefffffffULL, 0xfbfffffffffff7ffULL, 0xfffffdffffffffffULL, 0xfffffffffeffffffULL,
0xfffbfffffffffff7ULL, 0xfffffffdffffffffULL, 0x7ffffffffffeffffULL, 0xffffbfffffffffffULL, 0xffffffffdfffffffULL, 0xf7ffffffffffefffULL, 0xfffffbffffffffffULL, 0xfffffffffdffffffULL,
0xfff7ffffffffffefULL, 0xfffffffbffffffffULL, 0xfffffffffffdffffULL, 0xffff7ffffffffffeULL, 0xffffffffbfffffffULL, 0xefffffffffffdfffULL, 0xfffff7ffffffffffULL, 0xfffffffffbffffffULL,
0xffefffffffffffdfULL, 0xfffffff7ffffffffULL, 0xfffffffffffbffffULL, 0xfffefffffffffffdULL, 0xffffffff7fffffffULL, 0xdfffffffffffbfffULL, 0xffffefffffffffffULL, 0xfffffffff7ffffffULL,
0xffdfffffffffffbfULL, 0xffffffefffffffffULL, 0xfffffffffff7ffffULL, 0xfffdfffffffffffbULL, 0xfffffffeffffffffULL, 0xbfffffffffff7fffULL, 0xffffdfffffffffffULL, 0xffffffffefffffffULL,
0xffbfffffffffff7fULL, 0xffffffdfffffffffULL, 0xffffffffffefffffULL, 0xfffbfffffffffff7ULL, 0xfffffffdffffffffULL, 0x7ffffffffffeffffULL, 0xffffbfffffffffffULL, 0xffffffffdfffffffULL,
0xff7ffffffffffeffULL, 0xffffffbfffffffffULL, 0xffffffffffdfffffULL, 0xfff7ffffffffffefULL, 0xfffffffbffffffffULL, 0xfffffffffffdffffULL, 0xffff7ffffffffffeULL, 0xffffffffbfffffffULL,
0xfefffffffffffdffULL, 0xffffff7fffffffffULL, 0xffffffffffbfffffULL, 0xffefffffffffffdfULL, 0xfffffff7ffffffffULL, 0xfffffffffffbffffULL, 0xfffefffffffffffdULL, 0xffffffff7fffffffULL,
0xfdfffffffffffbffULL, 0xfffffeffffffffffULL, 0xffffffffff7fffffULL, 0xffdfffffffffffbfULL, 0xffffffefffffffffULL, 0xfffffffffff7ffffULL, 0xfffdfffffffffffbULL, 0xfffffffeffffffffULL,
0xfbfffffffffff7ffULL, 0xfffffdffffffffffULL, 0xfffffffffeffffffULL, 0xffbfffffffffff7fULL, 0xffffffdfffffffffULL, 0xffffffffffefffffULL, 0xfffbfffffffffff7ULL, 0xfffffffdffffffffULL,
0xf7ffffffffffefffULL, 0xfffffbffffffffffULL, 0xfffffffffdffffffULL, 0xff7ffffffffffeffULL, 0xffffffbfffffffffULL, 0xffffffffffdfffffULL, 0xfff7ffffffffffefULL, 0xfffffffbffffffffULL,
0xefffffffffffdfffULL, 0xfffff7ffffffffffULL, 0xfffffffffbffffffULL, 0xfefffffffffffdffULL, 0xffffff7fffffffffULL, 0xffffffffffbfffffULL, 0xffefffffffffffdfULL, 0xfffffff7ffffffffULL,
0xdfffffffffffbfffULL, 0xffffefffffffffffULL, 0xfffffffff7ffffffULL, 0xfdfffffffffffbffULL, 0xfffffeffffffffffULL, 0xffffffffff7fffffULL, 0xffdfffffffffffbfULL, 0xffffffefffffffffULL,
0xbfffffffffff7fffULL, 0xffffdfffffffffffULL, 0xffffffffefffffffULL, 0xfbfffffffffff7ffULL, 0xfffffdffffffffffULL, 0xfffffffffeffffffULL, 0xffbfffffffffff7fULL, 0xffffffdfffffffffULL,
0x7ffffffffffeffffULL, 0xffffbfffffffffffULL, 0xffffffffdfffffffULL, 0xf7ffffffffffefffULL, 0xfffffbffffffffffULL, 0xfffffffffdffffffULL, 0xff7ffffffffffeffULL, 0xffffffbfffffffffULL,
0xfffffffffffdffffULL, 0xffff7ffffffffffeULL, 0xffffffffbfffffffULL, 0xefffffffffffdfffULL, 0xfffff7ffffffffffULL, 0xfffffffffbffffffULL, 0xfefffffffffffdffULL, 0xffffff7fffffffffULL,
0xfffffffffffbffffULL, 0xfffefffffffffffdULL, 0xffffffff7fffffffULL, 0xdfffffffffffbfffULL, 0xffffefffffffffffULL, 0xfffffffff7ffffffULL, 0xfdfffffffffffbffULL, 0xfffffeffffffffffULL,
0xfffffffffff7ffffULL, 0xfffdfffffffffffbULL, 0xfffffffeffffffffULL, 0xbfffffffffff7fffULL, 0xffffdfffffffffffULL, 0xffffffffefffffffULL, 0xfbfffffffffff7ffULL, 0xfffffdffffffffffULL,
0xffffffffffefffffULL, 0xfffbfffffffffff7ULL, 0xfffffffdffffffffULL, 0x7ffffffffffeffffULL, 0xffffbfffffffffffULL, 0xffffffffdfffffffULL, 0xf7ffffffffffefffULL, 0xfffffbffffffffffULL,
0xffffffffffdfffffULL, 0xfff7ffffffffffefULL, 0xfffffffbffffffffULL, 0xfffffffffffdffffULL, 0xffff7ffffffffffeULL, 0xffffffffbfffffffULL, 0xefffffffffffdfffULL, 0xfffff7ffffffffffULL,
0xffffffffffbfffffULL, 0xffefffffffffffdfULL, 0xfffffff7ffffffffULL, 0xfffffffffffbffffULL, 0xfffefffffffffffdULL, 0xffffffff7fffffffULL, 0xdfffffffffffbfffULL, 0xffffefffffffffffULL,
0xffffffffff7fffffULL, 0xffdfffffffffffbfULL, 0xffffffefffffffffULL, 0xfffffffffff7ffffULL, 0xfffdfffffffffffbULL, 0xfffffffeffffffffULL, 0xbfffffffffff7fffULL, 0xffffdfffffffffffULL,
0xfffffffffeffffffULL, 0xffbfffffffffff7fULL, 0xffffffdfffffffffULL, 0xffffffffffefffffULL, 0xfffbfffffffffff7ULL, 0xfffffffdffffffffULL, 0x7ffffffffffeffffULL, 0xffffbfffffffffffULL,
0xfffffffffdffffffULL, 0xff7ffffffffffeffULL, 0xffffffbfffffffffULL, 0xffffffffffdfffffULL, 0xfff7ffffffffffefULL, 0xfffffffbffffffffULL, 0xfffffffffffdffffULL, 0xffff7ffffffffffeULL,
0xfffffffffbffffffULL, 0xfefffffffffffdffULL, 0xffffff7fffffffffULL, 0xffffffffffbfffffULL, 0xffefffffffffffdfULL, 0xfffffff7ffffffffULL, 0xfffffffffffbffffULL, 0xfffefffffffffffdULL,
0xfffffffff7ffffffULL, 0xfdfffffffffffbffULL, 0xfffffeffffffffffULL, 0xffffffffff7fffffULL, 0xffdfffffffffffbfULL, 0xffffffefffffffffULL, 0xfffffffffff7ffffULL, 0xfffdfffffffffffbULL,
0xffffffffefffffffULL, 0xfbfffffffffff7ffULL, 0xfffffdffffffffffULL, 0xfffffffffeffffffULL, 0xffbfffffffffff7fULL, 0xffffffdfffffffffULL, 0xffffffffffefffffULL, 0xfffbfffffffffff7ULL,
0xffffffffdfffffffULL, 0xf7ffffffffffefffULL, 0xfffffbffffffffffULL, 0xfffffffffdffffffULL, 0xff7ffffffffffeffULL, 0xffffffbfffffffffULL, 0xffffffffffdfffffULL, 0xfff7ffffffffffefULL,
0xffffffffbfffffffULL, 0xefffffffffffdfffULL, 0xfffff7ffffffffffULL, 0xfffffffffbffffffULL, 0xfefffffffffffdffULL, 0xffffff7fffffffffULL, 0xffffffffffbfffffULL, 0xffefffffffffffdfULL,
0xffffffff7fffffffULL, 0xdfffffffffffbfffULL, 0xffffefffffffffffULL, 0xfffffffff7ffffffULL, 0xfdfffffffffffbffULL, 0xfffffeffffffffffULL, 0xffffffffff7fffffULL, 0xffdfffffffffffbfULL,
0xfffffffeffffffffULL, 0xbfffffffffff7fffULL, 0xffffdfffffffffffULL, 0xffffffffefffffffULL, 0xfbfffffffffff7ffULL, 0xfffffdffffffffffULL, 0xfffffffffeffffffULL, 0xffbfffffffffff7fULL,
0xfffffffdffffffffULL, 0x7ffffffffffeffffULL, 0xffffbfffffffffffULL, 0xffffffffdfffffffULL, 0xf7ffffffffffefffULL, 0xfffffbffffffffffULL, 0xfffffffffdffffffULL, 0xff7ffffffffffeffULL,
0xfffffffbffffffffULL, 0xfffffffffffdffffULL, 0xffff7ffffffffffeULL, 0xffffffffbfffffffULL, 0xefffffffffffdfffULL, 0xfffff7ffffffffffULL, 0xfffffffffbffffffULL, 0xfefffffffffffdffULL,
0xfffffff7ffffffffULL, 0xfffffffffffbffffULL, 0xfffefffffffffffdULL, 0xffffffff7fffffffULL, 0xdfffffffffffbfffULL, 0xffffefffffffffffULL, 0xfffffffff7ffffffULL, 0xfdfffffffffffbffULL,
0xffffffefffffffffULL, 0xfffffffffff7ffffULL, 0xfffdfffffffffffbULL, 0xfffffffeffffffffULL, 0xbfffffffffff7fffULL, 0xffffdfffffffffffULL, 0xffffffffefffffffULL, 0xfbfffffffffff7ffULL,
0xffffffdfffffffffULL, 0xffffffffffefffffULL, 0xfffbfffffffffff7ULL, 0xfffffffdffffffffULL, 0x7ffffffffffeffffULL, 0xffffbfffffffffffULL, 0xffffffffdfffffffULL, 0xf7ffffffffffefffULL,
0xffffffbfffffffffULL, 0xffffffffffdfffffULL, 0xfff7ffffffffffefULL, 0xfffffffbffffffffULL, 0xfffffffffffdffffULL, 0xffff7ffffffffffeULL, 0xffffffffbfffffffULL, 0xefffffffffffdfffULL,
0xffffff7fffffffffULL, 0xffffffffffbfffffULL, 0xffefffffffffffdfULL, 0xfffffff7ffffffffULL, 0xfffffffffffbffffULL, 0xfffefffffffffffdULL, 0xffffffff7fffffffULL, 0xdfffffffffffbfffULL,
0xfffffeffffffffffULL, 0xffffffffff7fffffULL, 0xffdfffffffffffbfULL, 0xffffffefffffffffULL, 0xfffffffffff7ffffULL, 0xfffdfffffffffffbULL, 0xfffffffeffffffffULL, 0xbfffffffffff7fffULL,
0xfffffdffffffffffULL, 0xfffffffffeffffffULL, 0xffbfffffffffff7fULL, 0xffffffdfffffffffULL, 0xffffffffffefffffULL, 0xfffbfffffffffff7ULL, 0xfffffffdffffffffULL, 0x7ffffffffffeffffULL,
0xfffffbffffffffffULL, 0xfffffffffdffffffULL, 0xff7ffffffffffeffULL, 0xffffffbfffffffffULL, 0xffffffffffdfffffULL, 0xfff7ffffffffffefULL, 0xfffffffbffffffffULL, 0xfffffffffffdffffULL,
0xfffff7ffffffffffULL, 0xfffffffffbffffffULL, 0xfefffffffffffdffULL, 0xffffff7fffffffffULL, 0xffffffffffbfffffULL, 0xffefffffffffffdfULL, 0xfffffff7ffffffffULL, 0xfffffffffffbffffULL,
0xffffefffffffffffULL, 0xfffffffff7ffffffULL, 0xfdfffffffffffbffULL, 0xfffffeffffffffffULL, 0xffffffffff7fffffULL, 0xffdfffffffffffbfULL, 0xffffffefffffffffULL, 0xfffffffffff7ffffULL,
0xffffdfffffffffffULL, 0xffffffffefffffffULL, 0xfbfffffffffff7ffULL, 0xfffffdffffffffffULL, 0xfffffffffeffffffULL, 0xffbfffffffffff7fULL, 0xffffffdfffffffffULL, 0xffffffffffefffffULL,
0xffffbfffffffffffULL, 0xffffffffdfffffffULL, 0xf7ffffffffffefffULL, 0xfffffbffffffffffULL, 0xfffffffffdffffffULL, 0xff7ffffffffffeffULL, 0xffffffbfffffffffULL, 0xffffffffffdfffffULL};
// pid = 15 (p = 53, 3392 bytes)
uint64_t _53_MASKS_512[53 * 8] = {
0xffdffffffffffffeULL, 0xfffffbffffffffffULL, 0xffffffff7fffffffULL, 0xffffffffffefffffULL, 0xbffffffffffffdffULL, 0xfff7ffffffffffffULL, 0xfffffeffffffffffULL, 0xffffffffdfffffffULL,
0xffbffffffffffffdULL, 0xfffff7ffffffffffULL, 0xfffffffeffffffffULL, 0xffffffffffdfffffULL, 0x7ffffffffffffbffULL, 0xffefffffffffffffULL, 0xfffffdffffffffffULL, 0xffffffffbfffffffULL,
0xff7ffffffffffffbULL, 0xffffefffffffffffULL, 0xfffffffdffffffffULL, 0xffffffffffbfffffULL, 0xfffffffffffff7ffULL, 0xffdffffffffffffeULL, 0xfffffbffffffffffULL, 0xffffffff7fffffffULL,
0xfefffffffffffff7ULL, 0xffffdfffffffffffULL, 0xfffffffbffffffffULL, 0xffffffffff7fffffULL, 0xffffffffffffefffULL, 0xffbffffffffffffdULL, 0xfffff7ffffffffffULL, 0xfffffffeffffffffULL,
0xfdffffffffffffefULL, 0xffffbfffffffffffULL, 0xfffffff7ffffffffULL, 0xfffffffffeffffffULL, 0xffffffffffffdfffULL, 0xff7ffffffffffffbULL, 0xffffefffffffffffULL, 0xfffffffdffffffffULL,
0xfbffffffffffffdfULL, 0xffff7fffffffffffULL, 0xffffffefffffffffULL, 0xfffffffffdffffffULL, 0xffffffffffffbfffULL, 0xfefffffffffffff7ULL, 0xffffdfffffffffffULL, 0xfffffffbffffffffULL,
0xf7ffffffffffffbfULL, 0xfffeffffffffffffULL, 0xffffffdfffffffffULL, 0xfffffffffbffffffULL, 0xffffffffffff7fffULL, 0xfdffffffffffffefULL, 0xffffbfffffffffffULL, 0xfffffff7ffffffffULL,
0xefffffffffffff7fULL, 0xfffdffffffffffffULL, 0xffffffbfffffffffULL, 0xfffffffff7ffffffULL, 0xfffffffffffeffffULL, 0xfbffffffffffffdfULL, 0xffff7fffffffffffULL, 0xffffffefffffffffULL,
0xdffffffffffffeffULL, 0xfffbffffffffffffULL, 0xffffff7fffffffffULL, 0xffffffffefffffffULL, 0xfffffffffffdffffULL, 0xf7ffffffffffffbfULL, 0xfffeffffffffffffULL, 0xffffffdfffffffffULL,
0xbffffffffffffdffULL, 0xfff7ffffffffffffULL, 0xfffffeffffffffffULL, 0xffffffffdfffffffULL, 0xfffffffffffbffffULL, 0xefffffffffffff7fULL, 0xfffdffffffffffffULL, 0xffffffbfffffffffULL,
0x7ffffffffffffbffULL, 0xffefffffffffffffULL, 0xfffffdffffffffffULL, 0xffffffffbfffffffULL, 0xfffffffffff7ffffULL, 0xdffffffffffffeffULL, 0xfffbffffffffffffULL, 0xffffff7fffffffffULL,
0xfffffffffffff7ffULL, 0xffdffffffffffffeULL, 0xfffffbffffffffffULL, 0xffffffff7fffffffULL, 0xffffffffffefffffULL, 0xbffffffffffffdffULL, 0xfff7ffffffffffffULL, 0xfffffeffffffffffULL,
0xffffffffffffefffULL, 0xffbffffffffffffdULL, 0xfffff7ffffffffffULL, 0xfffffffeffffffffULL, 0xffffffffffdfffffULL, 0x7ffffffffffffbffULL, 0xffefffffffffffffULL, 0xfffffdffffffffffULL,
0xffffffffffffdfffULL, 0xff7ffffffffffffbULL, 0xffffefffffffffffULL, 0xfffffffdffffffffULL, 0xffffffffffbfffffULL, 0xfffffffffffff7ffULL, 0xffdffffffffffffeULL, 0xfffffbffffffffffULL,
0xffffffffffffbfffULL, 0xfefffffffffffff7ULL, 0xffffdfffffffffffULL, 0xfffffffbffffffffULL, 0xffffffffff7fffffULL, 0xffffffffffffefffULL, 0xffbffffffffffffdULL, 0xfffff7ffffffffffULL,
0xffffffffffff7fffULL, 0xfdffffffffffffefULL, 0xffffbfffffffffffULL, 0xfffffff7ffffffffULL, 0xfffffffffeffffffULL, 0xffffffffffffdfffULL, 0xff7ffffffffffffbULL, 0xffffefffffffffffULL,
0xfffffffffffeffffULL, 0xfbffffffffffffdfULL, 0xffff7fffffffffffULL, 0xffffffefffffffffULL, 0xfffffffffdffffffULL, 0xffffffffffffbfffULL, 0xfefffffffffffff7ULL, 0xffffdfffffffffffULL,
0xfffffffffffdffffULL, 0xf7ffffffffffffbfULL, 0xfffeffffffffffffULL, 0xffffffdfffffffffULL, 0xfffffffffbffffffULL, 0xffffffffffff7fffULL, 0xfdffffffffffffefULL, 0xffffbfffffffffffULL,
0xfffffffffffbffffULL, 0xefffffffffffff7fULL, 0xfffdffffffffffffULL, 0xffffffbfffffffffULL, 0xfffffffff7ffffffULL, 0xfffffffffffeffffULL, 0xfbffffffffffffdfULL, 0xffff7fffffffffffULL,
0xfffffffffff7ffffULL, 0xdffffffffffffeffULL, 0xfffbffffffffffffULL, 0xffffff7fffffffffULL, 0xffffffffefffffffULL, 0xfffffffffffdffffULL, 0xf7ffffffffffffbfULL, 0xfffeffffffffffffULL,
0xffffffffffefffffULL, 0xbffffffffffffdffULL, 0xfff7ffffffffffffULL, 0xfffffeffffffffffULL, 0xffffffffdfffffffULL, 0xfffffffffffbffffULL, 0xefffffffffffff7fULL, 0xfffdffffffffffffULL,
0xffffffffffdfffffULL, 0x7ffffffffffffbffULL, 0xffefffffffffffffULL, 0xfffffdffffffffffULL, 0xffffffffbfffffffULL, 0xfffffffffff7ffffULL, 0xdffffffffffffeffULL, 0xfffbffffffffffffULL,
0xffffffffffbfffffULL, 0xfffffffffffff7ffULL, 0xffdffffffffffffeULL, 0xfffffbffffffffffULL, 0xffffffff7fffffffULL, 0xffffffffffefffffULL, 0xbffffffffffffdffULL, 0xfff7ffffffffffffULL,
0xffffffffff7fffffULL, 0xffffffffffffefffULL, 0xffbffffffffffffdULL, 0xfffff7ffffffffffULL, 0xfffffffeffffffffULL, 0xffffffffffdfffffULL, 0x7ffffffffffffbffULL, 0xffefffffffffffffULL,
0xfffffffffeffffffULL, 0xffffffffffffdfffULL, 0xff7ffffffffffffbULL, 0xffffefffffffffffULL, 0xfffffffdffffffffULL, 0xffffffffffbfffffULL, 0xfffffffffffff7ffULL, 0xffdffffffffffffeULL,
0xfffffffffdffffffULL, 0xffffffffffffbfffULL, 0xfefffffffffffff7ULL, 0xffffdfffffffffffULL, 0xfffffffbffffffffULL, 0xffffffffff7fffffULL, 0xffffffffffffefffULL, 0xffbffffffffffffdULL,
0xfffffffffbffffffULL, 0xffffffffffff7fffULL, 0xfdffffffffffffefULL, 0xffffbfffffffffffULL, 0xfffffff7ffffffffULL, 0xfffffffffeffffffULL, 0xffffffffffffdfffULL, 0xff7ffffffffffffbULL,
0xfffffffff7ffffffULL, 0xfffffffffffeffffULL, 0xfbffffffffffffdfULL, 0xffff7fffffffffffULL, 0xffffffefffffffffULL, 0xfffffffffdffffffULL, 0xffffffffffffbfffULL, 0xfefffffffffffff7ULL,
0xffffffffefffffffULL, 0xfffffffffffdffffULL, 0xf7ffffffffffffbfULL, 0xfffeffffffffffffULL, 0xffffffdfffffffffULL, 0xfffffffffbffffffULL, 0xffffffffffff7fffULL, 0xfdffffffffffffefULL,
0xffffffffdfffffffULL, 0xfffffffffffbffffULL, 0xefffffffffffff7fULL, 0xfffdffffffffffffULL, 0xffffffbfffffffffULL, 0xfffffffff7ffffffULL, 0xfffffffffffeffffULL, 0xfbffffffffffffdfULL,
0xffffffffbfffffffULL, 0xfffffffffff7ffffULL, 0xdffffffffffffeffULL, 0xfffbffffffffffffULL, 0xffffff7fffffffffULL, 0xffffffffefffffffULL, 0xfffffffffffdffffULL, 0xf7ffffffffffffbfULL,
0xffffffff7fffffffULL, 0xffffffffffefffffULL, 0xbffffffffffffdffULL, 0xfff7ffffffffffffULL, 0xfffffeffffffffffULL, 0xffffffffdfffffffULL, 0xfffffffffffbffffULL, 0xefffffffffffff7fULL,
0xfffffffeffffffffULL, 0xffffffffffdfffffULL, 0x7ffffffffffffbffULL, 0xffefffffffffffffULL, 0xfffffdffffffffffULL, 0xffffffffbfffffffULL, 0xfffffffffff7ffffULL, 0xdffffffffffffeffULL,
0xfffffffdffffffffULL, 0xffffffffffbfffffULL, 0xfffffffffffff7ffULL, 0xffdffffffffffffeULL, 0xfffffbffffffffffULL, 0xffffffff7fffffffULL, 0xffffffffffefffffULL, 0xbffffffffffffdffULL,
0xfffffffbffffffffULL, 0xffffffffff7fffffULL, 0xffffffffffffefffULL, 0xffbffffffffffffdULL, 0xfffff7ffffffffffULL, 0xfffffffeffffffffULL, 0xffffffffffdfffffULL, 0x7ffffffffffffbffULL,
0xfffffff7ffffffffULL, 0xfffffffffeffffffULL, 0xffffffffffffdfffULL, 0xff7ffffffffffffbULL, 0xffffefffffffffffULL, 0xfffffffdffffffffULL, 0xffffffffffbfffffULL, 0xfffffffffffff7ffULL,
0xffffffefffffffffULL, 0xfffffffffdffffffULL, 0xffffffffffffbfffULL, 0xfefffffffffffff7ULL, 0xffffdfffffffffffULL, 0xfffffffbffffffffULL, 0xffffffffff7fffffULL, 0xffffffffffffefffULL,
0xffffffdfffffffffULL, 0xfffffffffbffffffULL, 0xffffffffffff7fffULL, 0xfdffffffffffffefULL, 0xffffbfffffffffffULL, 0xfffffff7ffffffffULL, 0xfffffffffeffffffULL, 0xffffffffffffdfffULL,
0xffffffbfffffffffULL, 0xfffffffff7ffffffULL, 0xfffffffffffeffffULL, 0xfbffffffffffffdfULL, 0xffff7fffffffffffULL, 0xffffffefffffffffULL, 0xfffffffffdffffffULL, 0xffffffffffffbfffULL,
0xffffff7fffffffffULL, 0xffffffffefffffffULL, 0xfffffffffffdffffULL, 0xf7ffffffffffffbfULL, 0xfffeffffffffffffULL, 0xffffffdfffffffffULL, 0xfffffffffbffffffULL, 0xffffffffffff7fffULL,
0xfffffeffffffffffULL, 0xffffffffdfffffffULL, 0xfffffffffffbffffULL, 0xefffffffffffff7fULL, 0xfffdffffffffffffULL, 0xffffffbfffffffffULL, 0xfffffffff7ffffffULL, 0xfffffffffffeffffULL,
0xfffffdffffffffffULL, 0xffffffffbfffffffULL, 0xfffffffffff7ffffULL, 0xdffffffffffffeffULL, 0xfffbffffffffffffULL, 0xffffff7fffffffffULL, 0xffffffffefffffffULL, 0xfffffffffffdffffULL,
0xfffffbffffffffffULL, 0xffffffff7fffffffULL, 0xffffffffffefffffULL, 0xbffffffffffffdffULL, 0xfff7ffffffffffffULL, 0xfffffeffffffffffULL, 0xffffffffdfffffffULL, 0xfffffffffffbffffULL,
0xfffff7ffffffffffULL, 0xfffffffeffffffffULL, 0xffffffffffdfffffULL, 0x7ffffffffffffbffULL, 0xffefffffffffffffULL, 0xfffffdffffffffffULL, 0xffffffffbfffffffULL, 0xfffffffffff7ffffULL,
0xffffefffffffffffULL, 0xfffffffdffffffffULL, 0xffffffffffbfffffULL, 0xfffffffffffff7ffULL, 0xffdffffffffffffeULL, 0xfffffbffffffffffULL, 0xffffffff7fffffffULL, 0xffffffffffefffffULL,
0xffffdfffffffffffULL, 0xfffffffbffffffffULL, 0xffffffffff7fffffULL, 0xffffffffffffefffULL, 0xffbffffffffffffdULL, 0xfffff7ffffffffffULL, 0xfffffffeffffffffULL, 0xffffffffffdfffffULL,
0xffffbfffffffffffULL, 0xfffffff7ffffffffULL, 0xfffffffffeffffffULL, 0xffffffffffffdfffULL, 0xff7ffffffffffffbULL, 0xffffefffffffffffULL, 0xfffffffdffffffffULL, 0xffffffffffbfffffULL,
0xffff7fffffffffffULL, 0xffffffefffffffffULL, 0xfffffffffdffffffULL, 0xffffffffffffbfffULL, 0xfefffffffffffff7ULL, 0xffffdfffffffffffULL, 0xfffffffbffffffffULL, 0xffffffffff7fffffULL,
0xfffeffffffffffffULL, 0xffffffdfffffffffULL, 0xfffffffffbffffffULL, 0xffffffffffff7fffULL, 0xfdffffffffffffefULL, 0xffffbfffffffffffULL, 0xfffffff7ffffffffULL, 0xfffffffffeffffffULL,
0xfffdffffffffffffULL, 0xffffffbfffffffffULL, 0xfffffffff7ffffffULL, 0xfffffffffffeffffULL, 0xfbffffffffffffdfULL, 0xffff7fffffffffffULL, 0xffffffefffffffffULL, 0xfffffffffdffffffULL,
0xfffbffffffffffffULL, 0xffffff7fffffffffULL, 0xffffffffefffffffULL, 0xfffffffffffdffffULL, 0xf7ffffffffffffbfULL, 0xfffeffffffffffffULL, 0xffffffdfffffffffULL, 0xfffffffffbffffffULL,
0xfff7ffffffffffffULL, 0xfffffeffffffffffULL, 0xffffffffdfffffffULL, 0xfffffffffffbffffULL, 0xefffffffffffff7fULL, 0xfffdffffffffffffULL, 0xffffffbfffffffffULL, 0xfffffffff7ffffffULL,
0xffefffffffffffffULL, 0xfffffdffffffffffULL, 0xffffffffbfffffffULL, 0xfffffffffff7ffffULL, 0xdffffffffffffeffULL, 0xfffbffffffffffffULL, 0xffffff7fffffffffULL, 0xffffffffefffffffULL};
*/
__inline uint32_t modinv_1(uint32_t a, uint32_t p) {
/* thanks to the folks at www.mersenneforum.org */
uint32_t ps1, ps2, parity, dividend, divisor, rem, q, t;
q = 1;
rem = a;
dividend = p;
divisor = a;
ps1 = 1;
ps2 = 0;
parity = 0;
while (divisor > 1) {
rem = dividend - divisor;
t = rem - divisor;
if (rem >= divisor) {
q += ps1; rem = t; t -= divisor;
if (rem >= divisor) {
q += ps1; rem = t; t -= divisor;
if (rem >= divisor) {
q += ps1; rem = t; t -= divisor;
if (rem >= divisor) {
q += ps1; rem = t; t -= divisor;
if (rem >= divisor) {
q += ps1; rem = t; t -= divisor;
if (rem >= divisor) {
q += ps1; rem = t; t -= divisor;
if (rem >= divisor) {
q += ps1; rem = t; t -= divisor;
if (rem >= divisor) {
q += ps1; rem = t;
if (rem >= divisor) {
q = dividend / divisor;
rem = dividend % divisor;
q *= ps1;
}
}
}
}
}
}
}
}
}
q += ps2;
parity = ~parity;
dividend = divisor;
divisor = rem;
ps2 = ps1;
ps1 = q;
}
if (parity == 0)
return ps1;
else
return p - ps1;
}
void MultiSegSieve2(uint32_t *count, uint32_t *primes_dev, uint32_t *pinv_dev,
int start_block, int num_blocks, int maxp, uint64_t maxID)
{
uint32_t bid;
#pragma omp parallel for
for (bid = startprime; bid < maxp; bid++)
{
uint32_t p = primes_dev[bid];
pinv_dev[bid] = p - modinv_1(30, p);
}
#pragma omp parallel for
for (bid = start_block; bid < start_block + num_blocks; bid++)
{
uint32_t sieve[BSIZE];
//uint32_t *sieve;
uint32_t pid;
int i, j, k, lnum;
uint32_t p = 0;
uint32_t residues[NLINES] = { 1, 7, 11, 13, 17, 19, 23, 29};
uint64_t block_start = (uint64_t)bid * BSIZE * 32 * 30;
count[bid] = 0;
//sieve = (uint32_t *)xmalloc_align(BSIZE * sizeof(uint32_t));
// for each line in the sieve there are BSIZE * 32 bits.
// In total, the lines of the block represent BSIZE * 32 * 30 integers
for (lnum = 0; lnum < NLINES; lnum++)
{
uint64_t line_start = block_start + (uint64_t)residues[lnum];
uint64_t tmp;
int mask_step, mask_num;
uint32_t offset;
uint64_t *sieve64 = (uint64_t *)sieve;
__m512i zero = _mm512_set1_epi32(0);
__m512i one = _mm512_set1_epi32(1);
__m512i bsz = _mm512_set1_epi32(BSIZE * 32);
__m512i v31 = _mm512_set1_epi32(31);
__m512i vls = _mm512_set1_epi64(line_start);
__m512i vfull = _mm512_set1_epi32(0xffffffff);
__m512i vmaskfull[17];
__m512i vmask;
///////////////////////////////////////////////////////////////////////////
// presieve
pid = 3;
p = primes_dev[pid];
// compute the offset into this block using the precomputed inverse modulo 30
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0; k < p; k++)
{
vmaskfull[k] = _mm512_load_epi32(&_7_MASKS_512[k*8]);
}
for (k = 0, mask_step = _512_MOD_P[1], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
_mm512_store_epi64(&sieve64[k * 8], vmaskfull[mask_num]);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 7 + mask_num;
}
pid = 4;
p = primes_dev[pid];
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0; k < p; k++)
{
vmaskfull[k] = _mm512_load_epi32(&_11_MASKS_512[k * 8]);
}
for (k = 0, mask_step = _512_MOD_P[2], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
__m512i vsieve = _mm512_load_epi32(&sieve64[k * 8]);
vmask = _mm512_and_epi32(vmaskfull[mask_num], vsieve);
_mm512_store_epi64(&sieve64[k * 8], vmask);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 11 + mask_num;
}
pid = 5;
p = primes_dev[pid];
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0; k < p; k++)
{
vmaskfull[k] = _mm512_load_epi32(&_13_MASKS_512[k * 8]);
}
for (k = 0, mask_step = _512_MOD_P[3], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
__m512i vsieve = _mm512_load_epi32(&sieve64[k * 8]);
vmask = _mm512_and_epi32(vmaskfull[mask_num], vsieve);
_mm512_store_epi64(&sieve64[k * 8], vmask);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 13 + mask_num;
}
pid = 6;
p = primes_dev[pid];
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0; k < p; k++)
{
vmaskfull[k] = _mm512_load_epi32(&_17_MASKS_512[k * 8]);
}
for (k = 0, mask_step = _512_MOD_P[4], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
__m512i vsieve = _mm512_load_epi32(&sieve64[k * 8]);
vmask = _mm512_and_epi32(vmaskfull[mask_num], vsieve);
_mm512_store_epi64(&sieve64[k * 8], vmask);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 17 + mask_num;
}
pid = 7;
p = primes_dev[pid];
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0, mask_step = _512_MOD_P[5], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
__m512i vsieve = _mm512_load_epi32(&sieve64[k * 8]);
vmask = _mm512_load_epi32(&_19_MASKS_512[mask_num * 8]);
vmask = _mm512_and_epi32(vmask, vsieve);
_mm512_store_epi64(&sieve64[k * 8], vmask);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 19 + mask_num;
}
pid = 8;
p = primes_dev[pid];
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0, mask_step = _512_MOD_P[6], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
__m512i vsieve = _mm512_load_epi32(&sieve64[k * 8]);
vmask = _mm512_load_epi32(&_23_MASKS_512[mask_num * 8]);
vmask = _mm512_and_epi32(vmask, vsieve);
_mm512_store_epi64(&sieve64[k * 8], vmask);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 23 + mask_num;
}
pid = 9;
p = primes_dev[pid];
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0, mask_step = _512_MOD_P[7], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
__m512i vsieve = _mm512_load_epi32(&sieve64[k * 8]);
vmask = _mm512_load_epi32(&_29_MASKS_512[mask_num * 8]);
vmask = _mm512_and_epi32(vmask, vsieve);
_mm512_store_epi64(&sieve64[k * 8], vmask);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 29 + mask_num;
}
pid = 10;
p = primes_dev[pid];
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0, mask_step = _512_MOD_P[8], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
__m512i vsieve = _mm512_load_epi32(&sieve64[k * 8]);
vmask = _mm512_load_epi32(&_31_MASKS_512[mask_num * 8]);
vmask = _mm512_and_epi32(vmask, vsieve);
_mm512_store_epi64(&sieve64[k * 8], vmask);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 31 + mask_num;
}
pid = 11;
p = primes_dev[pid];
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0, mask_step = _512_MOD_P[9], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
__m512i vsieve = _mm512_load_epi32(&sieve64[k * 8]);
vmask = _mm512_load_epi32(&_37_MASKS_512[mask_num * 8]);
vmask = _mm512_and_epi32(vmask, vsieve);
_mm512_store_epi64(&sieve64[k * 8], vmask);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 37 + mask_num;
}
pid = 12;
p = primes_dev[pid];
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0, mask_step = _512_MOD_P[10], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
__m512i vsieve = _mm512_load_epi32(&sieve64[k * 8]);
vmask = _mm512_load_epi32(&_41_MASKS_512[mask_num * 8]);
vmask = _mm512_and_epi32(vmask, vsieve);
_mm512_store_epi64(&sieve64[k * 8], vmask);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 41 + mask_num;
}
pid = 13;
p = primes_dev[pid];
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0, mask_step = _512_MOD_P[11], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
__m512i vsieve = _mm512_load_epi32(&sieve64[k * 8]);
vmask = _mm512_load_epi32(&_43_MASKS_512[mask_num * 8]);
vmask = _mm512_and_epi32(vmask, vsieve);
_mm512_store_epi64(&sieve64[k * 8], vmask);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 43 + mask_num;
}
pid = 14;
p = primes_dev[pid];
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0, mask_step = _512_MOD_P[12], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
__m512i vsieve = _mm512_load_epi32(&sieve64[k * 8]);
vmask = _mm512_load_epi32(&_47_MASKS_512[mask_num * 8]);
vmask = _mm512_and_epi32(vmask, vsieve);
_mm512_store_epi64(&sieve64[k * 8], vmask);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 47 + mask_num;
}
pid = 15;
p = primes_dev[pid];
tmp = (uint64_t)pinv_dev[pid] * (line_start % (uint64_t)p);
offset = (uint32_t)(tmp % (uint64_t)p);
for (k = 0, mask_step = _512_MOD_P[13], mask_num = offset;
k < (BSIZE * 32 >> 9); k++)
{
__m512i vsieve = _mm512_load_epi32(&sieve64[k * 8]);
vmask = _mm512_load_epi32(&_53_MASKS_512[mask_num * 8]);
vmask = _mm512_and_epi32(vmask, vsieve);
_mm512_store_epi64(&sieve64[k * 8], vmask);
mask_num -= mask_step;
if (mask_num < 0) mask_num = 53 + mask_num;
}
///////////////////////////////////////////////////////////////////////////
// regular sieve
for (pid = 16; pid < (maxp - 16); pid += 16)
{
__m512i vprime;
__m512i vpinv;
__m512i a, b, c, d, s, ep, op;
__mmask16 wmask;
__declspec(align(64)) uint32_t t[16];
__declspec(align(64)) uint32_t t2[16];
// load primes and inverses
vprime = _mm512_load_epi32(primes_dev + pid);
vpinv = _mm512_load_epi32(pinv_dev + pid);
// take line_start mod p so it is 32-bit
// (there does not appear to be a 64-bit vector integer multiply operation.)
ep = _mm512_mask_swizzle_epi32(zero, 0x5555, vprime, _MM_SWIZ_REG_NONE);
op = _mm512_mask_swizzle_epi32(zero, 0x5555, vprime, _MM_SWIZ_REG_CDAB);
b = _mm512_rem_epu64(vls, ep);
c = _mm512_rem_epu64(vls, op);
// re-combine two 64-bit remainders into one 32-bit vector again
c = _mm512_swizzle_epi32(c, _MM_SWIZ_REG_CDAB);
a = _mm512_or_epi32(c, b);
// multiply with pinv
b = _mm512_mulhi_epu32(a, vpinv);
a = _mm512_mullo_epi32(a, vpinv);
// re-arrange the two 32-bit vectors into 2 64-bit vector products.
// swizzle-swap the hi products to get the even 64-bit products
c = _mm512_mask_swizzle_epi32(a, 0xaaaa, b, _MM_SWIZ_REG_CDAB);
// swizzle-swap the lo products to get the odd 64-bit products
d = _mm512_mask_swizzle_epi32(b, 0x5555, a, _MM_SWIZ_REG_CDAB);
// offset = product mod p
b = _mm512_rem_epu64(d, op);
a = _mm512_rem_epu64(c, ep);
// re-combine two 64-bit modular products into one 32-bit vector again
b = _mm512_swizzle_epi32(b, _MM_SWIZ_REG_CDAB);
a = _mm512_or_epi32(b, a);
// hybrid collision-free sieve that is correct
// (unlike gather/scatter) yet faster than a fully non-vector sieve.
wmask = _mm512_cmp_epi32_mask(a, bsz, _MM_CMPINT_LT);
while (wmask > 0)
{
c = _mm512_srli_epi32(a, 5); // word location
b = _mm512_and_epi32(a, v31);
b = _mm512_sllv_epi32(one, b); // bit location
b = _mm512_andnot_epi32(b, vfull); // sieve &= not(bit location)
_mm512_store_epi32(t, c);
_mm512_store_epi32(t2, b);
// this is where gather/scatter fails... because more
// than one offset may be at the same t[k] and only
// the last t2 written will survive when using scatter.
// we'd have to change to a write only sieve (byte-wide
// writes of 0) to use gather/scatter. unsure if the
// resulting expansion of the sieve area will be a win
// with that approach.
if (wmask == 0xffff)
{
sieve[t[0]] &= t2[0];
sieve[t[1]] &= t2[1];
sieve[t[2]] &= t2[2];
sieve[t[3]] &= t2[3];
sieve[t[4]] &= t2[4];
sieve[t[5]] &= t2[5];
sieve[t[6]] &= t2[6];
sieve[t[7]] &= t2[7];
sieve[t[8]] &= t2[8];
sieve[t[9]] &= t2[9];
sieve[t[10]] &= t2[10];
sieve[t[11]] &= t2[11];
sieve[t[12]] &= t2[12];
sieve[t[13]] &= t2[13];
sieve[t[14]] &= t2[14];
sieve[t[15]] &= t2[15];
}
else
{
#pragma unroll(16)
for (k = 0; k < 16; k++)
{
if (wmask & (1 << k))
{
sieve[t[k]] &= t2[k];
}
}
}
a = _mm512_add_epi32(a, vprime);
wmask = _mm512_cmp_epi32_mask(a, bsz, _MM_CMPINT_LT);
}
}
// ending peel loop
for (; pid < maxp; pid++)
{
p = primes_dev[pid];
// compute the offset into this block using the precomputed inverse modulo 30
tmp = (uint64_t)pinv_dev[pid] * line_start;
offset = (uint32_t)(tmp % (uint64_t)p);
// then sieve the block
for (i = offset; i < BSIZE * 32; i += p)
{
sieve[i >> 5] &= (~(1 << (i & 31)));
}
}
///////////////////////////////////////////////////////////////////////////
// clear last bits
if (bid == (num_blocks + start_block - 1))
{
// zero locations outside the requested range.
// first zero whole 32-bit words.
for (j = BSIZE - 1; j >= 0; j--)
{
if ((block_start + j * 32 * 30 + residues[lnum]) > maxID)
sieve[j] = 0;
else
break;
}
// then any last bits
for (k = 31; k >= 0; k--)
{
if ((block_start + (j * 32 + k) * 30 + residues[lnum]) > maxID)
sieve[j] &= (~(1 << (k & 31)));
else
break;
}
}
///////////////////////////////////////////////////////////////////////////
// count primes found in this block
k = 0;
#pragma ivdep
for (j = 0; j < BSIZE; j++)
{
k += _mm_countbits_32(sieve[j]);
}
count[bid] += k;
}
//align_free(sieve);
}
return;
}
///////////////////////////////////////////////////////////////////////////
// public interface functions
///////////////////////////////////////////////////////////////////////////
// call once to create the bitmap
int gen_primes(uint64_t N, int threads)
{
uint32_t Nsmall;
int numblocks;
int primes_per_thread;
uint64_t array_size;
uint32_t* primes;
uint32_t* pinv;
uint32_t* device_primes;
uint32_t* device_pinv;
uint32_t* block_counts;
uint32_t np;
unsigned int thandle;
uint32_t* block_counts_on_host;
clock_t start, stop;
int i;
// timing variables
struct timeval stopt; // stop time of this job
struct timeval startt; // start time of this job
double t_time;
Nsmall = (uint32_t)sqrt((double)N);
printf("generating primes up to %lu using primes up to %u\n", N, Nsmall);
if (N > 1000000000000)
{
printf("input range too large, limit is 10e11");
exit(0);
}
// find seed primes
start = clock();
primes = tiny_soe(Nsmall, &np);
printf("%d small primes (< %d) found\n", np, Nsmall);
// allocate space for the inverse of p mod the wheel size,
// which is used to speed up a time critical operation.
pinv = (uint32_t *)xmalloc_align(np*sizeof(uint32_t));
stop = clock();
printf("init time was %1.2f sec\n", (double)(stop - start) / (double)CLOCKS_PER_SEC);
gettimeofday(&startt, NULL);
omp_set_num_threads(threads);
//if (N < 10000000)
//{
// BSIZE = 256;
//}
//else if (N < 100000000)
//{
// BSIZE = 512;
//}
//else if (N < 1000000000)
//{
// BSIZE = 2048;
//}
//else if (N < 10000000000)
//{
// BSIZE = 4096;
//}
//else
//{
// BSIZE = 8192;
//}
numblocks = (N / 30 / BSIZE / 32 + 1);
// init result array of block counts
block_counts = (uint32_t *)xmalloc_align(numblocks*sizeof(uint32_t));
printf("using %d blocks with %d bits per block and 8 residues\n",
numblocks, BSIZE * 32);
printf("sieved blocks have %d extra flags\n",
numblocks * BSIZE * 32 * 30 - N);
MultiSegSieve2(block_counts, primes, pinv, 0, numblocks, np, N);
gettimeofday(&stopt, NULL);
t_time = my_difftime(&startt, &stopt);
printf("%f seconds for big sieve\n", t_time);
uint32_t nbig = startprime - 1; // start here because we aren't sieving 3, and the sieve for
// primes less than 32 is special and crosses off those primes.
for (i = 0; i<numblocks; i++)
{
nbig += block_counts[i];
}
printf("\n%u big primes (< %lu) found\n", nbig + np - startprime, N);
align_free(block_counts);
align_free(primes);
align_free(pinv);
return 0;
}
// call as needed to extract a chunk of primes from the bitmap
uint32_t extract_prime_range(uint64_t *primes, uint64_t start)
{
// the bitmap is laid out like this:
//
// residue 0 : block 0 block 1 block 2... block numblks-1
// residue 1 : block 0 block 1 block 2... block numblks-1
// residue 2 : block 0 block 1 block 2... block numblks-1
// ...
// residue Nres - 1: block 0 block 1 block 2... block numblks-1
//
// where each block consists of BSIZE 32-bit words (currently 262144 bits).
// The primes are contiguous along columns e.g., residue 0, bit 0 then
// residue 1, bit 0 ... residue N-1, bit 0, then residue 0, bit 1, etc.
// we first compute which column of blocks contains the requested start.
// we then compute all primes in all bits of all residues in that column.
// currently this is 2097152 bits spanning 7864320 integers, of which a
// fraction will be primes (depending on 'start'). worst case this is
// about 500k primes per column of blocks ('start' == 0).
// finally we order these primes into the output list starting at the
// the requested 'start' prime (or next prime greater than 'start' if
// 'start' is not prime).
// the two difficult tasks are computing primes and ordering them. To
// compute them, we transform each '1' bit in each 32-bit word into
// a 64-bit output. This can be done sequentially but we'd like to do
// it in SIMD if possible.
return 0;
}
|
resample.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% RRRR EEEEE SSSSS AAA M M PPPP L EEEEE %
% R R E SS A A MM MM P P L E %
% RRRR EEE SSS AAAAA M M M PPPP L EEE %
% R R E SS A A M M P L E %
% R R EEEEE SSSSS A A M M P LLLLL EEEEE %
% %
% %
% MagickCore Pixel Resampling Methods %
% %
% Software Design %
% Cristy %
% Anthony Thyssen %
% August 2007 %
% %
% %
% Copyright 1999-2014 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/color-private.h"
#include "magick/cache.h"
#include "magick/draw.h"
#include "magick/exception-private.h"
#include "magick/gem.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/pixel.h"
#include "magick/pixel-private.h"
#include "magick/quantum.h"
#include "magick/random_.h"
#include "magick/resample.h"
#include "magick/resize.h"
#include "magick/resize-private.h"
#include "magick/resource_.h"
#include "magick/transform.h"
#include "magick/signature-private.h"
#include "magick/token.h"
#include "magick/utility.h"
#include "magick/option.h"
/*
EWA Resampling Options
*/
/* select ONE resampling method */
#define EWA 1 /* Normal EWA handling - raw or clamped */
/* if 0 then use "High Quality EWA" */
#define EWA_CLAMP 1 /* EWA Clamping from Nicolas Robidoux */
#define FILTER_LUT 1 /* Use a LUT rather then direct filter calls */
/* output debugging information */
#define DEBUG_ELLIPSE 0 /* output ellipse info for debug */
#define DEBUG_HIT_MISS 0 /* output hit/miss pixels (as gnuplot commands) */
#define DEBUG_NO_PIXEL_HIT 0 /* Make pixels that fail to hit anything - RED */
#if ! FILTER_DIRECT
#define WLUT_WIDTH 1024 /* size of the filter cache */
#endif
/*
Typedef declarations.
*/
struct _ResampleFilter
{
CacheView
*view;
Image
*image;
ExceptionInfo
*exception;
MagickBooleanType
debug;
/* Information about image being resampled */
ssize_t
image_area;
InterpolatePixelMethod
interpolate;
VirtualPixelMethod
virtual_pixel;
FilterTypes
filter;
/* processing settings needed */
MagickBooleanType
limit_reached,
do_interpolate,
average_defined;
MagickPixelPacket
average_pixel;
/* current ellipitical area being resampled around center point */
double
A, B, C,
Vlimit, Ulimit, Uwidth, slope;
#if FILTER_LUT
/* LUT of weights for filtered average in elliptical area */
double
filter_lut[WLUT_WIDTH];
#else
/* Use a Direct call to the filter functions */
ResizeFilter
*filter_def;
double
F;
#endif
/* the practical working support of the filter */
double
support;
size_t
signature;
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e R e s a m p l e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireResampleFilter() initializes the information resample needs do to a
% scaled lookup of a color from an image, using area sampling.
%
% The algorithm is based on a Elliptical Weighted Average, where the pixels
% found in a large elliptical area is averaged together according to a
% weighting (filter) function. For more details see "Fundamentals of Texture
% Mapping and Image Warping" a master's thesis by Paul.S.Heckbert, June 17,
% 1989. Available for free from, http://www.cs.cmu.edu/~ph/
%
% As EWA resampling (or any sort of resampling) can require a lot of
% calculations to produce a distorted scaling of the source image for each
% output pixel, the ResampleFilter structure generated holds that information
% between individual image resampling.
%
% This function will make the appropriate AcquireVirtualCacheView() calls
% to view the image, calling functions do not need to open a cache view.
%
% Usage Example...
% resample_filter=AcquireResampleFilter(image,exception);
% SetResampleFilter(resample_filter, GaussianFilter, 1.0);
% for (y=0; y < (ssize_t) image->rows; y++) {
% for (x=0; x < (ssize_t) image->columns; x++) {
% u= ....; v= ....;
% ScaleResampleFilter(resample_filter, ... scaling vectors ...);
% (void) ResamplePixelColor(resample_filter,u,v,&pixel);
% ... assign resampled pixel value ...
% }
% }
% DestroyResampleFilter(resample_filter);
%
% The format of the AcquireResampleFilter method is:
%
% ResampleFilter *AcquireResampleFilter(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ResampleFilter *AcquireResampleFilter(const Image *image,
ExceptionInfo *exception)
{
register ResampleFilter
*resample_filter;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
resample_filter=(ResampleFilter *) AcquireMagickMemory(
sizeof(*resample_filter));
if (resample_filter == (ResampleFilter *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(resample_filter,0,sizeof(*resample_filter));
resample_filter->exception=exception;
resample_filter->image=ReferenceImage((Image *) image);
resample_filter->view=AcquireVirtualCacheView(resample_filter->image,exception);
resample_filter->debug=IsEventLogging();
resample_filter->signature=MagickSignature;
resample_filter->image_area=(ssize_t) (image->columns*image->rows);
resample_filter->average_defined = MagickFalse;
/* initialise the resampling filter settings */
SetResampleFilter(resample_filter, image->filter, image->blur);
(void) SetResampleFilterInterpolateMethod(resample_filter,
image->interpolate);
(void) SetResampleFilterVirtualPixelMethod(resample_filter,
GetImageVirtualPixelMethod(image));
return(resample_filter);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y R e s a m p l e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyResampleFilter() finalizes and cleans up the resampling
% resample_filter as returned by AcquireResampleFilter(), freeing any memory
% or other information as needed.
%
% The format of the DestroyResampleFilter method is:
%
% ResampleFilter *DestroyResampleFilter(ResampleFilter *resample_filter)
%
% A description of each parameter follows:
%
% o resample_filter: resampling information structure
%
*/
MagickExport ResampleFilter *DestroyResampleFilter(
ResampleFilter *resample_filter)
{
assert(resample_filter != (ResampleFilter *) NULL);
assert(resample_filter->signature == MagickSignature);
assert(resample_filter->image != (Image *) NULL);
if (resample_filter->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
resample_filter->image->filename);
resample_filter->view=DestroyCacheView(resample_filter->view);
resample_filter->image=DestroyImage(resample_filter->image);
#if ! FILTER_LUT
resample_filter->filter_def=DestroyResizeFilter(resample_filter->filter_def);
#endif
resample_filter->signature=(~MagickSignature);
resample_filter=(ResampleFilter *) RelinquishMagickMemory(resample_filter);
return(resample_filter);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s a m p l e P i x e l C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResamplePixelColor() samples the pixel values surrounding the location
% given using an elliptical weighted average, at the scale previously
% calculated, and in the most efficent manner possible for the
% VirtualPixelMethod setting.
%
% The format of the ResamplePixelColor method is:
%
% MagickBooleanType ResamplePixelColor(ResampleFilter *resample_filter,
% const double u0,const double v0,MagickPixelPacket *pixel)
%
% A description of each parameter follows:
%
% o resample_filter: the resample filter.
%
% o u0,v0: A double representing the center of the area to resample,
% The distortion transformed transformed x,y coordinate.
%
% o pixel: the resampled pixel is returned here.
%
*/
MagickExport MagickBooleanType ResamplePixelColor(
ResampleFilter *resample_filter,const double u0,const double v0,
MagickPixelPacket *pixel)
{
MagickBooleanType
status;
ssize_t u,v, v1, v2, uw, hit;
double u1;
double U,V,Q,DQ,DDQ;
double divisor_c,divisor_m;
register double weight;
register const PixelPacket *pixels;
register const IndexPacket *indexes;
assert(resample_filter != (ResampleFilter *) NULL);
assert(resample_filter->signature == MagickSignature);
status=MagickTrue;
/* GetMagickPixelPacket(resample_filter->image,pixel); */
if ( resample_filter->do_interpolate ) {
status=InterpolateMagickPixelPacket(resample_filter->image,
resample_filter->view,resample_filter->interpolate,u0,v0,pixel,
resample_filter->exception);
return(status);
}
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "u0=%lf; v0=%lf;\n", u0, v0);
#endif
/*
Does resample area Miss the image Proper?
If and that area a simple solid color - then simply return that color!
This saves a lot of calculation when resampling outside the bounds of
the source image.
However it probably should be expanded to image bounds plus the filters
scaled support size.
*/
hit = 0;
switch ( resample_filter->virtual_pixel ) {
case BackgroundVirtualPixelMethod:
case ConstantVirtualPixelMethod:
case TransparentVirtualPixelMethod:
case BlackVirtualPixelMethod:
case GrayVirtualPixelMethod:
case WhiteVirtualPixelMethod:
case MaskVirtualPixelMethod:
if ( resample_filter->limit_reached
|| u0 + resample_filter->Ulimit < 0.0
|| u0 - resample_filter->Ulimit > (double) resample_filter->image->columns-1.0
|| v0 + resample_filter->Vlimit < 0.0
|| v0 - resample_filter->Vlimit > (double) resample_filter->image->rows-1.0
)
hit++;
break;
case UndefinedVirtualPixelMethod:
case EdgeVirtualPixelMethod:
if ( ( u0 + resample_filter->Ulimit < 0.0 && v0 + resample_filter->Vlimit < 0.0 )
|| ( u0 + resample_filter->Ulimit < 0.0
&& v0 - resample_filter->Vlimit > (double) resample_filter->image->rows-1.0 )
|| ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns-1.0
&& v0 + resample_filter->Vlimit < 0.0 )
|| ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns-1.0
&& v0 - resample_filter->Vlimit > (double) resample_filter->image->rows-1.0 )
)
hit++;
break;
case HorizontalTileVirtualPixelMethod:
if ( v0 + resample_filter->Vlimit < 0.0
|| v0 - resample_filter->Vlimit > (double) resample_filter->image->rows-1.0
)
hit++; /* outside the horizontally tiled images. */
break;
case VerticalTileVirtualPixelMethod:
if ( u0 + resample_filter->Ulimit < 0.0
|| u0 - resample_filter->Ulimit > (double) resample_filter->image->columns-1.0
)
hit++; /* outside the vertically tiled images. */
break;
case DitherVirtualPixelMethod:
if ( ( u0 + resample_filter->Ulimit < -32.0 && v0 + resample_filter->Vlimit < -32.0 )
|| ( u0 + resample_filter->Ulimit < -32.0
&& v0 - resample_filter->Vlimit > (double) resample_filter->image->rows+31.0 )
|| ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns+31.0
&& v0 + resample_filter->Vlimit < -32.0 )
|| ( u0 - resample_filter->Ulimit > (double) resample_filter->image->columns+31.0
&& v0 - resample_filter->Vlimit > (double) resample_filter->image->rows+31.0 )
)
hit++;
break;
case TileVirtualPixelMethod:
case MirrorVirtualPixelMethod:
case RandomVirtualPixelMethod:
case HorizontalTileEdgeVirtualPixelMethod:
case VerticalTileEdgeVirtualPixelMethod:
case CheckerTileVirtualPixelMethod:
/* resampling of area is always needed - no VP limits */
break;
}
if ( hit ) {
/* The area being resampled is simply a solid color
* just return a single lookup color.
*
* Should this return the users requested interpolated color?
*/
status=InterpolateMagickPixelPacket(resample_filter->image,
resample_filter->view,IntegerInterpolatePixel,u0,v0,pixel,
resample_filter->exception);
return(status);
}
/*
When Scaling limits reached, return an 'averaged' result.
*/
if ( resample_filter->limit_reached ) {
switch ( resample_filter->virtual_pixel ) {
/* This is always handled by the above, so no need.
case BackgroundVirtualPixelMethod:
case ConstantVirtualPixelMethod:
case TransparentVirtualPixelMethod:
case GrayVirtualPixelMethod,
case WhiteVirtualPixelMethod
case MaskVirtualPixelMethod:
*/
case UndefinedVirtualPixelMethod:
case EdgeVirtualPixelMethod:
case DitherVirtualPixelMethod:
case HorizontalTileEdgeVirtualPixelMethod:
case VerticalTileEdgeVirtualPixelMethod:
/* We need an average edge pixel, from the correct edge!
How should I calculate an average edge color?
Just returning an averaged neighbourhood,
works well in general, but falls down for TileEdge methods.
This needs to be done properly!!!!!!
*/
status=InterpolateMagickPixelPacket(resample_filter->image,
resample_filter->view,AverageInterpolatePixel,u0,v0,pixel,
resample_filter->exception);
break;
case HorizontalTileVirtualPixelMethod:
case VerticalTileVirtualPixelMethod:
/* just return the background pixel - Is there a better way? */
status=InterpolateMagickPixelPacket(resample_filter->image,
resample_filter->view,IntegerInterpolatePixel,-1.0,-1.0,pixel,
resample_filter->exception);
break;
case TileVirtualPixelMethod:
case MirrorVirtualPixelMethod:
case RandomVirtualPixelMethod:
case CheckerTileVirtualPixelMethod:
default:
/* generate a average color of the WHOLE image */
if ( resample_filter->average_defined == MagickFalse ) {
Image
*average_image;
CacheView
*average_view;
GetMagickPixelPacket(resample_filter->image,(MagickPixelPacket *)
&resample_filter->average_pixel);
resample_filter->average_defined=MagickTrue;
/* Try to get an averaged pixel color of whole image */
average_image=ResizeImage(resample_filter->image,1,1,BoxFilter,1.0,
resample_filter->exception);
if (average_image == (Image *) NULL)
{
*pixel=resample_filter->average_pixel; /* FAILED */
break;
}
average_view=AcquireVirtualCacheView(average_image,
&average_image->exception);
pixels=(PixelPacket *)GetCacheViewVirtualPixels(average_view,0,0,1,1,
resample_filter->exception);
if (pixels == (const PixelPacket *) NULL) {
average_view=DestroyCacheView(average_view);
average_image=DestroyImage(average_image);
*pixel=resample_filter->average_pixel; /* FAILED */
break;
}
indexes=(IndexPacket *) GetCacheViewAuthenticIndexQueue(average_view);
SetMagickPixelPacket(resample_filter->image,pixels,indexes,
&(resample_filter->average_pixel));
average_view=DestroyCacheView(average_view);
average_image=DestroyImage(average_image);
if ( resample_filter->virtual_pixel == CheckerTileVirtualPixelMethod )
{
/* CheckerTile is a alpha blend of the image's average pixel
color and the current background color */
/* image's average pixel color */
weight = QuantumScale*((MagickRealType)(QuantumRange-
resample_filter->average_pixel.opacity));
resample_filter->average_pixel.red *= weight;
resample_filter->average_pixel.green *= weight;
resample_filter->average_pixel.blue *= weight;
divisor_c = weight;
/* background color */
weight = QuantumScale*((MagickRealType)(QuantumRange-
resample_filter->image->background_color.opacity));
resample_filter->average_pixel.red +=
weight*resample_filter->image->background_color.red;
resample_filter->average_pixel.green +=
weight*resample_filter->image->background_color.green;
resample_filter->average_pixel.blue +=
weight*resample_filter->image->background_color.blue;
resample_filter->average_pixel.opacity +=
resample_filter->image->background_color.opacity;
divisor_c += weight;
/* alpha blend */
resample_filter->average_pixel.red /= divisor_c;
resample_filter->average_pixel.green /= divisor_c;
resample_filter->average_pixel.blue /= divisor_c;
resample_filter->average_pixel.opacity /= 2; /* 50% blend */
}
}
*pixel=resample_filter->average_pixel;
break;
}
return(status);
}
/*
Initialize weighted average data collection
*/
hit = 0;
divisor_c = 0.0;
divisor_m = 0.0;
pixel->red = pixel->green = pixel->blue = 0.0;
if (pixel->matte != MagickFalse) pixel->opacity = 0.0;
if (pixel->colorspace == CMYKColorspace) pixel->index = 0.0;
/*
Determine the parellelogram bounding box fitted to the ellipse
centered at u0,v0. This area is bounding by the lines...
*/
v1 = (ssize_t)ceil(v0 - resample_filter->Vlimit); /* range of scan lines */
v2 = (ssize_t)floor(v0 + resample_filter->Vlimit);
/* scan line start and width accross the parallelogram */
u1 = u0 + (v1-v0)*resample_filter->slope - resample_filter->Uwidth;
uw = (ssize_t)(2.0*resample_filter->Uwidth)+1;
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "v1=%ld; v2=%ld\n", (long)v1, (long)v2);
(void) FormatLocaleFile(stderr, "u1=%ld; uw=%ld\n", (long)u1, (long)uw);
#else
# define DEBUG_HIT_MISS 0 /* only valid if DEBUG_ELLIPSE is enabled */
#endif
/*
Do weighted resampling of all pixels, within the scaled ellipse,
bound by a Parellelogram fitted to the ellipse.
*/
DDQ = 2*resample_filter->A;
for( v=v1; v<=v2; v++ ) {
#if DEBUG_HIT_MISS
long uu = ceil(u1); /* actual pixel location (for debug only) */
(void) FormatLocaleFile(stderr, "# scan line from pixel %ld, %ld\n", (long)uu, (long)v);
#endif
u = (ssize_t)ceil(u1); /* first pixel in scanline */
u1 += resample_filter->slope; /* start of next scan line */
/* location of this first pixel, relative to u0,v0 */
U = (double)u-u0;
V = (double)v-v0;
/* Q = ellipse quotent ( if Q<F then pixel is inside ellipse) */
Q = (resample_filter->A*U + resample_filter->B*V)*U + resample_filter->C*V*V;
DQ = resample_filter->A*(2.0*U+1) + resample_filter->B*V;
/* get the scanline of pixels for this v */
pixels=GetCacheViewVirtualPixels(resample_filter->view,u,v,(size_t) uw,
1,resample_filter->exception);
if (pixels == (const PixelPacket *) NULL)
return(MagickFalse);
indexes=GetCacheViewVirtualIndexQueue(resample_filter->view);
/* count up the weighted pixel colors */
for( u=0; u<uw; u++ ) {
weight = 0;
#if FILTER_LUT
/* Note that the ellipse has been pre-scaled so F = WLUT_WIDTH */
if ( Q < (double)WLUT_WIDTH ) {
weight = resample_filter->filter_lut[(int)Q];
#else
/* Note that the ellipse has been pre-scaled so F = support^2 */
if ( Q < (double)resample_filter->F ) {
weight = GetResizeFilterWeight(resample_filter->filter_def,
sqrt(Q)); /* a SquareRoot! Arrggghhhhh... */
#endif
pixel->opacity += weight*pixels->opacity;
divisor_m += weight;
if (pixel->matte != MagickFalse)
weight *= QuantumScale*((MagickRealType)(QuantumRange-pixels->opacity));
pixel->red += weight*pixels->red;
pixel->green += weight*pixels->green;
pixel->blue += weight*pixels->blue;
if (pixel->colorspace == CMYKColorspace)
pixel->index += weight*(*indexes);
divisor_c += weight;
hit++;
#if DEBUG_HIT_MISS
/* mark the pixel according to hit/miss of the ellipse */
(void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 3\n",
(long)uu-.1,(double)v-.1,(long)uu+.1,(long)v+.1);
(void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 3\n",
(long)uu+.1,(double)v-.1,(long)uu-.1,(long)v+.1);
} else {
(void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 1\n",
(long)uu-.1,(double)v-.1,(long)uu+.1,(long)v+.1);
(void) FormatLocaleFile(stderr, "set arrow from %lf,%lf to %lf,%lf nohead ls 1\n",
(long)uu+.1,(double)v-.1,(long)uu-.1,(long)v+.1);
}
uu++;
#else
}
#endif
pixels++;
indexes++;
Q += DQ;
DQ += DDQ;
}
}
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "Hit=%ld; Total=%ld;\n", (long)hit, (long)uw*(v2-v1) );
#endif
/*
Result sanity check -- this should NOT happen
*/
if ( hit == 0 || divisor_m <= MagickEpsilon || divisor_c <= MagickEpsilon ) {
/* not enough pixels, or bad weighting in resampling,
resort to direct interpolation */
#if DEBUG_NO_PIXEL_HIT
pixel->opacity = pixel->red = pixel->green = pixel->blue = 0;
pixel->red = QuantumRange; /* show pixels for which EWA fails */
#else
status=InterpolateMagickPixelPacket(resample_filter->image,
resample_filter->view,resample_filter->interpolate,u0,v0,pixel,
resample_filter->exception);
#endif
return status;
}
/*
Finialize results of resampling
*/
divisor_m = 1.0/divisor_m;
pixel->opacity = (MagickRealType) ClampToQuantum(divisor_m*pixel->opacity);
divisor_c = 1.0/divisor_c;
pixel->red = (MagickRealType) ClampToQuantum(divisor_c*pixel->red);
pixel->green = (MagickRealType) ClampToQuantum(divisor_c*pixel->green);
pixel->blue = (MagickRealType) ClampToQuantum(divisor_c*pixel->blue);
if (pixel->colorspace == CMYKColorspace)
pixel->index = (MagickRealType) ClampToQuantum(divisor_c*pixel->index);
return(MagickTrue);
}
#if EWA && EWA_CLAMP
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
- C l a m p U p A x e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClampUpAxes() function converts the input vectors into a major and
% minor axis unit vectors, and their magnitude. This allows us to
% ensure that the ellipse generated is never smaller than the unit
% circle and thus never too small for use in EWA resampling.
%
% This purely mathematical 'magic' was provided by Professor Nicolas
% Robidoux and his Masters student Chantal Racette.
%
% Reference: "We Recommend Singular Value Decomposition", David Austin
% http://www.ams.org/samplings/feature-column/fcarc-svd
%
% By generating major and minor axis vectors, we can actually use the
% ellipse in its "canonical form", by remapping the dx,dy of the
% sampled point into distances along the major and minor axis unit
% vectors.
%
% Reference: http://en.wikipedia.org/wiki/Ellipse#Canonical_form
*/
static inline void ClampUpAxes(const double dux,
const double dvx,
const double duy,
const double dvy,
double *major_mag,
double *minor_mag,
double *major_unit_x,
double *major_unit_y,
double *minor_unit_x,
double *minor_unit_y)
{
/*
* ClampUpAxes takes an input 2x2 matrix
*
* [ a b ] = [ dux duy ]
* [ c d ] = [ dvx dvy ]
*
* and computes from it the major and minor axis vectors [major_x,
* major_y] and [minor_x,minor_y] of the smallest ellipse containing
* both the unit disk and the ellipse which is the image of the unit
* disk by the linear transformation
*
* [ dux duy ] [S] = [s]
* [ dvx dvy ] [T] = [t]
*
* (The vector [S,T] is the difference between a position in output
* space and [X,Y]; the vector [s,t] is the difference between a
* position in input space and [x,y].)
*/
/*
* Output:
*
* major_mag is the half-length of the major axis of the "new"
* ellipse.
*
* minor_mag is the half-length of the minor axis of the "new"
* ellipse.
*
* major_unit_x is the x-coordinate of the major axis direction vector
* of both the "old" and "new" ellipses.
*
* major_unit_y is the y-coordinate of the major axis direction vector.
*
* minor_unit_x is the x-coordinate of the minor axis direction vector.
*
* minor_unit_y is the y-coordinate of the minor axis direction vector.
*
* Unit vectors are useful for computing projections, in particular,
* to compute the distance between a point in output space and the
* center of a unit disk in output space, using the position of the
* corresponding point [s,t] in input space. Following the clamping,
* the square of this distance is
*
* ( ( s * major_unit_x + t * major_unit_y ) / major_mag )^2
* +
* ( ( s * minor_unit_x + t * minor_unit_y ) / minor_mag )^2
*
* If such distances will be computed for many [s,t]'s, it makes
* sense to actually compute the reciprocal of major_mag and
* minor_mag and multiply them by the above unit lengths.
*
* Now, if you want to modify the input pair of tangent vectors so
* that it defines the modified ellipse, all you have to do is set
*
* newdux = major_mag * major_unit_x
* newdvx = major_mag * major_unit_y
* newduy = minor_mag * minor_unit_x = minor_mag * -major_unit_y
* newdvy = minor_mag * minor_unit_y = minor_mag * major_unit_x
*
* and use these tangent vectors as if they were the original ones.
* Usually, this is a drastic change in the tangent vectors even if
* the singular values are not clamped; for example, the minor axis
* vector always points in a direction which is 90 degrees
* counterclockwise from the direction of the major axis vector.
*/
/*
* Discussion:
*
* GOAL: Fix things so that the pullback, in input space, of a disk
* of radius r in output space is an ellipse which contains, at
* least, a disc of radius r. (Make this hold for any r>0.)
*
* ESSENCE OF THE METHOD: Compute the product of the first two
* factors of an SVD of the linear transformation defining the
* ellipse and make sure that both its columns have norm at least 1.
* Because rotations and reflexions map disks to themselves, it is
* not necessary to compute the third (rightmost) factor of the SVD.
*
* DETAILS: Find the singular values and (unit) left singular
* vectors of Jinv, clampling up the singular values to 1, and
* multiply the unit left singular vectors by the new singular
* values in order to get the minor and major ellipse axis vectors.
*
* Image resampling context:
*
* The Jacobian matrix of the transformation at the output point
* under consideration is defined as follows:
*
* Consider the transformation (x,y) -> (X,Y) from input locations
* to output locations. (Anthony Thyssen, elsewhere in resample.c,
* uses the notation (u,v) -> (x,y).)
*
* The Jacobian matrix of the transformation at (x,y) is equal to
*
* J = [ A, B ] = [ dX/dx, dX/dy ]
* [ C, D ] [ dY/dx, dY/dy ]
*
* that is, the vector [A,C] is the tangent vector corresponding to
* input changes in the horizontal direction, and the vector [B,D]
* is the tangent vector corresponding to input changes in the
* vertical direction.
*
* In the context of resampling, it is natural to use the inverse
* Jacobian matrix Jinv because resampling is generally performed by
* pulling pixel locations in the output image back to locations in
* the input image. Jinv is
*
* Jinv = [ a, b ] = [ dx/dX, dx/dY ]
* [ c, d ] [ dy/dX, dy/dY ]
*
* Note: Jinv can be computed from J with the following matrix
* formula:
*
* Jinv = 1/(A*D-B*C) [ D, -B ]
* [ -C, A ]
*
* What we do is modify Jinv so that it generates an ellipse which
* is as close as possible to the original but which contains the
* unit disk. This can be accomplished as follows:
*
* Let
*
* Jinv = U Sigma V^T
*
* be an SVD decomposition of Jinv. (The SVD is not unique, but the
* final ellipse does not depend on the particular SVD.)
*
* We could clamp up the entries of the diagonal matrix Sigma so
* that they are at least 1, and then set
*
* Jinv = U newSigma V^T.
*
* However, we do not need to compute V for the following reason:
* V^T is an orthogonal matrix (that is, it represents a combination
* of rotations and reflexions) so that it maps the unit circle to
* itself. For this reason, the exact value of V does not affect the
* final ellipse, and we can choose V to be the identity
* matrix. This gives
*
* Jinv = U newSigma.
*
* In the end, we return the two diagonal entries of newSigma
* together with the two columns of U.
*/
/*
* ClampUpAxes was written by Nicolas Robidoux and Chantal Racette
* of Laurentian University with insightful suggestions from Anthony
* Thyssen and funding from the National Science and Engineering
* Research Council of Canada. It is distinguished from its
* predecessors by its efficient handling of degenerate cases.
*
* The idea of clamping up the EWA ellipse's major and minor axes so
* that the result contains the reconstruction kernel filter support
* is taken from Andreas Gustaffson's Masters thesis "Interactive
* Image Warping", Helsinki University of Technology, Faculty of
* Information Technology, 59 pages, 1993 (see Section 3.6).
*
* The use of the SVD to clamp up the singular values of the
* Jacobian matrix of the pullback transformation for EWA resampling
* is taken from the astrophysicist Craig DeForest. It is
* implemented in his PDL::Transform code (PDL = Perl Data
* Language).
*/
const double a = dux;
const double b = duy;
const double c = dvx;
const double d = dvy;
/*
* n is the matrix Jinv * transpose(Jinv). Eigenvalues of n are the
* squares of the singular values of Jinv.
*/
const double aa = a*a;
const double bb = b*b;
const double cc = c*c;
const double dd = d*d;
/*
* Eigenvectors of n are left singular vectors of Jinv.
*/
const double n11 = aa+bb;
const double n12 = a*c+b*d;
const double n21 = n12;
const double n22 = cc+dd;
const double det = a*d-b*c;
const double twice_det = det+det;
const double frobenius_squared = n11+n22;
const double discriminant =
(frobenius_squared+twice_det)*(frobenius_squared-twice_det);
/*
* In exact arithmetic, discriminant can't be negative. In floating
* point, it can, because of the bad conditioning of SVD
* decompositions done through the associated normal matrix.
*/
const double sqrt_discriminant =
sqrt(discriminant > 0.0 ? discriminant : 0.0);
/*
* s1 is the largest singular value of the inverse Jacobian
* matrix. In other words, its reciprocal is the smallest singular
* value of the Jacobian matrix itself.
* If s1 = 0, both singular values are 0, and any orthogonal pair of
* left and right factors produces a singular decomposition of Jinv.
*/
/*
* Initially, we only compute the squares of the singular values.
*/
const double s1s1 = 0.5*(frobenius_squared+sqrt_discriminant);
/*
* s2 the smallest singular value of the inverse Jacobian
* matrix. Its reciprocal is the largest singular value of the
* Jacobian matrix itself.
*/
const double s2s2 = 0.5*(frobenius_squared-sqrt_discriminant);
const double s1s1minusn11 = s1s1-n11;
const double s1s1minusn22 = s1s1-n22;
/*
* u1, the first column of the U factor of a singular decomposition
* of Jinv, is a (non-normalized) left singular vector corresponding
* to s1. It has entries u11 and u21. We compute u1 from the fact
* that it is an eigenvector of n corresponding to the eigenvalue
* s1^2.
*/
const double s1s1minusn11_squared = s1s1minusn11*s1s1minusn11;
const double s1s1minusn22_squared = s1s1minusn22*s1s1minusn22;
/*
* The following selects the largest row of n-s1^2 I as the one
* which is used to find the eigenvector. If both s1^2-n11 and
* s1^2-n22 are zero, n-s1^2 I is the zero matrix. In that case,
* any vector is an eigenvector; in addition, norm below is equal to
* zero, and, in exact arithmetic, this is the only case in which
* norm = 0. So, setting u1 to the simple but arbitrary vector [1,0]
* if norm = 0 safely takes care of all cases.
*/
const double temp_u11 =
( (s1s1minusn11_squared>=s1s1minusn22_squared) ? n12 : s1s1minusn22 );
const double temp_u21 =
( (s1s1minusn11_squared>=s1s1minusn22_squared) ? s1s1minusn11 : n21 );
const double norm = sqrt(temp_u11*temp_u11+temp_u21*temp_u21);
/*
* Finalize the entries of first left singular vector (associated
* with the largest singular value).
*/
const double u11 = ( (norm>0.0) ? temp_u11/norm : 1.0 );
const double u21 = ( (norm>0.0) ? temp_u21/norm : 0.0 );
/*
* Clamp the singular values up to 1.
*/
*major_mag = ( (s1s1<=1.0) ? 1.0 : sqrt(s1s1) );
*minor_mag = ( (s2s2<=1.0) ? 1.0 : sqrt(s2s2) );
/*
* Return the unit major and minor axis direction vectors.
*/
*major_unit_x = u11;
*major_unit_y = u21;
*minor_unit_x = -u21;
*minor_unit_y = u11;
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S c a l e R e s a m p l e F i l t e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ScaleResampleFilter() does all the calculations needed to resample an image
% at a specific scale, defined by two scaling vectors. This not using
% a orthogonal scaling, but two distorted scaling vectors, to allow the
% generation of a angled ellipse.
%
% As only two deritive scaling vectors are used the center of the ellipse
% must be the center of the lookup. That is any curvature that the
% distortion may produce is discounted.
%
% The input vectors are produced by either finding the derivitives of the
% distortion function, or the partial derivitives from a distortion mapping.
% They do not need to be the orthogonal dx,dy scaling vectors, but can be
% calculated from other derivatives. For example you could use dr,da/r
% polar coordinate vector scaling vectors
%
% If u,v = DistortEquation(x,y) OR u = Fu(x,y); v = Fv(x,y)
% Then the scaling vectors are determined from the deritives...
% du/dx, dv/dx and du/dy, dv/dy
% If the resulting scaling vectors is othogonally aligned then...
% dv/dx = 0 and du/dy = 0
% Producing an othogonally alligned ellipse in source space for the area to
% be resampled.
%
% Note that scaling vectors are different to argument order. Argument order
% is the general order the deritives are extracted from the distortion
% equations, and not the scaling vectors. As such the middle two vaules
% may be swapped from what you expect. Caution is advised.
%
% WARNING: It is assumed that any SetResampleFilter() method call will
% always be performed before the ScaleResampleFilter() method, so that the
% size of the ellipse will match the support for the resampling filter being
% used.
%
% The format of the ScaleResampleFilter method is:
%
% void ScaleResampleFilter(const ResampleFilter *resample_filter,
% const double dux,const double duy,const double dvx,const double dvy)
%
% A description of each parameter follows:
%
% o resample_filter: the resampling resample_filterrmation defining the
% image being resampled
%
% o dux,duy,dvx,dvy:
% The deritives or scaling vectors defining the EWA ellipse.
% NOTE: watch the order, which is based on the order deritives
% are usally determined from distortion equations (see above).
% The middle two values may need to be swapped if you are thinking
% in terms of scaling vectors.
%
*/
MagickExport void ScaleResampleFilter(ResampleFilter *resample_filter,
const double dux,const double duy,const double dvx,const double dvy)
{
double A,B,C,F;
assert(resample_filter != (ResampleFilter *) NULL);
assert(resample_filter->signature == MagickSignature);
resample_filter->limit_reached = MagickFalse;
/* A 'point' filter forces use of interpolation instead of area sampling */
if ( resample_filter->filter == PointFilter )
return; /* EWA turned off - nothing to do */
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "# -----\n" );
(void) FormatLocaleFile(stderr, "dux=%lf; dvx=%lf; duy=%lf; dvy=%lf;\n",
dux, dvx, duy, dvy);
#endif
/* Find Ellipse Coefficents such that
A*u^2 + B*u*v + C*v^2 = F
With u,v relative to point around which we are resampling.
And the given scaling dx,dy vectors in u,v space
du/dx,dv/dx and du/dy,dv/dy
*/
#if EWA
/* Direct conversion of derivatives into elliptical coefficients
However when magnifying images, the scaling vectors will be small
resulting in a ellipse that is too small to sample properly.
As such we need to clamp the major/minor axis to a minumum of 1.0
to prevent it getting too small.
*/
#if EWA_CLAMP
{ double major_mag,
minor_mag,
major_x,
major_y,
minor_x,
minor_y;
ClampUpAxes(dux,dvx,duy,dvy, &major_mag, &minor_mag,
&major_x, &major_y, &minor_x, &minor_y);
major_x *= major_mag; major_y *= major_mag;
minor_x *= minor_mag; minor_y *= minor_mag;
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "major_x=%lf; major_y=%lf; minor_x=%lf; minor_y=%lf;\n",
major_x, major_y, minor_x, minor_y);
#endif
A = major_y*major_y+minor_y*minor_y;
B = -2.0*(major_x*major_y+minor_x*minor_y);
C = major_x*major_x+minor_x*minor_x;
F = major_mag*minor_mag;
F *= F; /* square it */
}
#else /* raw unclamped EWA */
A = dvx*dvx+dvy*dvy;
B = -2.0*(dux*dvx+duy*dvy);
C = dux*dux+duy*duy;
F = dux*dvy-duy*dvx;
F *= F; /* square it */
#endif /* EWA_CLAMP */
#else /* HQ_EWA */
/*
This Paul Heckbert's "Higher Quality EWA" formula, from page 60 in his
thesis, which adds a unit circle to the elliptical area so as to do both
Reconstruction and Prefiltering of the pixels in the resampling. It also
means it is always likely to have at least 4 pixels within the area of the
ellipse, for weighted averaging. No scaling will result with F == 4.0 and
a circle of radius 2.0, and F smaller than this means magnification is
being used.
NOTE: This method produces a very blury result at near unity scale while
producing perfect results for strong minitification and magnifications.
However filter support is fixed to 2.0 (no good for Windowed Sinc filters)
*/
A = dvx*dvx+dvy*dvy+1;
B = -2.0*(dux*dvx+duy*dvy);
C = dux*dux+duy*duy+1;
F = A*C - B*B/4;
#endif
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "A=%lf; B=%lf; C=%lf; F=%lf\n", A,B,C,F);
/* Figure out the various information directly about the ellipse.
This information currently not needed at this time, but may be
needed later for better limit determination.
It is also good to have as a record for future debugging
*/
{ double alpha, beta, gamma, Major, Minor;
double Eccentricity, Ellipse_Area, Ellipse_Angle;
alpha = A+C;
beta = A-C;
gamma = sqrt(beta*beta + B*B );
if ( alpha - gamma <= MagickEpsilon )
Major= MagickMaximumValue;
else
Major= sqrt(2*F/(alpha - gamma));
Minor = sqrt(2*F/(alpha + gamma));
(void) FormatLocaleFile(stderr, "# Major=%lf; Minor=%lf\n", Major, Minor );
/* other information about ellipse include... */
Eccentricity = Major/Minor;
Ellipse_Area = MagickPI*Major*Minor;
Ellipse_Angle = atan2(B, A-C);
(void) FormatLocaleFile(stderr, "# Angle=%lf Area=%lf\n",
(double) RadiansToDegrees(Ellipse_Angle), Ellipse_Area);
}
#endif
/* If one or both of the scaling vectors is impossibly large
(producing a very large raw F value), we may as well not bother
doing any form of resampling since resampled area is very large.
In this case some alternative means of pixel sampling, such as
the average of the whole image is needed to get a reasonable
result. Calculate only as needed.
*/
if ( (4*A*C - B*B) > MagickMaximumValue ) {
resample_filter->limit_reached = MagickTrue;
return;
}
/* Scale ellipse to match the filters support
(that is, multiply F by the square of the support)
Simplier to just multiply it by the support twice!
*/
F *= resample_filter->support;
F *= resample_filter->support;
/* Orthogonal bounds of the ellipse */
resample_filter->Ulimit = sqrt(C*F/(A*C-0.25*B*B));
resample_filter->Vlimit = sqrt(A*F/(A*C-0.25*B*B));
/* Horizontally aligned parallelogram fitted to Ellipse */
resample_filter->Uwidth = sqrt(F/A); /* Half of the parallelogram width */
resample_filter->slope = -B/(2.0*A); /* Reciprocal slope of the parallelogram */
#if DEBUG_ELLIPSE
(void) FormatLocaleFile(stderr, "Ulimit=%lf; Vlimit=%lf; UWidth=%lf; Slope=%lf;\n",
resample_filter->Ulimit, resample_filter->Vlimit,
resample_filter->Uwidth, resample_filter->slope );
#endif
/* Check the absolute area of the parallelogram involved.
* This limit needs more work, as it is too slow for larger images
* with tiled views of the horizon.
*/
if ( (resample_filter->Uwidth * resample_filter->Vlimit)
> (4.0*resample_filter->image_area)) {
resample_filter->limit_reached = MagickTrue;
return;
}
/* Scale ellipse formula to directly index the Filter Lookup Table */
{ register double scale;
#if FILTER_LUT
/* scale so that F = WLUT_WIDTH; -- hardcoded */
scale = (double)WLUT_WIDTH/F;
#else
/* scale so that F = resample_filter->F (support^2) */
scale = resample_filter->F/F;
#endif
resample_filter->A = A*scale;
resample_filter->B = B*scale;
resample_filter->C = C*scale;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t R e s a m p l e F i l t e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetResampleFilter() set the resampling filter lookup table based on a
% specific filter. Note that the filter is used as a radial filter not as a
% two pass othogonally aligned resampling filter.
%
% The format of the SetResampleFilter method is:
%
% void SetResampleFilter(ResampleFilter *resample_filter,
% const FilterTypes filter,const double blur)
%
% A description of each parameter follows:
%
% o resample_filter: resampling resample_filterrmation structure
%
% o filter: the resize filter for elliptical weighting LUT
%
% o blur: filter blur factor (radial scaling) for elliptical weighting LUT
%
*/
MagickExport void SetResampleFilter(ResampleFilter *resample_filter,
const FilterTypes filter,const double blur)
{
ResizeFilter
*resize_filter;
assert(resample_filter != (ResampleFilter *) NULL);
assert(resample_filter->signature == MagickSignature);
resample_filter->do_interpolate = MagickFalse;
resample_filter->filter = filter;
/* Default cylindrical filter is a Cubic Keys filter */
if ( filter == UndefinedFilter )
resample_filter->filter = RobidouxFilter;
if ( resample_filter->filter == PointFilter ) {
resample_filter->do_interpolate = MagickTrue;
return; /* EWA turned off - nothing more to do */
}
resize_filter = AcquireResizeFilter(resample_filter->image,
resample_filter->filter,blur,MagickTrue,resample_filter->exception);
if (resize_filter == (ResizeFilter *) NULL) {
(void) ThrowMagickException(resample_filter->exception,GetMagickModule(),
ModuleError, "UnableToSetFilteringValue",
"Fall back to Interpolated 'Point' filter");
resample_filter->filter = PointFilter;
resample_filter->do_interpolate = MagickTrue;
return; /* EWA turned off - nothing more to do */
}
/* Get the practical working support for the filter,
* after any API call blur factors have been accoded for.
*/
#if EWA
resample_filter->support = GetResizeFilterSupport(resize_filter);
#else
resample_filter->support = 2.0; /* fixed support size for HQ-EWA */
#endif
#if FILTER_LUT
/* Fill the LUT with the weights from the selected filter function */
{ register int
Q;
double
r_scale;
/* Scale radius so the filter LUT covers the full support range */
r_scale = resample_filter->support*sqrt(1.0/(double)WLUT_WIDTH);
for(Q=0; Q<WLUT_WIDTH; Q++)
resample_filter->filter_lut[Q] = (double)
GetResizeFilterWeight(resize_filter,sqrt((double)Q)*r_scale);
/* finished with the resize filter */
resize_filter = DestroyResizeFilter(resize_filter);
}
#else
/* save the filter and the scaled ellipse bounds needed for filter */
resample_filter->filter_def = resize_filter;
resample_filter->F = resample_filter->support*resample_filter->support;
#endif
/*
Adjust the scaling of the default unit circle
This assumes that any real scaling changes will always
take place AFTER the filter method has been initialized.
*/
ScaleResampleFilter(resample_filter, 1.0, 0.0, 0.0, 1.0);
#if 0
/*
This is old code kept as a reference only. Basically it generates
a Gaussian bell curve, with sigma = 0.5 if the support is 2.0
Create Normal Gaussian 2D Filter Weighted Lookup Table.
A normal EWA guassual lookup would use exp(Q*ALPHA)
where Q = distance squared from 0.0 (center) to 1.0 (edge)
and ALPHA = -4.0*ln(2.0) ==> -2.77258872223978123767
The table is of length 1024, and equates to support radius of 2.0
thus needs to be scaled by ALPHA*4/1024 and any blur factor squared
The it comes from reference code provided by Fred Weinhaus.
*/
r_scale = -2.77258872223978123767/(WLUT_WIDTH*blur*blur);
for(Q=0; Q<WLUT_WIDTH; Q++)
resample_filter->filter_lut[Q] = exp((double)Q*r_scale);
resample_filter->support = WLUT_WIDTH;
#endif
#if FILTER_LUT
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp single
#endif
{
if (IsMagickTrue(GetImageArtifact(resample_filter->image,
"resample:verbose")) )
{
register int
Q;
double
r_scale;
/* Debug output of the filter weighting LUT
Gnuplot the LUT data, the x scale index has been adjusted
plot [0:2][-.2:1] "lut.dat" with lines
The filter values should be normalized for comparision
*/
printf("#\n");
printf("# Resampling Filter LUT (%d values) for '%s' filter\n",
WLUT_WIDTH, CommandOptionToMnemonic(MagickFilterOptions,
resample_filter->filter) );
printf("#\n");
printf("# Note: values in table are using a squared radius lookup.\n");
printf("# As such its distribution is not uniform.\n");
printf("#\n");
printf("# The X value is the support distance for the Y weight\n");
printf("# so you can use gnuplot to plot this cylindrical filter\n");
printf("# plot [0:2][-.2:1] \"lut.dat\" with lines\n");
printf("#\n");
/* Scale radius so the filter LUT covers the full support range */
r_scale = resample_filter->support*sqrt(1.0/(double)WLUT_WIDTH);
for(Q=0; Q<WLUT_WIDTH; Q++)
printf("%8.*g %.*g\n",
GetMagickPrecision(),sqrt((double)Q)*r_scale,
GetMagickPrecision(),resample_filter->filter_lut[Q] );
printf("\n\n"); /* generate a 'break' in gnuplot if multiple outputs */
}
/* Output the above once only for each image, and each setting
(void) DeleteImageArtifact(resample_filter->image,"resample:verbose");
*/
}
#endif /* FILTER_LUT */
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t R e s a m p l e F i l t e r I n t e r p o l a t e M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetResampleFilterInterpolateMethod() sets the resample filter interpolation
% method.
%
% The format of the SetResampleFilterInterpolateMethod method is:
%
% MagickBooleanType SetResampleFilterInterpolateMethod(
% ResampleFilter *resample_filter,const InterpolateMethod method)
%
% A description of each parameter follows:
%
% o resample_filter: the resample filter.
%
% o method: the interpolation method.
%
*/
MagickExport MagickBooleanType SetResampleFilterInterpolateMethod(
ResampleFilter *resample_filter,const InterpolatePixelMethod method)
{
assert(resample_filter != (ResampleFilter *) NULL);
assert(resample_filter->signature == MagickSignature);
assert(resample_filter->image != (Image *) NULL);
if (resample_filter->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
resample_filter->image->filename);
resample_filter->interpolate=method;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t R e s a m p l e F i l t e r V i r t u a l P i x e l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetResampleFilterVirtualPixelMethod() changes the virtual pixel method
% associated with the specified resample filter.
%
% The format of the SetResampleFilterVirtualPixelMethod method is:
%
% MagickBooleanType SetResampleFilterVirtualPixelMethod(
% ResampleFilter *resample_filter,const VirtualPixelMethod method)
%
% A description of each parameter follows:
%
% o resample_filter: the resample filter.
%
% o method: the virtual pixel method.
%
*/
MagickExport MagickBooleanType SetResampleFilterVirtualPixelMethod(
ResampleFilter *resample_filter,const VirtualPixelMethod method)
{
assert(resample_filter != (ResampleFilter *) NULL);
assert(resample_filter->signature == MagickSignature);
assert(resample_filter->image != (Image *) NULL);
if (resample_filter->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
resample_filter->image->filename);
resample_filter->virtual_pixel=method;
if (method != UndefinedVirtualPixelMethod)
(void) SetCacheViewVirtualPixelMethod(resample_filter->view,method);
return(MagickTrue);
}
|
GB_unop__erf_fp32_fp32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the 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__erf_fp32_fp32)
// op(A') function: GB (_unop_tran__erf_fp32_fp32)
// C type: float
// A type: float
// cast: float cij = aij
// unaryop: cij = erff (aij)
#define GB_ATYPE \
float
#define GB_CTYPE \
float
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = erff (x) ;
// casting
#define GB_CAST(z, aij) \
float z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
float aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = aij ; \
Cx [pC] = erff (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_ERF || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__erf_fp32_fp32)
(
float *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
// 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 (float), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
float z = aij ;
Cx [p] = erff (z) ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
float aij = Ax [p] ;
float z = aij ;
Cx [p] = erff (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__erf_fp32_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
transpose.c | /*
Copyright (c) 2013, Intel Corporation
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 Intel Corporation nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER 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.
*/
/*******************************************************************
NAME: transpose
PURPOSE: This program tests the efficiency with which a square matrix
can be transposed and stored in another matrix. The matrices
are distributed identically.
USAGE: Program input is three command line arguments that give the
matrix order, the number of times to repeat the operation
(iterations), and the number of threads to use:
transpose <# threads> <# iterations> <matrix_size> [tile size]
An optional parameter specifies the tile size used to divide the
individual matrix blocks for improved cache and TLB performance.
The output consists of diagnostics to make sure the
transpose worked and timing statistics.
FUNCTIONS CALLED:
Other than OpenMP or standard C functions, the following
functions are used in this program:
wtime() portable wall-timer interface.
bail_out()
test_results() Verify that the transpose worked
HISTORY: Written by Tim Mattson, April 1999.
Updated by Rob Van der Wijngaart, December 2005.
*******************************************************************/
#include <par-res-kern_general.h>
#include <par-res-kern_omp.h>
#define A(i,j) A[i+order*(j)]
#define B(i,j) B[i+order*(j)]
static double test_results (size_t , double*, int);
int main(int argc, char ** argv) {
size_t order; /* order of a the matrix */
size_t i, j, it, jt; /* matrix/tile indices */
int Tile_order=32; /* default tile size for tiling of local transpose */
int iterations; /* number of times to do the transpose */
int iter; /* dummy */
int tiling; /* boolean: true if tiling is used */
double bytes; /* combined size of matrices */
double * RESTRICT A; /* buffer to hold original matrix */
double * RESTRICT B; /* buffer to hold transposed matrix */
double abserr; /* absolute error */
double epsilon=1.e-8; /* error tolerance */
double transpose_time,/* timing parameters */
avgtime;
int nthread_input,
nthread;
int num_error=0; /* flag that signals that requested and
obtained numbers of threads are the same */
/*********************************************************************
** read and test input parameters
*********************************************************************/
printf("Parallel Research Kernels version %s\n", PRKVERSION);
printf("OpenMP Matrix transpose: B = A^T\n");
if (argc != 4 && argc != 5){
printf("Usage: %s <# threads> <# iterations> <matrix order> [tile size]\n",
*argv);
exit(EXIT_FAILURE);
}
/* Take number of threads to request from command line */
nthread_input = atoi(*++argv);
if ((nthread_input < 1) || (nthread_input > MAX_THREADS)) {
printf("ERROR: Invalid number of threads: %d\n", nthread_input);
exit(EXIT_FAILURE);
}
omp_set_num_threads(nthread_input);
iterations = atoi(*++argv);
if (iterations < 1){
printf("ERROR: iterations must be >= 1 : %d \n",iterations);
exit(EXIT_FAILURE);
}
order = atoi(*++argv);
if (order <= 0){
printf("ERROR: Matrix Order must be greater than 0 : %zu \n", order);
exit(EXIT_FAILURE);
}
if (argc == 5) Tile_order = atoi(*++argv);
/* a non-positive tile size means no tiling of the local transpose */
tiling = (Tile_order > 0) && ((size_t)Tile_order < order);
if (!tiling) Tile_order = order;
/*********************************************************************
** Allocate space for the input and transpose matrix
*********************************************************************/
A = (double *)prk_malloc(order*order*sizeof(double));
if (A == NULL){
printf(" ERROR: cannot allocate space for input matrix: %ld\n",
order*order*sizeof(double));
exit(EXIT_FAILURE);
}
B = (double *)prk_malloc(order*order*sizeof(double));
if (B == NULL){
printf(" ERROR: cannot allocate space for output matrix: %ld\n",
order*order*sizeof(double));
exit(EXIT_FAILURE);
}
bytes = 2.0 * sizeof(double) * order * order;
#pragma omp parallel private (i, j, it, jt, iter)
{
#pragma omp master
{
nthread = omp_get_num_threads();
if (nthread != nthread_input) {
num_error = 1;
printf("ERROR: number of requested threads %d does not equal ",
nthread_input);
printf("number of spawned threads %d\n", nthread);
}
else {
printf("Number of threads = %i;\n",nthread_input);
printf("Matrix order = %ld\n", order);
printf("Number of iterations = %d\n", iterations);
if (tiling) {
printf("Tile size = %d\n", Tile_order);
#if COLLAPSE
printf("Loop collapse = on\n");
#else
printf("Loop collapse = off\n");
#endif
}
else
printf("Untiled\n");
}
}
bail_out(num_error);
/* Fill the original matrix, set transpose to known garbage value. */
if (tiling) {
#if COLLAPSE
#pragma omp for collapse(2)
#else
#pragma omp for
#endif
for (j=0; j<order; j+=Tile_order)
for (i=0; i<order; i+=Tile_order)
for (jt=j; jt<MIN(order,j+Tile_order);jt++)
for (it=i; it<MIN(order,i+Tile_order); it++){
A(it,jt) = (double) (order*jt + it);
B(it,jt) = 0.0;
}
}
else {
#pragma omp for
for (j=0;j<order;j++)
for (i=0;i<order; i++) {
A(i,j) = (double) (order*j + i);
B(i,j) = 0.0;
}
}
for (iter = 0; iter<=iterations; iter++){
/* start timer after a warmup iteration */
if (iter == 1) {
#pragma omp barrier
#pragma omp master
{
transpose_time = wtime();
}
}
/* Transpose the matrix */
if (!tiling) {
#pragma omp for
for (i=0;i<order; i++)
for (j=0;j<order;j++) {
B(j,i) += A(i,j);
A(i,j) += 1.0;
}
}
else {
#if COLLAPSE
#pragma omp for collapse(2)
#else
#pragma omp for
#endif
for (i=0; i<order; i+=Tile_order)
for (j=0; j<order; j+=Tile_order)
for (it=i; it<MIN(order,i+Tile_order); it++)
for (jt=j; jt<MIN(order,j+Tile_order);jt++) {
B(jt,it) += A(it,jt);
A(it,jt) += 1.0;
}
}
} /* end of iter loop */
#pragma omp barrier
#pragma omp master
{
transpose_time = wtime() - transpose_time;
}
} /* end of OpenMP parallel region */
abserr = test_results (order, B, iterations);
prk_free(B);
prk_free(A);
/*********************************************************************
** Analyze and output results.
*********************************************************************/
if (abserr < epsilon) {
printf("Solution validates\n");
avgtime = transpose_time/iterations;
printf("Rate (MB/s): %lf Avg time (s): %lf\n",
1.0E-06 * bytes/avgtime, avgtime);
#if VERBOSE
printf("Squared errors: %f \n", abserr);
#endif
exit(EXIT_SUCCESS);
}
else {
printf("ERROR: Aggregate squared error %lf exceeds threshold %e\n",
abserr, epsilon);
exit(EXIT_FAILURE);
}
} /* end of main */
/* function that computes the error committed during the transposition */
double test_results (size_t order, double *B, int iterations) {
double abserr=0.0;
size_t i, j;
double addit = ((double)(iterations+1) * (double) (iterations))/2.0;
#pragma omp parallel for reduction(+:abserr)
for (j=0;j<order;j++) {
for (i=0;i<order; i++) {
abserr += ABS(B(i,j) - ((i*order + j)*(iterations+1L)+addit));
}
}
#if VERBOSE
#pragma omp master
{
printf(" Squared sum of differences: %f\n",abserr);
}
#endif
return abserr;
}
|
adjvectorbqm.h | // Copyright 2020 D-Wave Systems Inc.
//
// 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 DIMOD_ADJVECTORBQM_H_
#define DIMOD_ADJVECTORBQM_H_
#include <stdio.h>
#include <algorithm>
#include <utility>
#include <vector>
#include "dimod/utils.h"
namespace dimod {
template <class V, class B>
class AdjVectorBQM {
public:
using bias_type = B;
using variable_type = V;
using size_type = std::size_t;
using outvars_iterator = typename std::vector<std::pair<V, B>>::iterator;
using const_outvars_iterator =
typename std::vector<std::pair<V, B>>::const_iterator;
// in the future we'd probably like to make this protected
std::vector<std::pair<std::vector<std::pair<V, B>>, B>> adj;
AdjVectorBQM() {}
template <class BQM>
explicit AdjVectorBQM(const BQM &bqm) {
adj.resize(bqm.num_variables());
for (variable_type v = 0; v < bqm.num_variables(); ++v) {
linear(v) = bqm.linear(v);
auto span = bqm.neighborhood(v);
adj[v].first.insert(adj[v].first.begin(), span.first, span.second);
}
}
/**
* Construct a BQM from a dense array.
*
* @param dense An array containing the biases. Assumed to contain
* `num_variables`^2 elements. The upper and lower triangle are summed.
* @param num_variables The number of variables.
*/
template <class B2>
AdjVectorBQM(const B2 dense[], size_type num_variables,
bool ignore_diagonal = false) {
// we know how big our linear is going to be
adj.resize(num_variables);
bias_type qbias;
if (!ignore_diagonal) {
for (size_type v = 0; v < num_variables; ++v) {
adj[v].second = dense[v * (num_variables + 1)];
}
}
for (size_type u = 0; u < num_variables; ++u) {
for (size_type v = u + 1; v < num_variables; ++v) {
qbias = dense[u * num_variables + v] +
dense[v * num_variables + u];
if (qbias != 0) {
adj[u].first.emplace_back(v, qbias);
adj[v].first.emplace_back(u, qbias);
}
}
}
}
/**
* Construct a BQM from a dense array. This constructor is parallelized
* and temporarily zeroes out the diagonal of the dense array but restores
* it back.
*
* @param dense An array containing the biases. Assumed to contain
* `num_variables`^2 elements. The upper and lower triangle are summed.
* @param num_variables The number of variables.
*/
template <class B2>
AdjVectorBQM(B2 dense[], size_type num_variables,
bool ignore_diagonal = false) {
// we know how big our linear is going to be
adj.resize(num_variables);
// Backup copy of the diagonal of the dense matrix.
std::vector<B2> dense_diagonal(num_variables);
if (!ignore_diagonal) {
#pragma omp parallel for
for (size_type v = 0; v < num_variables; ++v) {
adj[v].second = dense[v * (num_variables + 1)];
}
}
#pragma omp parallel
{
// Zero out the diagonal to avoid expensive checks inside innermost
// loop in the code for reading the matrix. The diagonal will be
// restored so a backup copy is saved.
#pragma omp for schedule(static)
for (size_type v = 0; v < num_variables; ++v) {
dense_diagonal[v] = dense[v * (num_variables + 1)];
dense[v * (num_variables + 1)] = 0;
}
size_type counters[BLOCK_SIZE] = {0};
size_type buffer_size = num_variables * BLOCK_SIZE *
sizeof(std::pair<variable_type, bias_type>);
std::pair<variable_type, bias_type> *temp_buffer =
(std::pair<variable_type, bias_type> *)malloc(buffer_size);
if (temp_buffer == NULL) {
printf("Memory allocation failure.\n");
exit(0);
}
// We process the matrix in blocks of size BLOCK_SIZE*BLOCK_SIZE to take
// advantage of cache locality. Dynamic scheduling is used as we know some
// blocks may be more sparse than others and processing them may finish earlier.
#pragma omp for schedule(dynamic)
for (size_type u_st = 0; u_st < num_variables; u_st += BLOCK_SIZE) {
size_type u_end = std::min(u_st + BLOCK_SIZE, num_variables);
for (size_type v_st = 0; v_st < num_variables;
v_st += BLOCK_SIZE) {
size_type v_end =
std::min(v_st + BLOCK_SIZE, num_variables);
for (size_type u = u_st, n = 0; u < u_end; u++, n++) {
size_type counter_u = counters[n];
size_type counter_u_old = counter_u;
for (size_type v = v_st; v < v_end; v++) {
bias_type qbias = dense[u * num_variables + v] +
dense[v * num_variables + u];
if (qbias != 0) {
temp_buffer[n * num_variables + counter_u++] = {
v, qbias};
}
}
if (counter_u != counter_u_old) {
counters[n] = counter_u;
}
}
}
for (size_type n = 0; n < BLOCK_SIZE; n++) {
if (counters[n]) {
adj[u_st + n].first.assign(
temp_buffer + n * num_variables,
temp_buffer + n * num_variables + counters[n]);
counters[n] = 0;
}
}
}
free(temp_buffer);
// Restore the diagonal of the original dense matrix
#pragma omp for schedule(static)
for (size_type v = 0; v < num_variables; ++v) {
dense[v * (num_variables + 1)] = dense_diagonal[v];
}
}
}
/**
* Construct a BQM from COO-formated iterators.
*
* A sparse BQM encoded in [COOrdinate] format is specified by three
* arrays of (row, column, value).
*
* [COOrdinate]: https://w.wiki/n$L
*
* @param row_iterator Iterator pointing to the beginning of the row data.
* Must be a random access iterator.
* @param col_iterator Iterator pointing to the beginning of the column
* data. Must be a random access iterator.
* @param bias_iterator Iterator pointing to the beginning of the bias data.
* Must be a random access iterator.
* @param length The number of (row, column, bias) entries.
* @param ignore_diagonal If true, entries on the diagonal of the sparse
* matrix are ignored.
*/
template <class ItRow, class ItCol, class ItBias>
AdjVectorBQM(ItRow row_iterator, ItCol col_iterator, ItBias bias_iterator,
size_type length, bool ignore_diagonal = false) {
// determine the number of variables so we can allocate adj
if (length > 0) {
size_type max_label = std::max(
*std::max_element(row_iterator, row_iterator + length),
*std::max_element(col_iterator, col_iterator + length));
adj.resize(max_label + 1);
}
// Count the degrees and use that to reserve the neighborhood vectors
std::vector<size_type> degrees(adj.size());
ItRow rit(row_iterator);
ItCol cit(col_iterator);
for (size_type i = 0; i < length; ++i, ++rit, ++cit) {
if (*rit != *cit) {
degrees[*rit] += 1;
degrees[*cit] += 1;
}
}
for (size_type i = 0; i < degrees.size(); ++i) {
adj[i].first.reserve(degrees[i]);
}
// add the values to the adjacency, not worrying about order or
// duplicates
for (size_type i = 0; i < length; i++) {
if (*row_iterator == *col_iterator) {
// linear bias
if (!ignore_diagonal) {
linear(*row_iterator) += *bias_iterator;
}
} else {
// quadratic bias
adj[*row_iterator].first.emplace_back(*col_iterator,
*bias_iterator);
adj[*col_iterator].first.emplace_back(*row_iterator,
*bias_iterator);
}
++row_iterator;
++col_iterator;
++bias_iterator;
}
normalize_neighborhood();
}
/// Add one (disconnected) variable to the BQM and return its index.
variable_type add_variable() {
adj.resize(adj.size() + 1);
return adj.size() - 1;
}
/// Get the degree of variable `v`.
size_type degree(variable_type v) const { return adj[v].first.size(); }
[[deprecated("Use AdjVectorBQM::linear(v)")]] bias_type get_linear(
variable_type v) const { return linear(v); }
std::pair<bias_type, bool> get_quadratic(variable_type u,
variable_type v) const {
assert(u >= 0 && u < adj.size());
assert(v >= 0 && v < adj.size());
assert(u != v);
auto span = neighborhood(u);
auto low = std::lower_bound(span.first, span.second, v,
utils::comp_v<V, B>);
if (low == span.second || low->first != v)
return std::make_pair(0, false);
return std::make_pair(low->second, true);
}
bias_type &linear(variable_type v) {
assert(v >= 0 && v < adj.size());
return adj[v].second;
}
const bias_type &linear(variable_type v) const {
assert(v >= 0 && v < adj.size());
return adj[v].second;
}
std::pair<outvars_iterator, outvars_iterator> neighborhood(
variable_type u) {
assert(u >= 0 && u < adj.size());
return std::make_pair(adj[u].first.begin(), adj[u].first.end());
}
std::pair<const_outvars_iterator, const_outvars_iterator> neighborhood(
variable_type u) const {
assert(u >= 0 && u < adj.size());
return std::make_pair(adj[u].first.cbegin(), adj[u].first.cend());
}
/**
* The neighborhood of variable `v`.
*
* @param A variable `v`.
* @param The neighborhood will start with the first out variable that
* does not compare less than `start`.
*
* @returns A pair of iterators pointing to the start and end of the
* neighborhood.
*/
std::pair<const_outvars_iterator, const_outvars_iterator> neighborhood(
variable_type v, variable_type start) const {
auto span = neighborhood(v);
auto low = std::lower_bound(span.first, span.second, start,
utils::comp_v<V, B>);
return std::make_pair(low, span.second);
}
/// sort each neighborhood and merge duplicates
void normalize_neighborhood() {
for (variable_type v = 0; v < adj.size(); ++v) {
auto span = neighborhood(v);
if (!std::is_sorted(span.first, span.second)) {
std::sort(span.first, span.second);
}
// now merge any duplicate variables, adding the biases
auto it = adj[v].first.begin();
while (it + 1 < adj[v].first.end()) {
if (it->first == (it + 1)->first) {
it->second += (it + 1)->second;
adj[v].first.erase(it + 1);
} else {
++it;
}
}
}
}
template<class Iter>
void normalize_neighborhood(Iter begin, Iter end) {
while (begin != end) {
auto v = *begin;
auto span = neighborhood(v);
if (!std::is_sorted(span.first, span.second)) {
std::sort(span.first, span.second);
}
// now merge any duplicate variables, adding the biases
auto it = adj[v].first.begin();
while (it + 1 < adj[v].first.end()) {
if (it->first == (it + 1)->first) {
it->second += (it + 1)->second;
adj[v].first.erase(it + 1);
} else {
++it;
}
}
++begin;
}
}
size_type num_variables() const { return adj.size(); }
size_type num_interactions() const {
size_type count = 0;
for (auto it = adj.begin(); it != adj.end(); ++it)
count += it->first.size();
return count / 2;
}
variable_type pop_variable() {
assert(adj.size() > 0);
variable_type v = adj.size() - 1;
// remove v from all of its neighbor's neighborhoods
for (auto it = adj[v].first.cbegin(); it != adj[v].first.cend(); ++it) {
auto span = neighborhood(it->first);
auto low = std::lower_bound(span.first, span.second, v,
utils::comp_v<V, B>);
adj[it->first].first.erase(low);
}
adj.pop_back();
return adj.size();
}
bool remove_interaction(variable_type u, variable_type v) {
assert(u >= 0 && u < adj.size());
assert(v >= 0 && v < adj.size());
auto span = neighborhood(u);
auto low = std::lower_bound(span.first, span.second, v,
utils::comp_v<V, B>);
bool exists = !(low == span.second || low->first != v);
if (exists) {
adj[u].first.erase(low);
span = neighborhood(v);
low = std::lower_bound(span.first, span.second, u,
utils::comp_v<V, B>);
assert(!(low == span.second || low->first != u) == exists);
adj[v].first.erase(low);
}
return exists;
}
[[deprecated("Use AdjVectorBQM::linear(v)")]] void set_linear(
variable_type v, bias_type b) {
assert(v >= 0 && v < adj.size());
linear(v) = b;
}
bool set_quadratic(variable_type u, variable_type v, bias_type b) {
assert(u >= 0 && u < adj.size());
assert(v >= 0 && v < adj.size());
assert(u != v);
auto span = neighborhood(u);
auto low = std::lower_bound(span.first, span.second, v,
utils::comp_v<V, B>);
bool exists = !(low == span.second || low->first != v);
if (exists) {
low->second = b;
} else {
adj[u].first.emplace(low, v, b);
}
span = neighborhood(v);
low = std::lower_bound(span.first, span.second, u, utils::comp_v<V, B>);
assert(!(low == span.second || low->first != u) == exists);
if (exists) {
low->second = b;
} else {
adj[v].first.emplace(low, u, b);
}
// to be consistent with AdjArrayBQM, we return whether the value was
// set
return true;
}
};
} // namespace dimod
#endif // DIMOD_ADJVECTORBQM_H_
|
sigmoid_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: hhchen@openailab.com
*/
#include "graph/tensor.h"
#include "graph/node.h"
#include "graph/graph.h"
#include "utility/sys_port.h"
#include "utility/float.h"
#include "utility/log.h"
#include "device/cpu/cpu_node.h"
#include "device/cpu/cpu_graph.h"
#include "device/cpu/cpu_module.h"
#include <math.h>
#define SIGMOID_MAX(a, b) ((a) > (b) ? (a) : (b))
#define SIGMOID_MIN(a, b) ((a) < (b) ? (a) : (b))
int ref_sigmoid_fp32(struct tensor* input_tensor, struct tensor* output_tensor, int num_thread)
{
int dim_num = input_tensor->dim_num;
if (dim_num == 4)
{
int batch = input_tensor->dims[0];
int channel = input_tensor->dims[1];
int cstep = input_tensor->dims[2] * input_tensor->dims[3];
int bstep = channel * cstep;
for (int n = 0; n < batch; n++)
{
#pragma omp parallel for num_threads(num_thread)
for (int c = 0; c < channel; c++)
{
float* input_data = (float*)input_tensor->data + n * bstep + c * cstep;
float* output_data = (float*)output_tensor->data + n * bstep + c * cstep;
for (int i = 0; i < cstep; i++)
{
output_data[i] = SIGMOID_MIN(input_data[i], 30.0f);
output_data[i] = SIGMOID_MAX(input_data[i], -30.0f);
output_data[i] = 1.f / (1 + expf(-output_data[i]));
}
}
}
}
else
{
uint32_t elem_num = input_tensor->elem_num;
float* input_data = (float*)input_tensor->data;
float* output_data = (float*)output_tensor->data;
for (int i = 0; i < elem_num; i++)
{
output_data[i] = SIGMOID_MIN(input_data[i], 30.0f);
output_data[i] = SIGMOID_MAX(input_data[i], -30.0f);
output_data[i] = 1.f / (1 + expf(-output_data[i]));
}
}
return 0;
}
int ref_sigmoid_uint8(struct tensor* input_tensor, struct tensor* output_tensor, int num_thread)
{
/* dequant */
uint8_t* input_uint8 = (uint8_t*)input_tensor->data;
uint8_t* output_uint8 = (uint8_t*)output_tensor->data;
float input_scale = input_tensor->scale;
float output_scale = output_tensor->scale;
int32_t input_zero = input_tensor->zero_point;
int32_t output_zero = output_tensor->zero_point;
int input_size = input_tensor->elem_num;
int output_size = output_tensor->elem_num;
float* input_fp32 = (float*)sys_malloc(input_size * sizeof(float));
float* output_fp32 = (float*)sys_malloc(output_size * sizeof(float));
for (int i = 0; i < input_size; i++)
{
input_fp32[i] = ((float)input_uint8[i] - (float)input_zero) * input_scale;
}
for (int i = 0; i < input_size; i++)
{
output_fp32[i] = SIGMOID_MIN(input_fp32[i], 30.0f);
output_fp32[i] = SIGMOID_MAX(input_fp32[i], -30.0f);
output_fp32[i] = 1 / (1 + exp(-output_fp32[i]));
}
/* quant */
for (int i = 0; i < output_size; i++)
{
int udata = round(output_fp32[i] / output_scale + output_zero);
if (udata > 255)
udata = 255;
else if (udata < 0)
udata = 0;
output_uint8[i] = udata;
}
sys_free(input_fp32);
sys_free(output_fp32);
return 0;
}
static int init_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
return 0;
}
static int release_node(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
return 0;
}
static int reshape_node(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;
int ret = 0;
input_tensor = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]);
output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]);
if (input_tensor->dims[1] != output_tensor->dims[1] || input_tensor->dims[2] != output_tensor->dims[2] || input_tensor->dims[3] != output_tensor->dims[3])
ret = set_ir_tensor_shape(output_tensor, input_tensor->dims, input_tensor->dim_num);
return ret;
}
static int prerun(struct node_ops* node_ops, struct exec_node* exec_node, struct exec_graph* exec_graph)
{
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 = get_ir_graph_tensor(ir_graph, ir_node->input_tensors[0]);
struct tensor* output_tensor = get_ir_graph_tensor(ir_graph, ir_node->output_tensors[0]);
int ret = -1;
if (input_tensor->data_type == TENGINE_DT_FP32)
ret = ref_sigmoid_fp32(input_tensor, output_tensor, exec_graph->num_thread);
else if (input_tensor->data_type == TENGINE_DT_UINT8)
ret = ref_sigmoid_uint8(input_tensor, output_tensor, exec_graph->num_thread);
return ret;
}
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 sigmoid_node_ops = {.prerun = prerun,
.run = run,
.reshape = reshape_node,
.postrun = NULL,
.init_node = init_node,
.release_node = release_node,
.score = score};
int register_sigmoid_ref_op()
{
return register_builtin_node_ops(OP_SIGMOID, &sigmoid_node_ops);
}
int unregister_sigmoid_ref_op()
{
return unregister_builtin_node_ops(OP_SIGMOID, &sigmoid_node_ops);
}
|
GB_dense_ewise3_accum_template.c | //------------------------------------------------------------------------------
// GB_dense_ewise3_accum_template: C += A+B where all 3 matrices are dense
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// FUTURE: allow the accum and the 'plus' op to differ (as in C += A-B,
// with PLUS as the accum and MINUS as the operator, so CBLAS can be used
// for this combination.
{
//--------------------------------------------------------------------------
// get A, B, and C
//--------------------------------------------------------------------------
// any matrix may be aliased to any other (C==A, C==B, and/or A==B)
GB_ATYPE *Ax = (GB_ATYPE *) A->x ;
GB_BTYPE *Bx = (GB_BTYPE *) B->x ;
GB_CTYPE *Cx = (GB_CTYPE *) C->x ;
const int64_t cnz = GB_NNZ (C) ;
int64_t p ;
//--------------------------------------------------------------------------
// C += A+B where all 3 matries are dense
//--------------------------------------------------------------------------
if (A == B)
{
//----------------------------------------------------------------------
// C += A+A where A and C are dense
//----------------------------------------------------------------------
// If the op is PLUS, this becomes C += 2*A. If the op is MINUS,
// almost nothing happens since C=C-(A-A) = C, except if A has Infs or
// NaNs. In this case, don't bother to call the CBLAS if the op is
// MINUS.
#if defined ( GB_HAS_CBLAS ) && GB_OP_IS_PLUS_REAL
// C += 2*A via GB_cblas_saxpy or GB_cblas_daxpy
GB_CBLAS_AXPY (cnz, (GB_CTYPE) 2, Ax, Cx, nthreads) ; // C += 2*A
#else
// C += A+A
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < cnz ; p++)
{
GB_GETA (aij, Ax, p) ; // aij = Ax [p]
GB_CTYPE_SCALAR (t) ; // declare scalar t
GB_BINOP (t, aij, aij) ; // t = aij + aij
GB_BINOP (GB_CX (p), GB_CX (p), t) ; // Cx [p] = cij + t
}
#endif
}
else
{
//----------------------------------------------------------------------
// C += A+B where all 3 matrices are dense
//----------------------------------------------------------------------
#if defined ( GB_HAS_CBLAS ) && GB_OP_IS_PLUS_REAL
// C += A+B via GB_cblas_saxpy or GB_cblas_daxpy
GB_CBLAS_AXPY (cnz, (GB_CTYPE) 1, Ax, Cx, nthreads) ; // C += A
GB_CBLAS_AXPY (cnz, (GB_CTYPE) 1, Bx, Cx, nthreads) ; // C += B
#elif defined ( GB_HAS_CBLAS ) && GB_OP_IS_MINUS_REAL
// C -= (A-B) via GB_cblas_saxpy or GB_cblas_daxpy
GB_CBLAS_AXPY (cnz, (GB_CTYPE) -1, Ax, Cx, nthreads) ; // C -= A
GB_CBLAS_AXPY (cnz, (GB_CTYPE) 1, Bx, Cx, nthreads) ; // C += B
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < cnz ; p++)
{
GB_GETA (aij, Ax, p) ; // aij = Ax [p]
GB_GETB (bij, Bx, p) ; // bij = Bx [p]
GB_CTYPE_SCALAR (t) ; // declare scalar t
GB_BINOP (t, aij, bij) ; // t = aij + bij
GB_BINOP (GB_CX (p), GB_CX (p), t) ; // Cx [p] = cij + t
}
#endif
}
}
|
vect-outer-simd-1.c | /* { dg-require-effective-target vect_simd_clones } */
/* { dg-additional-options "-fopenmp-simd -ffast-math" } */
#include <stdlib.h>
#include "tree-vect.h"
#define N 64
float *px, *py;
float *tx, *ty;
float *x1, *z1, *t1, *t2;
static void inline bar(const float cx, float cy,
float *vx, float *vy)
{
int j;
for (j = 0; j < N; ++j)
{
const float dx = cx - px[j];
const float dy = cy - py[j];
*vx -= dx * tx[j];
*vy -= dy * ty[j];
}
}
__attribute__((noinline, noclone)) void foo1 ()
{
int i;
#pragma omp simd
for (i=0; i<N; i++)
bar(px[i], py[i], x1+i, z1+i);
}
__attribute__((noinline, noclone)) void foo2 ()
{
volatile int i;
for (i=0; i<N; i++)
bar(px[i], py[i], x1+i, z1+i);
}
int main()
{
float *X = (float*)malloc(N * 8 * sizeof (float));
int i;
check_vect ();
px = &X[0];
py = &X[N * 1];
tx = &X[N * 2];
ty = &X[N * 3];
x1 = &X[N * 4];
z1 = &X[N * 5];
t1 = &X[N * 6];
t2 = &X[N * 7];
for (i=0; i<N; i++)
{
px[i] = (float) (i+2);
tx[i] = (float) (i+1);
py[i] = (float) (i+4);
ty[i] = (float) (i+3);
x1[i] = z1[i] = 1.0f;
}
foo1 (); /* vector variant. */
for (i=0; i<N;i++)
{
t1[i] = x1[i]; x1[i] = 1.0f;
t2[i] = z1[i]; z1[i] = 1.0f;
}
foo2 (); /* scalar variant. */
for (i=0; i<N; i++)
if (x1[i] != t1[i] || z1[i] != t2[i])
abort ();
return 0;
}
/* { dg-final { scan-tree-dump "OUTER LOOP VECTORIZED" "vect" } } */
|
pattern.h | #ifndef PATTERN_H
#define PATTERN_H
#include <stdio.h>
#include <stdbool.h>
#include <omp.h>
#include "utils.h"
bool match(char* string, char* mask)
{
char* rs = 0, // Place to return in string if `*` didn't match
* rm; // Place to return in mask
for (;;) {
if (*mask == '*') {
rs = string;
rm = ++mask;
}
else if (!*string) { return !*mask; }
else if (*string == *mask || *mask == '?') {
++string;
++mask;
}
else if (rs) {
string = ++rs;
mask = rm;
}
else { return false; }
}
}
bool search(char** text, ull lines, char* mask)
{
{
bool found = false, lc = false;
ull i = 0;
#pragma omp parallel for private(i) reduction(||: found) num_threads(lines)
iterate(, i, lines) {
lc = match(text[i], mask);
if (lc) { printf("\t\t%llu\n", i); }
found |= lc;
}
return found;
}
}
ull pattern(const char* filename, char* mask)
{
timeval start, end;
FILE* file;
ull lines = 0;
file = fopen(filename, "rb");
if (!file) {
perror("File error");
return 1;
}
while (!feof(file)) {
char character = fgetc(file);
if (character == '\n') {
lines += 1;
}
}
char** text = (char**) malloc(sizeof(char*) * lines);
rewind(file);
iterate(ull, i, lines) {
char* line = (char*) malloc(sizeof(char) * 1024);
fscanf(file, "%s", line); // Read line to buffer
text[i] = line; // Save it
}
/**
* Algorithm
*/
gettimeofday(&start, NULL);
printf("\tString(s) with the pattern found on line(s):\n");
if (!search(text, lines, mask)) { printf("\t\tNone\n"); }
gettimeofday(&end, NULL);
fclose(file); // Close file
iterate(ull, i, lines) { free(text[i]); } // Deallocate lines
free(text); // Deallocate buffer
return ELAPSED;
}
#endif // PATTERN_H
|
kernel.openmp.h | #include <iris/iris_openmp.h>
static void ijk(float* C, float* A, float* B, IRIS_OPENMP_KERNEL_ARGS) {
int i;
#pragma omp parallel for shared(C, A, B) private(i)
IRIS_OPENMP_KERNEL_BEGIN (i)
for (int j = 0; j < _ndr; j++) {
float sum = 0.0;
for (int k = 0; k < _ndr; k++) {
sum += A[i * _ndr + k] * B[k * _ndr + j];
}
C[i * _ndr + j] = sum;
}
IRIS_OPENMP_KERNEL_END
}
|
convolution_1x1_int8.h | // SenseNets is pleased to support the open source community by supporting ncnn available.
//
// Copyright (C) 2018 SenseNets Technology Ltd. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#if __ARM_NEON
#include <arm_neon.h>
#endif // __ARM_NEON
#if __aarch64__
static void conv1x1s1_int8_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Option& opt)
{
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float *kernel = _kernel;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0);
int q = 0;
for (; q+7<inch; q+=8)
{
int* outptr0 = out0;
const signed char *kernel0 = (const signed char *)kernel + p * inch + q;
const signed char *r0 = bottom_blob.channel(q);
const signed char *r1 = bottom_blob.channel(q + 1);
const signed char *r2 = bottom_blob.channel(q + 2);
const signed char *r3 = bottom_blob.channel(q + 3);
const signed char *r4 = bottom_blob.channel(q + 4);
const signed char *r5 = bottom_blob.channel(q + 5);
const signed char *r6 = bottom_blob.channel(q + 6);
const signed char *r7 = bottom_blob.channel(q + 7);
int size = outw * outh;
int remain = size;
for (; remain > 0; remain--)
{
//ToDo Neon
int sum0 = (int)*r0 * (int)kernel0[0] + (int)*r1 * (int)kernel0[1] +
(int)*r2 * (int)kernel0[2] + (int)*r3 * (int)kernel0[3] +
(int)*r4 * (int)kernel0[4] + (int)*r5 * (int)kernel0[5] +
(int)*r6 * (int)kernel0[6] + (int)*r7 * (int)kernel0[7];
*outptr0 += sum0;
r0++;
r1++;
r2++;
r3++;
r4++;
r5++;
r6++;
r7++;
outptr0++;
}
}
for (; q<inch; q++)
{
int* outptr0 = out0;
const signed char *r0 = bottom_blob.channel(q);
const signed char *kernel0 = (const signed char *)kernel + p * inch + q;
const signed char k0 = kernel0[0];
int size = outw * outh;
int remain = size;
for (; remain > 0; remain--)
{
int sum0 = (int)(*r0) * (int)k0;
*outptr0 += sum0;
r0++;
outptr0++;
}
}
}
}
#else // __aarch64__
/*
* Convolution 1x1 quantized with int8,unroll 8 x 4
*/
static void conv1x1s1_neon_s8(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt)
{
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const signed char* kernel = _kernel;
int nn_outch = outch >> 2;
int remain_outch_start = nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 4;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p+1);
Mat out2 = top_blob.channel(p+2);
Mat out3 = top_blob.channel(p+3);
out0.fill(0);
out1.fill(0);
out2.fill(0);
out3.fill(0);
int q = 0;
for (; q+7<inch; q+=8)
{
int* outptr0 = out0;
int* outptr1 = out1;
int* outptr2 = out2;
int* outptr3 = out3;
const signed char* r0 = bottom_blob.channel(q);
const signed char* r1 = bottom_blob.channel(q+1);
const signed char* r2 = bottom_blob.channel(q+2);
const signed char* r3 = bottom_blob.channel(q+3);
const signed char* r4 = bottom_blob.channel(q+4);
const signed char* r5 = bottom_blob.channel(q+5);
const signed char* r6 = bottom_blob.channel(q+6);
const signed char* r7 = bottom_blob.channel(q+7);
const signed char* kernel0 = (const signed char*)kernel + p*inch + q;
const signed char* kernel1 = (const signed char*)kernel + (p+1)*inch + q;
const signed char* kernel2 = (const signed char*)kernel + (p+2)*inch + q;
const signed char* kernel3 = (const signed char*)kernel + (p+3)*inch + q;
int size = outw * outh;
int nn = size >> 3;
int remain = size & 7;
if (nn > 0)
{
asm volatile(
"vld1.s8 d18, [%0] \n"
"vld1.s8 d19, [%1] \n"
"vld1.s8 d24, [%2] \n"
"vld1.s8 d25, [%3] \n"
: "=r"(kernel0), // %0
"=r"(kernel1), // %1
"=r"(kernel2), // %2
"=r"(kernel3) // %3
: "0"(kernel0),
"1"(kernel1),
"2"(kernel2),
"3"(kernel3)
:
);
asm volatile(
"0: \n"
//ld r0-r7
"pld [%5, #64] \n"
"vld1.s8 {d0}, [%5 :64]! \n" //r0
"pld [%6, #64] \n"
"vld1.s8 {d1}, [%6 :64]! \n" //r1
"pld [%7, #64] \n"
"vld1.s8 {d2}, [%7 :64]! \n" //r2
"pld [%8, #64] \n"
"vld1.s8 {d3}, [%8 :64]! \n" //r3
"pld [%9, #64] \n"
"vld1.s8 {d4}, [%9 :64]! \n" //r4
"pld [%10, #64] \n"
"vld1.s8 {d5}, [%10 :64]! \n" //r5
"pld [%11, #64] \n"
"vld1.s8 {d6}, [%11 :64]! \n" //r6
"pld [%12, #64] \n"
"vld1.s8 {d7}, [%12 :64]! \n" //r7
//###########################################
//load inch kernel_0 k0-k7
"vdup.s8 d8, d18[0] \n"
"vdup.s8 d9, d18[1] \n"
"vdup.s8 d10, d18[2] \n"
"vdup.s8 d11, d18[3] \n"
"vdup.s8 d12, d18[4] \n"
"vdup.s8 d13, d18[5] \n"
"vdup.s8 d14, d18[6] \n"
"vdup.s8 d15, d18[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr0_s32
"pld [%1, #256] \n"
"vld1.32 {d20-d23}, [%1:128] \n" //outptr0_s32
"vaddw.s16 q10, q10, d16 \n"
"vaddw.s16 q11, q11, d17 \n"
"vst1.32 {d20-d23}, [%1:128]!\n"
//###########################################
//load inch kernel_1 k0-k7
"vdup.s8 d8, d19[0] \n"
"vdup.s8 d9, d19[1] \n"
"vdup.s8 d10, d19[2] \n"
"vdup.s8 d11, d19[3] \n"
"vdup.s8 d12, d19[4] \n"
"vdup.s8 d13, d19[5] \n"
"vdup.s8 d14, d19[6] \n"
"vdup.s8 d15, d19[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr1_s32
"pld [%2, #256] \n"
"vld1.32 {d20-d23}, [%2:128] \n" //outptr1_s32
"vaddw.s16 q10, q10, d16 \n"
"vaddw.s16 q11, q11, d17 \n"
"vst1.32 {d20-d23}, [%2:128]!\n"
//############################################
//load inch kernel_2 k0-k7
"vdup.s8 d8, d24[0] \n"
"vdup.s8 d9, d24[1] \n"
"vdup.s8 d10, d24[2] \n"
"vdup.s8 d11, d24[3] \n"
"vdup.s8 d12, d24[4] \n"
"vdup.s8 d13, d24[5] \n"
"vdup.s8 d14, d24[6] \n"
"vdup.s8 d15, d24[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr2_s32
"pld [%3, #256] \n"
"vld1.32 {d20-d23}, [%3:128] \n" //outptr2_s32
"vaddw.s16 q10, q10, d16 \n"
"vaddw.s16 q11, q11, d17 \n"
"vst1.32 {d20-d23}, [%3:128]!\n"
//#############################################
//load inch kernel_3 k0-k7
"vdup.s8 d8, d25[0] \n"
"vdup.s8 d9, d25[1] \n"
"vdup.s8 d10, d25[2] \n"
"vdup.s8 d11, d25[3] \n"
"vdup.s8 d12, d25[4] \n"
"vdup.s8 d13, d25[5] \n"
"vdup.s8 d14, d25[6] \n"
"vdup.s8 d15, d25[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr3_s32
"pld [%4, #256] \n"
"vld1.32 {d20-d23}, [%4:128] \n" //outptr3_s32
"vaddw.s16 q10, q10, d16 \n"
"vaddw.s16 q11, q11, d17 \n"
"vst1.32 {d20-d23}, [%4:128]!\n"
//next
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(r0), // %5
"=r"(r1), // %6
"=r"(r2), // %7
"=r"(r3), // %8
"=r"(r4), // %9
"=r"(r5), // %10
"=r"(r6), // %11
"=r"(r7) // %12
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(r0),
"6"(r1),
"7"(r2),
"8"(r3),
"9"(r4),
"10"(r5),
"11"(r6),
"12"(r7)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q10", "q11", "q13", "q14", "q15"
);
}
for (; remain>0; remain--)
{
//ToDo Neon
int sum0 = (int)*r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3] + *r4 * kernel0[4] + *r5 * kernel0[5] + *r6 * kernel0[6] + *r7 * kernel0[7];
int sum1 = (int)*r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3] + *r4 * kernel1[4] + *r5 * kernel1[5] + *r6 * kernel1[6] + *r7 * kernel1[7];
int sum2 = (int)*r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3] + *r4 * kernel2[4] + *r5 * kernel2[5] + *r6 * kernel2[6] + *r7 * kernel2[7];
int sum3 = (int)*r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3] + *r4 * kernel3[4] + *r5 * kernel3[5] + *r6 * kernel3[6] + *r7 * kernel3[7];
*outptr0 += sum0;
*outptr1 += sum1;
*outptr2 += sum2;
*outptr3 += sum3;
r0++;
r1++;
r2++;
r3++;
r4++;
r5++;
r6++;
r7++;
outptr0++;
outptr1++;
outptr2++;
outptr3++;
}
}
for (; q<inch; q++)
{
int* outptr0 = out0;
int* outptr1 = out1;
int* outptr2 = out2;
int* outptr3 = out3;
const signed char* img0_s8 = bottom_blob.channel(q);
const signed char* kernel0 = (const signed char*)kernel + p*inch + q;
const signed char* kernel1 = (const signed char*)kernel + (p+1)*inch + q;
const signed char* kernel2 = (const signed char*)kernel + (p+2)*inch + q;
const signed char* kernel3 = (const signed char*)kernel + (p+3)*inch + q;
const signed char k0 = kernel0[0];
const signed char k1 = kernel1[0];
const signed char k2 = kernel2[0];
const signed char k3 = kernel3[0];
const signed char* r0 = img0_s8;
int size = outw * outh;
int nn = size >> 3;
int remain = size & 7;
int8x8_t _k0 = vdup_n_s8(k0);
int8x8_t _k1 = vdup_n_s8(k1);
int8x8_t _k2 = vdup_n_s8(k2);
int8x8_t _k3 = vdup_n_s8(k3);
if (nn > 0)
{
asm volatile(
"0: \n"
//load r0
"pld [%5, #64] \n"
"vld1.s8 {d8}, [%5 :64]! \n"
//mla
"vmull.s8 q5, d8, %12 \n"
//outptr0_s32
"pld [%1, #256] \n"
"vld1.32 {d12-d15}, [%1] \n"
"vmovl.s16 q8, d10 \n"
"vmovl.s16 q9, d11 \n"
"vadd.s32 q6, q8 \n"
"vadd.s32 q7, q9 \n"
"vst1.32 {d12-d15}, [%1]! \n"
//mla
"vmull.s8 q5, d8, %13 \n"
//outptr1_s32
"pld [%2, #256] \n"
"vld1.32 {d12-d15}, [%2] \n"
"vaddw.s16 q6, q6, d10 \n"
"vaddw.s16 q7, q7, d11 \n"
"vst1.32 {d12-d15}, [%2]! \n"
//mla
"vmull.s8 q5, d8, %14 \n"
//outptr0_s32
"pld [%3, #256] \n"
"vld1.32 {d12-d15}, [%3] \n"
"vaddw.s16 q6, q6, d10 \n"
"vaddw.s16 q7, q7, d11 \n"
"vst1.32 {d12-d15}, [%3]! \n"
//mla
"vmull.s8 q5, d8, %15 \n"
//outptr0_s32
"pld [%4, #256] \n"
"vld1.32 {d12-d15}, [%4] \n"
"vaddw.s16 q6, q6, d10 \n"
"vaddw.s16 q7, q7, d11 \n"
"vst1.32 {d12-d15}, [%4]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(r0) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(r0),
"w"(_k0), // %12
"w"(_k1), // %13
"w"(_k2), // %14
"w"(_k3) // %15
: "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9"
);
}
for (; remain>0; remain--)
{
// TODO neon optimize
int sum0 = (int)*r0 * k0;
int sum1 = (int)*r0 * k1;
int sum2 = (int)*r0 * k2;
int sum3 = (int)*r0 * k3;
*outptr0 += sum0;
*outptr1 += sum1;
*outptr2 += sum2;
*outptr3 += sum3;
r0++;
outptr0++;
outptr1++;
outptr2++;
outptr3++;
}
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0);
int q = 0;
for (; q+7<inch; q+=8)
{
int* outptr0 = out0;
const signed char* r0 = bottom_blob.channel(q);
const signed char* r1 = bottom_blob.channel(q+1);
const signed char* r2 = bottom_blob.channel(q+2);
const signed char* r3 = bottom_blob.channel(q+3);
const signed char* r4 = bottom_blob.channel(q+4);
const signed char* r5 = bottom_blob.channel(q+5);
const signed char* r6 = bottom_blob.channel(q+6);
const signed char* r7 = bottom_blob.channel(q+7);
const signed char* kernel0 = (const signed char*)kernel + p*inch + q;
int size = outw * outh;
int nn = size >> 3;
int remain = size & 7;
if (nn > 0)
{
//load inch kernel_0 k0-k7
asm volatile(
"vld1.s8 d18, [%0] \n"
: "=r"(kernel0) // %0
: "0" (kernel0)
:
);
asm volatile(
"0: \n"
//ld r0-r7
"pld [%2, #64] \n"
"vld1.s8 {d0}, [%2 :64]! \n" //r0
"pld [%3, #64] \n"
"vld1.s8 {d1}, [%3 :64]! \n" //r1
"pld [%4, #64] \n"
"vld1.s8 {d2}, [%4 :64]! \n" //r2
"pld [%5, #64] \n"
"vld1.s8 {d3}, [%5 :64]! \n" //r3
"pld [%6, #64] \n"
"vld1.s8 {d4}, [%6 :64]! \n" //r4
"pld [%7, #64] \n"
"vld1.s8 {d5}, [%7 :64]! \n" //r5
"pld [%8, #64] \n"
"vld1.s8 {d6}, [%8 :64]! \n" //r6
"pld [%9, #64] \n"
"vld1.s8 {d7}, [%9 :64]! \n" //r7
//load inch kernel_0 k0-k7
"vdup.s8 d8, d18[0] \n"
"vdup.s8 d9, d18[1] \n"
"vdup.s8 d10, d18[2] \n"
"vdup.s8 d11, d18[3] \n"
"vdup.s8 d12, d18[4] \n"
"vdup.s8 d13, d18[5] \n"
"vdup.s8 d14, d18[6] \n"
"vdup.s8 d15, d18[7] \n"
//mla
"vmull.s8 q14, d0, d8 \n"
"vmlal.s8 q14, d1, d9 \n"
"vmlal.s8 q14, d2, d10 \n"
"vmlal.s8 q14, d3, d11 \n"
"vmlal.s8 q14, d4, d12 \n"
"vmlal.s8 q14, d5, d13 \n"
"vmlal.s8 q14, d6, d14 \n"
"vmlal.s8 q14, d7, d15 \n"
//outptr0_s32
"pld [%1, #256] \n"
"vld1.32 {d20-d23}, [%1] \n" //outptr0_s32
"vaddw.s16 q10, q10, d28 \n"
"vaddw.s16 q11, q11, d29 \n"
"vst1.32 {d20-d23}, [%1]! \n"
//next
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2), // %4
"=r"(r3), // %5
"=r"(r4), // %6
"=r"(r5), // %7
"=r"(r6), // %8
"=r"(r7) // %9
: "0"(nn),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2),
"5"(r3),
"6"(r4),
"7"(r5),
"8"(r6),
"9"(r7)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q10", "q11", "q12", "q13", "q14"
);
}
for (; remain>0; remain--)
{
//ToDo Neon
int sum0 = (int)*r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3] + *r4 * kernel0[4] + *r5 * kernel0[5] + *r6 * kernel0[6] + *r7 * kernel0[7];
*outptr0 += sum0;
r0++;
r1++;
r2++;
r3++;
r4++;
r5++;
r6++;
r7++;
outptr0++;
}
}
for (; q<inch; q++)
{
int* outptr0 = out0;
const signed char* img0_s8 = bottom_blob.channel(q);
const signed char* r0 = img0_s8;
const signed char* kernel0 = (const signed char*)kernel + p*inch + q;
const signed char k0 = kernel0[0];
int size = outw * outh;
int nn = size >> 3;
int remain = size & 7;
int8x8_t _k0 = vdup_n_s8(k0);
if (nn > 0)
{
asm volatile(
"0: \n"
//load r0
"pld [%2, #64] \n"
"vld1.s8 {d8}, [%2 :64]! \n"
//mla
"vmull.s8 q10, d8, %6 \n"
//outptr0_s32
"pld [%1, #256] \n"
"vld1.32 {d12-d15}, [%1] \n"
"vaddw.s16 q6, q6, d20 \n"
"vaddw.s16 q7, q7, d21 \n"
"vst1.32 {d12-d15}, [%1]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(r0) // %2
: "0"(nn),
"1"(outptr0),
"2"(r0),
"w"(_k0) // %6
: "cc", "memory", "q4", "q10", "q7", "q8", "q9"
);
}
for (; remain>0; remain--)
{
int sum0 = (int)*r0 * k0;
*outptr0 += sum0;
r0++;
outptr0++;
}
}
}
}
static void conv1x1s1_neon_s8_left4(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt)
{
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const signed char* kernel = _kernel;
int nn_outch = outch >> 2;
int remain_outch_start = nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 4;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p+1);
Mat out2 = top_blob.channel(p+2);
Mat out3 = top_blob.channel(p+3);
out0.fill(0);
out1.fill(0);
out2.fill(0);
out3.fill(0);
int q = 0;
for (; q+7<inch; q+=8)
{
int* outptr0 = out0;
int* outptr1 = out1;
int* outptr2 = out2;
int* outptr3 = out3;
const signed char* r0 = bottom_blob.channel(q);
const signed char* r1 = bottom_blob.channel(q+1);
const signed char* r2 = bottom_blob.channel(q+2);
const signed char* r3 = bottom_blob.channel(q+3);
const signed char* r4 = bottom_blob.channel(q+4);
const signed char* r5 = bottom_blob.channel(q+5);
const signed char* r6 = bottom_blob.channel(q+6);
const signed char* r7 = bottom_blob.channel(q+7);
const signed char* kernel0 = (const signed char*)kernel + p*inch + q;
const signed char* kernel1 = (const signed char*)kernel + (p+1)*inch + q;
const signed char* kernel2 = (const signed char*)kernel + (p+2)*inch + q;
const signed char* kernel3 = (const signed char*)kernel + (p+3)*inch + q;
int size = outw * outh;
int nn = size >> 3;
asm volatile(
"vld1.s8 d18, [%0] \n"
"vld1.s8 d19, [%1] \n"
"vld1.s8 d24, [%2] \n"
"vld1.s8 d25, [%3] \n"
: "=r"(kernel0), // %0
"=r"(kernel1), // %1
"=r"(kernel2), // %2
"=r"(kernel3) // %3
: "0"(kernel0),
"1"(kernel1),
"2"(kernel2),
"3"(kernel3)
:
);
if (nn > 0)
{
asm volatile(
"0: \n"
//ld r0-r7
"pld [%5, #64] \n"
"vld1.s8 {d0}, [%5 :64]! \n" //r0
"pld [%6, #64] \n"
"vld1.s8 {d1}, [%6 :64]! \n" //r1
"pld [%7, #64] \n"
"vld1.s8 {d2}, [%7 :64]! \n" //r2
"pld [%8, #64] \n"
"vld1.s8 {d3}, [%8 :64]! \n" //r3
"pld [%9, #64] \n"
"vld1.s8 {d4}, [%9 :64]! \n" //r4
"pld [%10, #64] \n"
"vld1.s8 {d5}, [%10 :64]! \n" //r5
"pld [%11, #64] \n"
"vld1.s8 {d6}, [%11 :64]! \n" //r6
"pld [%12, #64] \n"
"vld1.s8 {d7}, [%12 :64]! \n" //r7
//###########################################
//load inch kernel_0 k0-k7
"vdup.s8 d8, d18[0] \n"
"vdup.s8 d9, d18[1] \n"
"vdup.s8 d10, d18[2] \n"
"vdup.s8 d11, d18[3] \n"
"vdup.s8 d12, d18[4] \n"
"vdup.s8 d13, d18[5] \n"
"vdup.s8 d14, d18[6] \n"
"vdup.s8 d15, d18[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr0_s32
"pld [%1, #256] \n"
"vld1.32 {d20-d23}, [%1:128] \n" //outptr0_s32
"vaddw.s16 q10, q10, d16 \n"
"vaddw.s16 q11, q11, d17 \n"
"vst1.32 {d20-d23}, [%1:128]!\n"
//###########################################
//load inch kernel_1 k0-k7
"vdup.s8 d8, d19[0] \n"
"vdup.s8 d9, d19[1] \n"
"vdup.s8 d10, d19[2] \n"
"vdup.s8 d11, d19[3] \n"
"vdup.s8 d12, d19[4] \n"
"vdup.s8 d13, d19[5] \n"
"vdup.s8 d14, d19[6] \n"
"vdup.s8 d15, d19[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr1_s32
"pld [%2, #256] \n"
"vld1.32 {d20-d23}, [%2:128] \n" //outptr1_s32
"vaddw.s16 q10, q10, d16 \n"
"vaddw.s16 q11, q11, d17 \n"
"vst1.32 {d20-d23}, [%2:128]!\n"
//############################################
//load inch kernel_2 k0-k7
"vdup.s8 d8, d24[0] \n"
"vdup.s8 d9, d24[1] \n"
"vdup.s8 d10, d24[2] \n"
"vdup.s8 d11, d24[3] \n"
"vdup.s8 d12, d24[4] \n"
"vdup.s8 d13, d24[5] \n"
"vdup.s8 d14, d24[6] \n"
"vdup.s8 d15, d24[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr2_s32
"pld [%3, #256] \n"
"vld1.32 {d20-d23}, [%3:128] \n" //outptr2_s32
"vaddw.s16 q10, q10, d16 \n"
"vaddw.s16 q11, q11, d17 \n"
"vst1.32 {d20-d23}, [%3:128]!\n"
//#############################################
//load inch kernel_3 k0-k7
"vdup.s8 d8, d25[0] \n"
"vdup.s8 d9, d25[1] \n"
"vdup.s8 d10, d25[2] \n"
"vdup.s8 d11, d25[3] \n"
"vdup.s8 d12, d25[4] \n"
"vdup.s8 d13, d25[5] \n"
"vdup.s8 d14, d25[6] \n"
"vdup.s8 d15, d25[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr3_s32
"pld [%4, #256] \n"
"vld1.32 {d20-d23}, [%4:128] \n" //outptr3_s32
"vaddw.s16 q10, q10, d16 \n"
"vaddw.s16 q11, q11, d17 \n"
"vst1.32 {d20-d23}, [%4:128]!\n"
//next
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(r0), // %5
"=r"(r1), // %6
"=r"(r2), // %7
"=r"(r3), // %8
"=r"(r4), // %9
"=r"(r5), // %10
"=r"(r6), // %11
"=r"(r7) // %12
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(r0),
"6"(r1),
"7"(r2),
"8"(r3),
"9"(r4),
"10"(r5),
"11"(r6),
"12"(r7)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q10", "q11"
);
}
asm volatile(
"0: \n"
//ld r0-r7
"pld [%5, #64] \n"
"vld1.s8 {d0}, [%5 :64] \n" //r0
"pld [%6, #64] \n"
"vld1.s8 {d1}, [%6 :64] \n" //r1
"pld [%7, #64] \n"
"vld1.s8 {d2}, [%7 :64] \n" //r2
"pld [%8, #64] \n"
"vld1.s8 {d3}, [%8 :64] \n" //r3
"pld [%9, #64] \n"
"vld1.s8 {d4}, [%9 :64] \n" //r4
"pld [%10, #64] \n"
"vld1.s8 {d5}, [%10 :64] \n" //r5
"pld [%11, #64] \n"
"vld1.s8 {d6}, [%11 :64] \n" //r6
"pld [%12, #64] \n"
"vld1.s8 {d7}, [%12 :64] \n" //r7
"add %5, #4 \n"
"add %6, #4 \n"
"add %7, #4 \n"
"add %8, #4 \n"
"add %9, #4 \n"
"add %10, #4 \n"
"add %11, #4 \n"
"add %12, #4 \n"
//###########################################
//load inch kernel_0 k0-k7
"vdup.s8 d8, d18[0] \n"
"vdup.s8 d9, d18[1] \n"
"vdup.s8 d10, d18[2] \n"
"vdup.s8 d11, d18[3] \n"
"vdup.s8 d12, d18[4] \n"
"vdup.s8 d13, d18[5] \n"
"vdup.s8 d14, d18[6] \n"
"vdup.s8 d15, d18[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr0_s32
"pld [%1, #128] \n"
"vld1.32 {d20-d21}, [%1:128] \n" //outptr0_s32
"vaddw.s16 q10, q10, d16 \n"
"vst1.32 {d20-d21}, [%1:128]!\n"
//###########################################
//load inch kernel_1 k0-k7
"vdup.s8 d8, d19[0] \n"
"vdup.s8 d9, d19[1] \n"
"vdup.s8 d10, d19[2] \n"
"vdup.s8 d11, d19[3] \n"
"vdup.s8 d12, d19[4] \n"
"vdup.s8 d13, d19[5] \n"
"vdup.s8 d14, d19[6] \n"
"vdup.s8 d15, d19[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr1_s32
"pld [%2, #128] \n"
"vld1.32 {d20-d21}, [%2:128] \n" //outptr1_s32
"vaddw.s16 q10, q10, d16 \n"
"vst1.32 {d20-d21}, [%2:128]!\n"
//############################################
//load inch kernel_2 k0-k7
"vdup.s8 d8, d24[0] \n"
"vdup.s8 d9, d24[1] \n"
"vdup.s8 d10, d24[2] \n"
"vdup.s8 d11, d24[3] \n"
"vdup.s8 d12, d24[4] \n"
"vdup.s8 d13, d24[5] \n"
"vdup.s8 d14, d24[6] \n"
"vdup.s8 d15, d24[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr2_s32
"pld [%3, #256] \n"
"vld1.32 {d20-d21}, [%3:128] \n" //outptr2_s32
"vaddw.s16 q10, q10, d16 \n"
"vst1.32 {d20-d21}, [%3:128]!\n"
//#############################################
//load inch kernel_3 k0-k7
"vdup.s8 d8, d25[0] \n"
"vdup.s8 d9, d25[1] \n"
"vdup.s8 d10, d25[2] \n"
"vdup.s8 d11, d25[3] \n"
"vdup.s8 d12, d25[4] \n"
"vdup.s8 d13, d25[5] \n"
"vdup.s8 d14, d25[6] \n"
"vdup.s8 d15, d25[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr3_s32
"pld [%4, #256] \n"
"vld1.32 {d20-d21}, [%4:128] \n" //outptr3_s32
"vaddw.s16 q10, q10, d16 \n"
"vst1.32 {d20-d21}, [%4:128]!\n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(r0), // %5
"=r"(r1), // %6
"=r"(r2), // %7
"=r"(r3), // %8
"=r"(r4), // %9
"=r"(r5), // %10
"=r"(r6), // %11
"=r"(r7) // %12
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(r0),
"6"(r1),
"7"(r2),
"8"(r3),
"9"(r4),
"10"(r5),
"11"(r6),
"12"(r7)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q10", "q11"
);
}
for (; q<inch; q++)
{
int* outptr0 = out0;
int* outptr1 = out1;
int* outptr2 = out2;
int* outptr3 = out3;
const signed char* img0_s8 = bottom_blob.channel(q);
const signed char* kernel0 = (const signed char*)kernel + p*inch + q;
const signed char* kernel1 = (const signed char*)kernel + (p+1)*inch + q;
const signed char* kernel2 = (const signed char*)kernel + (p+2)*inch + q;
const signed char* kernel3 = (const signed char*)kernel + (p+3)*inch + q;
const signed char k0 = kernel0[0];
const signed char k1 = kernel1[0];
const signed char k2 = kernel2[0];
const signed char k3 = kernel3[0];
const signed char* r0 = img0_s8;
int size = outw * outh;
int nn = size >> 3;
int remain = size & 7;
int8x8_t _k0 = vdup_n_s8(k0);
int8x8_t _k1 = vdup_n_s8(k1);
int8x8_t _k2 = vdup_n_s8(k2);
int8x8_t _k3 = vdup_n_s8(k3);
if (nn > 0)
{
asm volatile(
"0: \n"
//load r0
"pld [%5, #64] \n"
"vld1.s8 {d8}, [%5 :64]! \n"
//mla
"vmull.s8 q5, d8, %12 \n"
//outptr0_s32
"pld [%1, #256] \n"
"vld1.32 {d12-d15}, [%1] \n"
"vaddw.s16 q6, q6, d10 \n"
"vaddw.s16 q7, q7, d11 \n"
"vst1.32 {d12-d15}, [%1]! \n"
//mla
"vmull.s8 q5, d8, %13 \n"
//outptr1_s32
"pld [%2, #256] \n"
"vld1.32 {d12-d15}, [%2] \n"
"vaddw.s16 q6, q6, d10 \n"
"vaddw.s16 q7, q7, d11 \n"
"vst1.32 {d12-d15}, [%2]! \n"
//mla
"vmull.s8 q5, d8, %14 \n"
//outptr0_s32
"pld [%3, #256] \n"
"vld1.32 {d12-d15}, [%3] \n"
"vaddw.s16 q6, q6, d10 \n"
"vaddw.s16 q7, q7, d11 \n"
"vst1.32 {d12-d15}, [%3]! \n"
//mla
"vmull.s8 q5, d8, %15 \n"
//outptr0_s32
"pld [%4, #256] \n"
"vld1.32 {d12-d15}, [%4] \n"
"vaddw.s16 q6, q6, d10 \n"
"vaddw.s16 q7, q7, d11 \n"
"vst1.32 {d12-d15}, [%4]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(r0) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(r0),
"w"(_k0), // %12
"w"(_k1), // %13
"w"(_k2), // %14
"w"(_k3) // %15
: "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9"
);
}
for (; remain>0; remain--)
{
// TODO neon optimize
int sum0 = (int)*r0 * k0;
int sum1 = (int)*r0 * k1;
int sum2 = (int)*r0 * k2;
int sum3 = (int)*r0 * k3;
*outptr0 += sum0;
*outptr1 += sum1;
*outptr2 += sum2;
*outptr3 += sum3;
r0++;
outptr0++;
outptr1++;
outptr2++;
outptr3++;
}
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0);
int q = 0;
for (; q+7<inch; q+=8)
{
int* outptr0 = out0;
const signed char* r0 = bottom_blob.channel(q);
const signed char* r1 = bottom_blob.channel(q+1);
const signed char* r2 = bottom_blob.channel(q+2);
const signed char* r3 = bottom_blob.channel(q+3);
const signed char* r4 = bottom_blob.channel(q+4);
const signed char* r5 = bottom_blob.channel(q+5);
const signed char* r6 = bottom_blob.channel(q+6);
const signed char* r7 = bottom_blob.channel(q+7);
const signed char* kernel0 = (const signed char*)kernel + p*inch + q;
int size = outw * outh;
int nn = size >> 3;
int remain = size & 7;
if (nn > 0)
{
//load inch kernel_0 k0-k7
asm volatile(
"vld1.s8 d18, [%0] \n"
: "=r"(kernel0) // %0
: "0" (kernel0)
:
);
asm volatile(
"0: \n"
//ld r0-r7
"pld [%2, #64] \n"
"vld1.s8 {d0}, [%2 :64]! \n" //r0
"pld [%3, #64] \n"
"vld1.s8 {d1}, [%3 :64]! \n" //r1
"pld [%4, #64] \n"
"vld1.s8 {d2}, [%4 :64]! \n" //r2
"pld [%5, #64] \n"
"vld1.s8 {d3}, [%5 :64]! \n" //r3
"pld [%6, #64] \n"
"vld1.s8 {d4}, [%6 :64]! \n" //r4
"pld [%7, #64] \n"
"vld1.s8 {d5}, [%7 :64]! \n" //r5
"pld [%8, #64] \n"
"vld1.s8 {d6}, [%8 :64]! \n" //r6
"pld [%9, #64] \n"
"vld1.s8 {d7}, [%9 :64]! \n" //r7
//load inch kernel_0 k0-k7
"vdup.s8 d8, d18[0] \n"
"vdup.s8 d9, d18[1] \n"
"vdup.s8 d10, d18[2] \n"
"vdup.s8 d11, d18[3] \n"
"vdup.s8 d12, d18[4] \n"
"vdup.s8 d13, d18[5] \n"
"vdup.s8 d14, d18[6] \n"
"vdup.s8 d15, d18[7] \n"
//mla
"vmull.s8 q8, d0, d8 \n"
"vmlal.s8 q8, d1, d9 \n"
"vmlal.s8 q8, d2, d10 \n"
"vmlal.s8 q8, d3, d11 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q8, d5, d13 \n"
"vmlal.s8 q8, d6, d14 \n"
"vmlal.s8 q8, d7, d15 \n"
//outptr0_s32
"pld [%1, #256] \n"
"vld1.32 {d20-d23}, [%1] \n" //outptr0_s32
"vaddw.s16 q10, q10, d16 \n"
"vaddw.s16 q11, q11, d17 \n"
"vst1.32 {d20-d23}, [%1]! \n"
//next
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2), // %4
"=r"(r3), // %5
"=r"(r4), // %6
"=r"(r5), // %7
"=r"(r6), // %8
"=r"(r7) // %9
: "0"(nn),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2),
"5"(r3),
"6"(r4),
"7"(r5),
"8"(r6),
"9"(r7)
: "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q10", "q11", "q12", "q13"
);
}
for (; remain>0; remain--)
{
//ToDo Neon
int sum0 = (int)*r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3] + *r4 * kernel0[4] + *r5 * kernel0[5] + *r6 * kernel0[6] + *r7 * kernel0[7];
*outptr0 += sum0;
r0++;
r1++;
r2++;
r3++;
r4++;
r5++;
r6++;
r7++;
outptr0++;
}
}
for (; q<inch; q++)
{
int* outptr0 = out0;
const signed char* img0_s8 = bottom_blob.channel(q);
const signed char* r0 = img0_s8;
const signed char* kernel0 = (const signed char*)kernel + p*inch + q;
const signed char k0 = kernel0[0];
int size = outw * outh;
int nn = size >> 3;
int remain = size & 7;
int8x8_t _k0 = vdup_n_s8(k0);
if (nn > 0)
{
asm volatile(
"0: \n"
//load r0
"pld [%2, #64] \n"
"vld1.s8 {d8}, [%2 :64]! \n"
//mla
"vmull.s8 q5, d8, %6 \n"
//outptr0_s32
"pld [%1, #256] \n"
"vld1.32 {d12-d15}, [%1] \n"
"vaddw.s16 q6, q6, d10 \n"
"vaddw.s16 q7, q7, d11 \n"
"vst1.32 {d12-d15}, [%1]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(r0) // %2
: "0"(nn),
"1"(outptr0),
"2"(r0),
"w"(_k0) // %6
: "cc", "memory", "q4", "q5", "q7", "q8", "q9"
);
}
for (; remain>0; remain--)
{
int sum0 = (int)*r0 * k0;
*outptr0 += sum0;
r0++;
outptr0++;
}
}
}
}
static void conv1x1s1_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt)
{
int size = top_blob.h * top_blob.w;
int remain = size & 7;
typedef void (*conv_func_int8)(const Mat&, Mat&, const Mat&, const Option&);
conv_func_int8 conv_func_table[8] =
{
conv1x1s1_neon_s8, //0
conv1x1s1_neon_s8, //1
conv1x1s1_neon_s8, //2
conv1x1s1_neon_s8, //3
conv1x1s1_neon_s8_left4, //4
conv1x1s1_neon_s8, //5
conv1x1s1_neon_s8, //6
conv1x1s1_neon_s8, //7
};
conv_func_int8 conv = conv_func_table[remain];
conv(bottom_blob, top_blob, _kernel, opt);
return;
}
#endif // __aarch64__
static void conv1x1s2_int8_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int tailstep = w - 2*outw + w;
const signed char *kernel = _kernel;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0);
int q = 0;
for (; q+7<inch; q+=8)
{
int* outptr0 = out0;
const signed char *kernel0 = (const signed char *)kernel + p * inch + q;
const signed char *r0 = bottom_blob.channel(q);
const signed char *r1 = bottom_blob.channel(q + 1);
const signed char *r2 = bottom_blob.channel(q + 2);
const signed char *r3 = bottom_blob.channel(q + 3);
const signed char *r4 = bottom_blob.channel(q + 4);
const signed char *r5 = bottom_blob.channel(q + 5);
const signed char *r6 = bottom_blob.channel(q + 6);
const signed char *r7 = bottom_blob.channel(q + 7);
for(int i = 0; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
//ToDo Neon
int sum0 = (int)*r0 * (int)kernel0[0] + (int)*r1 * (int)kernel0[1] +
(int)*r2 * (int)kernel0[2] + (int)*r3 * (int)kernel0[3] +
(int)*r4 * (int)kernel0[4] + (int)*r5 * (int)kernel0[5] +
(int)*r6 * (int)kernel0[6] + (int)*r7 * (int)kernel0[7];
*outptr0 += sum0;
r0 += 2;
r1 += 2;
r2 += 2;
r3 += 2;
r4 += 2;
r5 += 2;
r6 += 2;
r7 += 2;
outptr0++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
r3 += tailstep;
r4 += tailstep;
r5 += tailstep;
r6 += tailstep;
r7 += tailstep;
}
}
for (; q<inch; q++)
{
int* outptr0 = out0;
const signed char *r0 = bottom_blob.channel(q);
const signed char *kernel0 = (const signed char *)kernel + p * inch + q;
for(int i = 0; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
//ToDo Neon
int sum0 = (int)*r0 * (int)kernel0[0];
*outptr0 += sum0;
r0 += 2;
outptr0++;
}
r0 += tailstep;
}
}
}
}
|
GB_unop__identity_uint16_int32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_uint16_int32)
// op(A') function: GB (_unop_tran__identity_uint16_int32)
// C type: uint16_t
// A type: int32_t
// cast: uint16_t cij = (uint16_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int32_t
#define GB_CTYPE \
uint16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
uint16_t z = (uint16_t) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint16_t z = (uint16_t) aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT16 || GxB_NO_INT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_uint16_int32)
(
uint16_t *Cx, // Cx and Ax may be aliased
const int32_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++)
{
int32_t aij = Ax [p] ;
uint16_t z = (uint16_t) aij ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
int32_t aij = Ax [p] ;
uint16_t z = (uint16_t) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_uint16_int32)
(
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
|
cross.h | //
// @author raver119@gmail.com
//
#include <ops/declarable/helpers/helpers.h>
namespace nd4j {
namespace ops {
namespace helpers {
template <typename T>
void FORCEINLINE _cross(NDArray<T> *a, NDArray<T> *b, NDArray<T> *o) {
auto a0 = a->getScalar(0);
auto a1 = a->getScalar(1);
auto a2 = a->getScalar(2);
auto b0 = b->getScalar(0);
auto b1 = b->getScalar(1);
auto b2 = b->getScalar(2);
o->putScalar(0, a1 * b2 - a2 * b1);
o->putScalar(1, a2 * b0 - a0 * b2);
o->putScalar(2, a0 * b1 - a1 * b0);
}
template <typename T>
void FORCEINLINE _crossBatched(NDArray<T> *a, NDArray<T> *b, NDArray<T> *o) {
auto _a = a->reshape(a->ordering(), {-1, 3});
auto _b = b->reshape(b->ordering(), {-1, 3});
auto _o = o->reshape(o->ordering(), {-1, 3});
auto tadsA = NDArrayFactory<T>::allTensorsAlongDimension(_a, {1});
auto tadsB = NDArrayFactory<T>::allTensorsAlongDimension(_b, {1});
auto tadsO = NDArrayFactory<T>::allTensorsAlongDimension(_o, {1});
int tads = tadsA->size();
#pragma omp parallel for simd schedule(static)
for (int e = 0; e < tads; e++) {
auto a_ = tadsA->at(e);
auto b_ = tadsB->at(e);
auto o_ = tadsO->at(e);
helpers::_cross(a_, b_, o_);
}
delete tadsA;
delete tadsB;
delete tadsO;
delete _a;
delete _b;
delete _o;
}
}
}
} |
GB_binop__rdiv_fc32.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_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__rdiv_fc32)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__rdiv_fc32)
// A.*B function (eWiseMult): GB (_AemultB_03__rdiv_fc32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__rdiv_fc32)
// A*D function (colscale): GB (_AxD__rdiv_fc32)
// D*A function (rowscale): GB (_DxB__rdiv_fc32)
// C+=B function (dense accum): GB (_Cdense_accumB__rdiv_fc32)
// C+=b function (dense accum): GB (_Cdense_accumb__rdiv_fc32)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rdiv_fc32)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rdiv_fc32)
// C=scalar+B GB (_bind1st__rdiv_fc32)
// C=scalar+B' GB (_bind1st_tran__rdiv_fc32)
// C=A+scalar GB (_bind2nd__rdiv_fc32)
// C=A'+scalar GB (_bind2nd_tran__rdiv_fc32)
// C type: GxB_FC32_t
// A type: GxB_FC32_t
// B,b type: GxB_FC32_t
// BinaryOp: cij = GB_FC32_div (bij, aij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_BTYPE \
GxB_FC32_t
#define GB_CTYPE \
GxB_FC32_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
GxB_FC32_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
GxB_FC32_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y, i, j) \
z = GB_FC32_div (y, x) ;
// 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_RDIV || GxB_NO_FC32 || GxB_NO_RDIV_FC32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__rdiv_fc32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__rdiv_fc32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__rdiv_fc32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__rdiv_fc32)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type GxB_FC32_t
GxB_FC32_t bwork = (*((GxB_FC32_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__rdiv_fc32)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t *restrict Cx = (GxB_FC32_t *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__rdiv_fc32)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t *restrict Cx = (GxB_FC32_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__rdiv_fc32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_01__rdiv_fc32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_01_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__rdiv_fc32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__rdiv_fc32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_03_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__rdiv_fc32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__rdiv_fc32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ;
GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ;
GxB_FC32_t *Bx = (GxB_FC32_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
GxB_FC32_t bij = Bx [p] ;
Cx [p] = GB_FC32_div (bij, x) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__rdiv_fc32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ;
GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ;
GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
GxB_FC32_t aij = Ax [p] ;
Cx [p] = GB_FC32_div (y, aij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
GxB_FC32_t aij = Ax [pA] ; \
Cx [pC] = GB_FC32_div (aij, x) ; \
}
GrB_Info GB (_bind1st_tran__rdiv_fc32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
GxB_FC32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
GxB_FC32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
GxB_FC32_t aij = Ax [pA] ; \
Cx [pC] = GB_FC32_div (y, aij) ; \
}
GrB_Info GB (_bind2nd_tran__rdiv_fc32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
2.race1.c | // RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s
#include <omp.h>
#define N 20
int main() {
int A[N][N];
#pragma omp simd
for (int i = 1; i < N; i++)
for (int j = 1; j < N; j++)
A[i][j] = A[i - 1][j];
}
// CHECK: Data Race detected
// END
|
util.h | #ifndef CORE_UTIL_H_
#define CORE_UTIL_H_
#include <math.h>
#include <omp.h>
#include <cstdio>
// For GCC
#ifndef __host__
#define __host__
#endif
#ifndef __device__
#define __device__
#endif
// From
// https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#atomic-functions
// With help from https://stackoverflow.com/a/39287554/3427580
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 600
static __inline__ __device__ double atomicAdd(double *address, double val) {
unsigned long long int *address_as_ull = (unsigned long long int *)address;
unsigned long long int old = *address_as_ull, assumed;
if (val == 0.0) { return __longlong_as_double(old); }
do {
assumed = old;
old = atomicCAS(address_as_ull, assumed,
__double_as_longlong(val + __longlong_as_double(assumed)));
} while (assumed != old);
return __longlong_as_double(old);
}
#endif
template <typename T>
__host__ __device__ inline void atomic_add(T *address, T val) {
#ifdef __CUDACC__ // CUDA versions of atomic add
atomicAdd(address, val);
#else // C++ version of atomic add
#pragma omp atomic
*address += val;
#endif
}
template <typename T>
__host__ __device__ inline const T fnegmod(const T lval, const T rval) {
return fmod(fmod(lval, rval) + rval, rval);
}
__host__ __device__ inline int64_t negmod(const int64_t lval,
const int64_t rval) {
return ((lval % rval) + rval) % rval;
}
#endif |
softmax-inl.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2017 by Contributors
* \file softmax-inl.h
* \brief
*/
#ifndef MXNET_OPERATOR_NN_SOFTMAX_INL_H_
#define MXNET_OPERATOR_NN_SOFTMAX_INL_H_
#include <vector>
#include "../mxnet_op.h"
#include "../operator_common.h"
#include "../tensor/broadcast_reduce_op.h"
namespace mxnet {
namespace op {
namespace mxnet_op {
struct softmax_fwd {
template<typename DType>
MSHADOW_XINLINE static DType Map(DType a, DType b) {
return DType(expf(a)/b);
}
};
struct log_softmax_fwd {
template<typename DType>
MSHADOW_XINLINE static DType Map(DType a, DType b) {
return DType(a - logf(b));
}
};
template<typename OP, typename DType, int ndim>
inline void Softmax(Stream<cpu> *s, DType *in, DType *out,
Shape<ndim> shape, int axis, const DType temperature) {
index_t M = shape[axis];
index_t N = shape.Size()/M;
Shape<ndim> stride = calc_stride(shape);
Shape<ndim> sshape = shape;
sshape[axis] = 1;
index_t sa = stride[axis];
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(N); ++i) {
index_t base = unravel_dot(i, sshape, stride);
DType mmax = in[base];
for (index_t j = 1; j < M; ++j) {
if (mmax < in[base + j*sa]) mmax = in[base + j*sa];
}
DType sum = DType(0);
// By default temperature is 1.0, and only in reinforcement training
// users would set it to other values.
// Adding a branch here to save the CPU 'divide-by-1' computation at runtime
if (temperature == 1.0) {
for (index_t j = 0; j < M; ++j) {
sum += std::exp(in[base + j*sa] - mmax);
}
for (index_t j = 0; j < M; ++j) {
out[base + j*sa] = OP::Map(in[base + j*sa] - mmax, sum);
}
} else {
for (index_t j = 0; j < M; ++j) {
sum += std::exp((in[base + j*sa] - mmax)/temperature);
}
for (index_t j = 0; j < M; ++j) {
out[base + j*sa] = OP::Map((in[base + j*sa] - mmax)/temperature, sum);
}
}
}
}
struct softmax_bwd {
template<typename DType>
MSHADOW_XINLINE static DType Map(DType ograd, DType out, DType sum) {
return DType(out * (ograd - sum));
}
};
struct log_softmax_bwd {
template<typename DType>
MSHADOW_XINLINE static DType Map(DType ograd, DType out, DType sum) {
return DType(ograd - expf(out)*sum);
}
};
template<typename OP1, typename OP2, typename DType, int ndim>
inline void SoftmaxGrad(Stream<cpu> *s, DType *out, DType *ograd,
DType *igrad, Shape<ndim> shape, int axis,
const DType temperature) {
index_t M = shape[axis];
index_t N = shape.Size()/M;
Shape<ndim> stride = calc_stride(shape);
Shape<ndim> sshape = shape;
sshape[axis] = 1;
index_t sa = stride[axis];
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(N); ++i) {
index_t base = unravel_dot(i, sshape, stride);
DType sum = DType(0);
for (index_t j = 0; j < M; ++j) {
sum += OP1::Map(ograd[base + j*sa], out[base + j*sa]);
}
// By default temperature is 1.0, and only in reinforcement training
// users would set it to other values.
// Adding a branch here to save the CPU 'divide-by-1' computation at runtime
if (temperature == 1.0) {
for (index_t j = 0; j < M; ++j) {
igrad[base + j*sa] = OP2::Map(ograd[base + j*sa], out[base + j*sa], sum);
}
} else {
for (index_t j = 0; j < M; ++j) {
igrad[base + j*sa] = OP2::Map(ograd[base + j*sa], out[base + j*sa], sum)/temperature;
}
}
}
}
#ifdef __CUDACC__
template<int x_bits, typename OP, typename DType, int ndim>
__global__ void softmax_compute_kernel(DType *in, DType *out, index_t M, int axis,
Shape<ndim> sshape, Shape<ndim> stride,
const double temperature) {
const unsigned x_size = 1 << x_bits;
__shared__ DType smem[x_size];
index_t sa = stride[axis];
index_t base = unravel_dot(blockIdx.x, sshape, stride);
index_t x = threadIdx.x;
red::maximum::SetInitValue(smem[x]);
for (index_t i = x; i < M; i += x_size) {
red::maximum::Reduce(smem[x], in[base + i*sa]);
}
__syncthreads();
cuda::Reduce1D<red::maximum, x_bits>(smem);
__syncthreads();
DType smax = smem[0];
__syncthreads();
red::sum::SetInitValue(smem[x]);
for (index_t i = x; i < M; i += x_size) {
red::sum::Reduce(smem[x], static_cast<DType>(expf((in[base + i*sa] - smax)/
static_cast<DType>(temperature))));
}
__syncthreads();
cuda::Reduce1D<red::sum, x_bits>(smem);
__syncthreads();
DType ssum = smem[0];
__syncthreads();
for (index_t i = x; i < M; i += x_size) {
out[base + i*sa] = OP::Map((in[base + i*sa] - smax)/static_cast<DType>(temperature), ssum);
}
}
template<typename OP, typename DType, int ndim>
inline void Softmax(Stream<gpu> *s, DType *in, DType *out,
Shape<ndim> shape, int axis, const double temperature) {
const int x_bits = 7;
const int x_size = 1 << x_bits;
index_t M = shape[axis];
index_t N = shape.Size()/M;
Shape<ndim> stride = calc_stride(shape);
Shape<ndim> sshape = shape;
sshape[axis] = 1;
softmax_compute_kernel<x_bits, OP, DType, ndim>
<<<N, x_size, 0, mshadow::Stream<gpu>::GetStream(s)>>>(
in, out, M, axis, sshape, stride, temperature);
MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_compute_kernel);
}
template<int x_bits, typename OP1, typename OP2, typename DType, int ndim>
__global__ void softmax_gradient_kernel(DType *out, DType *ograd, DType *igrad,
index_t M, int axis, Shape<ndim> sshape,
Shape<ndim> stride, const double temperature) {
const unsigned x_size = 1 << x_bits;
__shared__ DType smem[x_size];
index_t sa = stride[axis];
index_t base = unravel_dot(blockIdx.x, sshape, stride);
index_t x = threadIdx.x;
red::sum::SetInitValue(smem[x]);
for (index_t i = x; i < M; i += x_size) {
red::sum::Reduce(smem[x], OP1::Map(ograd[base + i*sa], out[base + i*sa]));
}
__syncthreads();
cuda::Reduce1D<red::sum, x_bits>(smem);
__syncthreads();
DType ssum = smem[0];
__syncthreads();
for (index_t i = x; i < M; i += x_size) {
igrad[base + i*sa] = OP2::Map(ograd[base + i*sa], out[base + i*sa], ssum)/
static_cast<DType>(temperature);
}
}
template<typename OP1, typename OP2, typename DType, int ndim>
inline void SoftmaxGrad(Stream<gpu> *s, DType *out, DType *ograd,
DType *igrad, Shape<ndim> shape, int axis,
const double temperature) {
const int x_bits = 7;
const int x_size = 1 << x_bits;
index_t M = shape[axis];
index_t N = shape.Size()/M;
Shape<ndim> stride = calc_stride(shape);
Shape<ndim> sshape = shape;
sshape[axis] = 1;
softmax_gradient_kernel<x_bits, OP1, OP2, DType, ndim>
<<<N, x_size, 0, mshadow::Stream<gpu>::GetStream(s)>>>(
out, ograd, igrad, M, axis, sshape, stride, temperature);
MSHADOW_CUDA_POST_KERNEL_CHECK(softmax_gradient_kernel);
}
#endif
} // namespace mxnet_op
struct SoftmaxParam : public dmlc::Parameter<SoftmaxParam> {
int axis;
dmlc::optional<double> temperature;
DMLC_DECLARE_PARAMETER(SoftmaxParam) {
DMLC_DECLARE_FIELD(axis).set_default(-1)
.describe("The axis along which to compute softmax.");
DMLC_DECLARE_FIELD(temperature).set_default(dmlc::optional<double>())
.describe("Temperature parameter in softmax");
}
};
template<typename xpu, typename OP>
void SoftmaxCompute(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mxnet_op;
if (req[0] == kNullOp) return;
CHECK_NE(req[0], kAddTo);
const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed);
int axis = CheckAxis(param.axis, inputs[0].ndim());
const double temperature = param.temperature.has_value() ?
param.temperature.value() : 1.0;
TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true);
MSHADOW_REAL_TYPE_SWITCH(inputs[0].type_flag_, DType, {
if (shape.ndim() == 2) {
Softmax<OP>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(),
outputs[0].dptr<DType>(), shape.get<2>(), axis,
static_cast<DType>(temperature));
} else {
Softmax<OP>(ctx.get_stream<xpu>(), inputs[0].dptr<DType>(),
outputs[0].dptr<DType>(), shape.get<3>(), axis,
static_cast<DType>(temperature));
}
});
}
template<typename xpu, typename OP1, typename OP2>
void SoftmaxGradCompute(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
using namespace mxnet_op;
if (req[0] == kNullOp) return;
CHECK_NE(req[0], kAddTo);
const SoftmaxParam& param = nnvm::get<SoftmaxParam>(attrs.parsed);
int axis = CheckAxis(param.axis, inputs[0].ndim());
const double temperature = param.temperature.has_value() ?
param.temperature.value() : 1.0;
TShape shape = AxisShapeCompact(inputs[0].shape_, &axis, true);
MSHADOW_REAL_TYPE_SWITCH(inputs[0].type_flag_, DType, {
if (shape.ndim() == 2) {
SoftmaxGrad<OP1, OP2>(ctx.get_stream<xpu>(), inputs[1].dptr<DType>(),
inputs[0].dptr<DType>(), outputs[0].dptr<DType>(),
shape.get<2>(), axis,
static_cast<DType>(temperature));
} else {
SoftmaxGrad<OP1, OP2>(ctx.get_stream<xpu>(), inputs[1].dptr<DType>(),
inputs[0].dptr<DType>(), outputs[0].dptr<DType>(),
shape.get<3>(), axis,
static_cast<DType>(temperature));
}
});
}
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_NN_SOFTMAX_INL_H_
|
Method.h | //
// Created by Александр Кучеров on 22/03/2018.
//
#ifndef METHOD_H
#define METHOD_H
#include <iostream>
#include <utility>
#include <algorithm>
#include <vector>
#include <string>
#include "boost/graph/graph_traits.hpp"
#include "boost/graph/adjacency_list.hpp"
#include "boost/graph/breadth_first_search.hpp"
#include "boost/graph/depth_first_search.hpp"
#include "boost/graph/graphviz.hpp"
#include "boost/algorithm/string.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
extern std::string INPUT_FILE_PATH("");//("input/graph_input.json");
#include "../../Models/Graph.h"
using namespace boost;
typedef std::pair<int, int> Edge;
typedef adjacency_list<vecS, vecS, undirectedS,
property<edge_color_t, default_color_type> > graph_t;
typedef graph_traits<graph_t>::vertex_descriptor vertex_t;
class custom_bfs_visitor : public default_bfs_visitor
{
public:
template < typename Vertex, typename Graph >
void discover_vertex(Vertex v, const Graph & g) const
{
LOG_DEBUG << "Visited vertex - " << v;
}
};
class custom_dfs_visitor : public default_dfs_visitor
{
public:
void discover_vertex(vertex_t v, const graph_t& g) const
{
LOG_DEBUG << "Visited vertex - " << v;
}
};
// Graphviz property writer (vertex)
class custom_vertex_writer {
public:
custom_vertex_writer( graph_t& g , Graph& gModel) : currentGraph( g ), currentGraphModel(gModel) {}
template <class VertexOrEdge>
void operator()(std::ostream& out, const VertexOrEdge& e) const {
float coverage = this->currentGraphModel.getNodes().at(e).getCoverage();
float posX = this->currentGraphModel.getNodes().at(e).getCoordinates().at(0);
float posY = this->currentGraphModel.getNodes().at(e).getCoordinates().at(1);
if (e != 0) {
out << "[shape=circle,width=" << coverage
<< ",style=filled,fillcolor=\"#000000\",pos=\""
<< posX << "," << posY << "!\", pin=true]";
} else {
out << "[shape=circle,width=" << coverage
<< ",style=invis,pos=\""
<< posX << "," << posY << "!\", pin=true]";
}
}
private:
graph_t& currentGraph;
Graph& currentGraphModel;
};
// Graphviz property writer (edge)
class custom_edge_writer {
public:
custom_edge_writer( graph_t& g) : currentGraph( g ) {}
template <class VertexOrEdge>
void operator()(std::ostream& out, const VertexOrEdge& e) const {
out << "[style=invis]";
}
private:
graph_t& currentGraph;
};
class Method {
public:
Method(unsigned int accuracy, unsigned int oImgSizeX, unsigned int oImgSizeY, unsigned int oImgScale, string oImgFormat)
: _accuracy(accuracy),
_oImgSizeX(oImgSizeX),
_oImgSizeY(oImgSizeY),
_oImgCoordScale(oImgScale),
_oImgFormat(oImgFormat),
_graphModel(Graph::initWithFile(INPUT_FILE_PATH.c_str())){
LOG_DEBUG << "Method - Initialized";
this->init();
}
void init(){
this->graphInit(this->getGraphModel());
LOG_DEBUG << "Boost BFS - START";
this->boost_bfs();
LOG_DEBUG << "Boost BFS - END";
LOG_DEBUG << "Boost DFS - START";
this->boost_dfs();
LOG_DEBUG << "Boost DFS - END";
this->fileItr = 0;
this->setMaxCoverageInit();
LOG_INFO << "Method - Initialized";
}
unsigned int getAccuracy(){
return this->_accuracy;
}
void setAccuracy(unsigned int accuracy){
this->_accuracy = accuracy;
}
std::vector<Edge> getEdgeVector(){
return this->_edgeVector;
}
void setEdgeVector(std::vector<Edge> edgeVector){
this->_edgeVector = edgeVector;
}
graph_t getUndirectedGraph(){
return this->_graph_t;
}
void setUndirectedGraph(graph_t undGraph){
this->_graph_t = undGraph;
}
Graph getGraphModel(){
return this->_graphModel;
}
void setGraphModel(Graph graphModel){
this->_graphModel = graphModel;
}
unsigned long getMaxCoverage(){
return this->_maxCoverage;
}
void setMaxCoverage(unsigned long maxCoverage){
this->_maxCoverage = maxCoverage;
}
unsigned long getMaxCoverageMatrix(){
return this->_maxCoverageMatrix;
}
void setMaxCoverageMatrix(unsigned long maxCoverageMatrix){
this->_maxCoverageMatrix = maxCoverageMatrix;
}
protected:
vector<float> getVisitedNodes() {
return this->_visited;
}
void setVisitedNodes(vector<float> visited) {
this->_visited = visited;
}
void graphInit(Graph graphModel) {
LOG_DEBUG << "Adding edges to graph - START";
std::vector<Edge> edgeVec;
for ( Node node : graphModel.getNodes()) {
for (unsigned int neighborVertex: node.getRelations()){
edgeVec.push_back(Edge(node.getId(), neighborVertex));
}
}
this->setEdgeVector(edgeVec);
LOG_DEBUG << "Adding edges to graph - END";
LOG_DEBUG << "Initializing graph with edges - START";
// GraphInit
graph_t g(edgeVec.begin(), edgeVec.end(), graphModel.getNodes().size());
graph_traits<graph_t>::vertex_iterator vi, vi_end, next;
tie(vi, vi_end) = vertices(g);
for (next = vi; vi != vi_end; vi = next) {
++next;
}
this->setUndirectedGraph(g);
LOG_DEBUG << "Edges Num - " << num_edges(g);
LOG_DEBUG << "Initializing graph with edges - END";
// List all edges
typedef graph_traits<graph_t>::edge_iterator edge_iterator;
std::pair<edge_iterator, edge_iterator> ei = edges(g);
for(edge_iterator edge_iter = ei.first; edge_iter != ei.second; ++edge_iter) {
LOG_DEBUG << "Edge (" << source(*edge_iter, g) << ", " << target(*edge_iter, g) << ")";
}
}
void setMaxCoverageInit(){
string maxCoveragePath = "_max_coverage";
this->graphToImg(maxCoveragePath, this->_graph_t);
this->setMaxCoverage(this->maxCoverageReadImg(maxCoveragePath)); // Count of black pixels for graph with max coverage
LOG_INFO << "Ratio of black pixels against all for graph with max coverage (image) - "
<< this->maxCoverageReadImgRatioAgainstAll(maxCoveragePath);
vector<float> visited;
vector<float> prVector = this->getGraphProbabilities();
visited = this->updateGraphConnectivity(prVector);
this->setMaxCoverageMatrix(this->countSquareMatrixMaxCoverage(visited)); // Count of black pixels for graph with max coverage
LOG_DEBUG << "Ratio of black pixels against all for graph with max coverage (matrix) - "
<< this->countSquareMatrixMaxCoverageAgainstAll(visited);
}
vector<float> getGraphProbabilities() {
Graph g = this->_graphModel;
vector<float> prVector;
for (Node node : g.getNodes()) {
prVector.push_back(node.getReliablility());
}
return prVector;
}
// Return set of visited vertices in connected graph
void recursiveVertexVisit(vector<float> nodeRel) {
unsigned int v = 0;
for (unsigned int i = 0; i < nodeRel.size(); i++) {
if (nodeRel.at(i) == 1) {
for (unsigned int neighborVertexId: this->_graphModel.getNodes().at(i).getRelations()) {
float visitedV = this->getVisitedNodes().at(neighborVertexId);
if ((nodeRel.at(neighborVertexId) > 0) && (visitedV != 1)) {
v = neighborVertexId;
break;
}
}
}
if (v > 0) break;
}
if (v > 0) {
vector<float> visited = this->getVisitedNodes();
visited.at(v) = 1;
this->setVisitedNodes(visited);
this->recursiveVertexVisit(nodeRel);
}
}
vector<float> updateGraphConnectivity(vector<float> nodeRel) {
// Init & fill vector with non-visited vertices
vector<float> visited;
for (unsigned long i = 0; i < nodeRel.size(); i++) {
visited.push_back(0);
}
visited.at(0) = 1; // Stock is always connected
this->setVisitedNodes(visited);
this->recursiveVertexVisit(nodeRel);
visited = this->getVisitedNodes();
for (unsigned long i = 1; i < visited.size(); i++) {
if (visited.at(i) != 1) {
nodeRel.at(i) = 0;
}
}
return nodeRel;
}
void graphToImg(string filename,graph_t g){
//write_graphviz (std::cout, g);
std::ofstream dmp;
string imgPath = "output/graph" + filename + "." + this->_oImgFormat;
string dotPath = "output/graph" + filename + ".dot";
dmp.open(dotPath);
write_graphviz(dmp, g, custom_vertex_writer(g, this->_graphModel), custom_edge_writer(g));
string outFormat = "neato";
string gScale = "-n -s" + std::to_string(this->_oImgCoordScale);
string gFormat = "-T" + this->_oImgFormat;
string gSize = "-Gsize="
+ std::to_string(this->_oImgSizeX) + ","
+ std::to_string(this->_oImgSizeY) + "!";
string gViewport = "-Gviewport="
+ std::to_string(this->_oImgSizeX) + ","
+ std::to_string(this->_oImgSizeY) + ","
+ std::to_string(this->_oImgCoordScale) + "!";
string gDpi = "-Gdpi=" + std::to_string(this->_accuracy);
string cmd = outFormat +
" " + gScale +
" " + dotPath +
" " + gFormat +
" " + gSize +
" " + gViewport +
" " + gDpi +
" -o " + imgPath;
const char * dotCmd = cmd.c_str();
std::system(dotCmd);
}
/*
* Returns ratio of black pixels against amount of
* black pixels for graph whose each node probability is 1
* */
float readImg(){
string imgPath = "output/graph" + std::to_string(this->fileItr) + "." + this->_oImgFormat;
cv::Mat image;
image = cv::imread(imgPath, CV_LOAD_IMAGE_COLOR);
if(! image.data) LOG_ERROR << "Could not open or find the image - " << imgPath;
// Display img
/*cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
cv::imshow( "Display window", image );
cv::waitKey(0);*/
// Prepare Image
cv::cvtColor(image, image, CV_BGR2GRAY);
cv::threshold(image, image, 254, 255, cv::THRESH_BINARY );
// Count Pixels
int count_all = image.cols * image.rows;
int count_white = cv::countNonZero(image);
int count_black = count_all - count_white;
LOG_DEBUG << "All pixels - " << count_all << "; White pixels - " << count_white
<< "; Black pixels - " << count_black;
this->fileItr++;
float square = count_black;
square /= this->getMaxCoverage();
//square /= count_all;
LOG_DEBUG << "Square - " << square;
return square;
}
/*
* FOR PARALLEL METHODS
* Returns ratio of black pixels against amount of
* black pixels for graph whose each node probability is 1
* */
float readImgParallel(unsigned long fileItr){
string imgPath = "output/graph" + std::to_string(fileItr) + "." + this->_oImgFormat;
cv::Mat image;
image = cv::imread(imgPath, CV_LOAD_IMAGE_COLOR);
if(! image.data) LOG_ERROR << "Could not open or find the image - " << imgPath;
// Display img
/*cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE );
cv::imshow( "Display window", image );
cv::waitKey(0);*/
// Prepare Image
cv::cvtColor(image, image, CV_BGR2GRAY);
cv::threshold(image, image, 254, 255, cv::THRESH_BINARY );
// Count Pixels
int count_all = image.cols * image.rows;
int count_white = cv::countNonZero(image);
int count_black = count_all - count_white;
LOG_DEBUG << "All pixels - " << count_all << "; White pixels - " << count_white
<< "; Black pixels - " << count_black;
float square = count_black;
square /= this->getMaxCoverage();;
LOG_DEBUG << "Square - " << square;
return square;
}
/*
* Returns count of black pixels for all graph, where p of every node is 1
* */
unsigned long maxCoverageReadImg(string filename){
string imgPath = "output/graph" + filename + "." + this->_oImgFormat;
cv::Mat image;
image = cv::imread(imgPath, CV_LOAD_IMAGE_COLOR);
if(! image.data) LOG_ERROR << "Could not open or find the image - " << imgPath;
// Prepare Image
cv::cvtColor(image, image, CV_BGR2GRAY);
cv::threshold(image, image, 254, 255, cv::THRESH_BINARY );
// Count Pixels
int count_all = image.cols * image.rows;
int count_white = cv::countNonZero(image);
int count_black = count_all - count_white;
LOG_DEBUG << "All pixels - " << count_all << "; White pixels - " << count_white
<< "; Black pixels - " << count_black;
return count_black;
}
/*
* Returns ratio black/all pixel
* */
float maxCoverageReadImgRatioAgainstAll(string filename){
string imgPath = "output/graph" + filename + "." + this->_oImgFormat;
cv::Mat image;
image = cv::imread(imgPath, CV_LOAD_IMAGE_COLOR);
if(! image.data) LOG_ERROR << "Could not open or find the image - " << imgPath;
// Prepare Image
cv::cvtColor(image, image, CV_BGR2GRAY);
cv::threshold(image, image, 254, 255, cv::THRESH_BINARY );
// Count Pixels
int count_all = image.cols * image.rows;
int count_white = cv::countNonZero(image);
int count_black = count_all - count_white;
LOG_DEBUG << "All pixels - " << count_all << "; White pixels - " << count_white
<< "; Black pixels - " << count_black;
float square = count_black;
square /= count_all;
LOG_DEBUG << "Square (against all) - " << square;
return square;
}
float countSquareTest(vector<float> visited){
int sum_square = 0;
for (int i=1; i < visited.size(); i++ ){
if (visited.at(i) == 1) sum_square++;
}
return sum_square;
}
float countSquareMatrixMaxCoverage(vector<float> visited){
bool** matrix = new bool*[this->_oImgSizeX];
for(int i = 0; i < this->_oImgSizeX; i++)
matrix[i] = new bool[this->_oImgSizeY];
int count_all = this->_oImgSizeX * this->_oImgSizeY;
int count_black = 0;
// Initialize matrix
for (unsigned int i=0; i < this->_oImgSizeX; i++) {
for (unsigned int j=0; j < this->_oImgSizeY; j++) {
matrix[i][j] = false;
}
}
// Draw node circles
for (int i=1; i < visited.size(); i++ ){
int x = this->_graphModel.getNodes().at(i).getCoordinates().at(0);
int y = this->_graphModel.getNodes().at(i).getCoordinates().at(1);
int radius = this->_graphModel.getNodes().at(i).getCoverage() * this->getAccuracy();
this->drawCircle(matrix, x, y, radius);
}
// Count covered area
for (unsigned int i=0; i < this->_oImgSizeX; i++) {
for (unsigned int j=0; j < this->_oImgSizeY; j++) {
if (matrix[i][j]) {
count_black++;
}
}
}
// Dealloc memory
delete[] matrix;
return count_black;
}
float countSquareMatrixMaxCoverageAgainstAll(vector<float> visited){
bool** matrix = new bool*[this->_oImgSizeX];
for(int i = 0; i < this->_oImgSizeX; i++)
matrix[i] = new bool[this->_oImgSizeY];
int count_all = this->_oImgSizeX * this->_oImgSizeY;
int count_black = 0;
// Initialize matrix
for (unsigned int i=0; i < this->_oImgSizeX; i++) {
for (unsigned int j=0; j < this->_oImgSizeY; j++) {
matrix[i][j] = false;
}
}
// Draw node circles
for (int i=1; i < visited.size(); i++ ){
int x = this->_graphModel.getNodes().at(i).getCoordinates().at(0);
int y = this->_graphModel.getNodes().at(i).getCoordinates().at(1);
int radius = this->_graphModel.getNodes().at(i).getCoverage() * this->getAccuracy();
this->drawCircle(matrix, x, y, radius);
}
// Count covered area
for (unsigned int i=0; i < this->_oImgSizeX; i++) {
for (unsigned int j=0; j < this->_oImgSizeY; j++) {
if (matrix[i][j]) {
count_black++;
}
}
}
// Dealloc memory
delete[] matrix;
float square = count_black;
square /= count_all;
return square;
}
float countSquareMatrix(vector<float> visited){
bool** matrix = new bool*[this->_oImgSizeX];
for(int i = 0; i < this->_oImgSizeX; i++)
matrix[i] = new bool[this->_oImgSizeY];
int count_black = 0;
// Initialize matrix
for (unsigned int i=0; i < this->_oImgSizeX; i++) {
for (unsigned int j=0; j < this->_oImgSizeY; j++) {
matrix[i][j] = false;
}
}
// Draw node circles
for (int i=1; i < visited.size(); i++ ){
int x = this->_graphModel.getNodes().at(i).getCoordinates().at(0);
int y = this->_graphModel.getNodes().at(i).getCoordinates().at(1);
int radius = this->_graphModel.getNodes().at(i).getCoverage() * this->getAccuracy();
this->drawCircle(matrix, x, y, radius);
}
// Count covered area
for (unsigned int i=0; i < this->_oImgSizeX; i++) {
for (unsigned int j=0; j < this->_oImgSizeY; j++) {
if (matrix[i][j]) {
count_black++;
}
}
}
// Debug Code
/*for(int i = 0; i < this->_oImgSizeX; i++) {
for (int j = 0; j < this->_oImgSizeY; j++)
if (matrix[i][j]) { std::cout << "*"; } else std::cout << " ";
std::cout << "\n";
}
std::cout << "\n --------------- \n";*/
// Dealloc memory
delete[] matrix;
float square = count_black;
square /= this->getMaxCoverageMatrix();
return square;
}
// Help function countSquareMatrix method
void drawCircle(bool **matrix, int x0, int y0, int radius)
{
int x = radius;
int y = 0;
int xChange = 1 - (radius << 1);
int yChange = 0;
int radiusError = 0;
while (x >= y)
{
for (int i = x0 - x; i <= x0 + x; i++)
{
if ((i >= 0) && (i < this->_oImgSizeX)) {
int yNew = y0 + y;
if ((yNew >= 0) && (yNew < this->_oImgSizeY)) matrix[i][yNew] = true;
yNew = y0 - y;
if ((yNew >= 0) && (yNew < this->_oImgSizeY)) matrix[i][yNew] = true;
}
}
for (int i = x0 - y; i <= x0 + y; i++)
{
if ((i >= 0) && (i < this->_oImgSizeX)){
int yNew = y0 + x;
if ((yNew >= 0) && (yNew < this->_oImgSizeY)) matrix[i][yNew] = true;
yNew = y0 - x;
if ((yNew >= 0) && (yNew < this->_oImgSizeY)) matrix[i][yNew] = true;
}
}
y++;
radiusError += yChange;
yChange += 2;
if (((radiusError << 1) + xChange) > 0)
{
x--;
radiusError += xChange;
xChange += 2;
}
}
}
// Simple draw circle, less accurate not suggested for usage
void drawCircleSimple(bool **matrix, int x0, int y0, int r){
for(int i = x0 - r; i <= x0 + r; i++)
{
for(int j = y0 - r; j <= y0 + r; j++)
{
if(((i-x0)*(i-x0) + (j-y0)*(j-y0)) <= r*r)
{
if (((i >= 0) && (i < this->_oImgSizeX)) && ((j >= 0) && (j < this->_oImgSizeY)))
matrix[i][j] = true;
}
}
}
}
graph_t genNewGraph(vector<float> visited){
Graph graphModel = this->getGraphModel();
std::vector<Edge> edgeVec;
unsigned long verticesNum = 0;
LOG_DEBUG << "Adding edges to graph - END";
for (unsigned long i=0; i < visited.size(); i++ ){
if (visited.at(i) == 1) {
for (unsigned int neighborVertex: graphModel.getNodes().at(i).getRelations()){
for (unsigned long j=0; j < visited.size(); j++ ){
if ((j == neighborVertex) && (visited.at(j) == 1)){
edgeVec.push_back(Edge(i, neighborVertex));
}
}
}
verticesNum++;
}
}
LOG_DEBUG << "Adding edges to graph - END";
LOG_DEBUG << "Initializing graph with edges - START";
// GraphInit
graph_t g(edgeVec.begin(), edgeVec.end(), verticesNum);
LOG_DEBUG << "Initializing graph with edges - END";
return g;
}
float countSquare(vector<float> visited){
graph_t g = genNewGraph(visited);
this->graphToImg(std::to_string(this->fileItr),g);
return this->readImg();
}
//FOR PARALLEL METHODS
float countSquareParallel(vector<float> visited, unsigned long fileItr){
graph_t g = genNewGraph(visited);
#pragma omp critical
{
this->graphToImg(std::to_string(fileItr), g);
}
return this->readImgParallel(fileItr);
}
void boost_bfs(){
graph_t g = this->getUndirectedGraph();
custom_bfs_visitor vis;
breadth_first_search(g, vertex(this->getGraphModel().getStockId(), g), visitor(vis));
}
void boost_dfs() {
graph_t g = this->getUndirectedGraph();
auto indexmap = boost::get(boost::vertex_index, g);
auto colormap = boost::make_vector_property_map<boost::default_color_type>(indexmap);
custom_dfs_visitor vis;
depth_first_search(g, visitor(vis));
}
// Output image properties
unsigned int _accuracy;
unsigned int _oImgSizeX;
unsigned int _oImgSizeY;
unsigned int _oImgCoordScale;
string _oImgFormat;
// Boost graph entities
std::vector<Edge> _edgeVector;
graph_t _graph_t;
unsigned long _maxCoverage;
unsigned long _maxCoverageMatrix;
// Graph inited model
Graph _graphModel;
// Img
unsigned long fileItr;
// Visited nodes
vector<float> _visited;
};
#endif |
8495.c | /* POLYBENCH/GPU-OPENMP
*
* This file is a part of the Polybench/GPU-OpenMP suite
*
* Contact:
* William Killian <killian@udel.edu>
*
* Copyright 2013, The University of Delaware
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 4096x4096. */
#include "convolution-2d.h"
/* Array initialization. */
static
void init_array (int ni, int nj,
DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj))
{
// printf("Initializing Array\n");
int i, j;
for (i = 0; i < ni; i++)
for (j = 0; j < nj; j++)
{
A[i][j] = ((DATA_TYPE) (i + j) / nj);
}
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static
void print_array(int ni, int nj,
DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj))
{
int i, j;
for (i = 0; i < ni; i++)
for (j = 0; j < nj; j++) {
fprintf(stderr, DATA_PRINTF_MODIFIER, B[i][j]);
if ((i * NJ + j) % 20 == 0) fprintf(stderr, "\n");
}
fprintf(stderr, "\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static
void kernel_conv2d(int ni,
int nj,
DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj),
DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj))
{
int i, j;
#pragma scop
#pragma omp target teams distribute dist_schedule(static, 16) private(j)
for (i = 1; i < _PB_NI - 1; ++i)
{
for (j = 1; j < _PB_NJ - 1; ++j)
{
B[i][j] = 0.2 * A[i-1][j-1] + 0.5 * A[i-1][j] + -0.8 * A[i-1][j+1]
+ -0.3 * A[ i ][j-1] + 0.6 * A[ i ][j] + -0.9 * A[ i ][j+1]
+ 0.4 * A[i+1][j-1] + 0.7 * A[i+1][j] + 0.1 * A[i+1][j+1];
}
}
#pragma endscop
// printf("Kernal computation complete !!\n");
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int ni = NI;
int nj = NJ;
/* Variable declaration/allocation. */
POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NJ, ni, nj);
POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NI, NJ, ni, nj);
/* Initialize array(s). */
init_array (ni, nj, POLYBENCH_ARRAY(A));
/* Start timer. */
//polybench_start_instruments;
polybench_timer_start();
/* Run kernel. */
kernel_conv2d (ni, nj, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B));
/* Stop and print timer. */
polybench_timer_stop();
polybench_timer_print();
//polybench_stop_instruments;
//polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(ni, nj, POLYBENCH_ARRAY(B)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(A);
POLYBENCH_FREE_ARRAY(B);
return 0;
}
|
dynamic_module.c | // RUN: %libomptarget-compile-aarch64-unknown-linux-gnu -DSHARED -shared -o %t.so && %libomptarget-compile-aarch64-unknown-linux-gnu %t.so && %libomptarget-run-aarch64-unknown-linux-gnu 2>&1 | %fcheck-aarch64-unknown-linux-gnu
// RUN: %libomptarget-compile-powerpc64-ibm-linux-gnu -DSHARED -shared -o %t.so && %libomptarget-compile-powerpc64-ibm-linux-gnu %t.so && %libomptarget-run-powerpc64-ibm-linux-gnu 2>&1 | %fcheck-powerpc64-ibm-linux-gnu
// RUN: %libomptarget-compile-powerpc64le-ibm-linux-gnu -DSHARED -shared -o %t.so && %libomptarget-compile-powerpc64le-ibm-linux-gnu %t.so && %libomptarget-run-powerpc64le-ibm-linux-gnu 2>&1 | %fcheck-powerpc64le-ibm-linux-gnu
// RUN: %libomptarget-compile-x86_64-pc-linux-gnu -DSHARED -shared -o %t.so && %libomptarget-compile-x86_64-pc-linux-gnu %t.so && %libomptarget-run-x86_64-pc-linux-gnu 2>&1 | %fcheck-x86_64-pc-linux-gnu
#ifdef SHARED
void foo() {}
#else
#include <stdio.h>
int main() {
#pragma omp target
;
// CHECK: DONE.
printf("%s\n", "DONE.");
return 0;
}
#endif
|
residual_based_implicit_time_scheme.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
#if !defined(KRATOS_RESIDUAL_BASED_IMPLICIT_TIME_SCHEME )
#define KRATOS_RESIDUAL_BASED_IMPLICIT_TIME_SCHEME
/* System includes */
/* External includes */
/* Project includes */
#include "solving_strategies/schemes/scheme.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @class ResidualBasedImplicitTimeScheme
* @ingroup KratosCore
* @brief This is the base class for the implicit time schemes
* @details Other implicit schemes should derive from this one. With the use of this base scheme it is possible to reduce code duplication
* @tparam TSparseSpace The sparse space considered
* @tparam TDenseSpace The dense space considered
* @see Scheme
* @author Vicente Mataix Ferrandiz
*/
template<class TSparseSpace, class TDenseSpace >
class ResidualBasedImplicitTimeScheme
: public Scheme<TSparseSpace,TDenseSpace>
{
public:
///@name Type Definitions
///@{
/// Pointer definition of ResidualBasedImplicitTimeScheme
KRATOS_CLASS_POINTER_DEFINITION( ResidualBasedImplicitTimeScheme );
/// Base class definition
typedef Scheme<TSparseSpace,TDenseSpace> BaseType;
/// DoF array type definition
typedef typename BaseType::DofsArrayType DofsArrayType;
/// DoF vector type definition
typedef typename Element::DofsVectorType DofsVectorType;
/// Data type definition
typedef typename BaseType::TDataType TDataType;
/// Matrix type definition
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
/// Vector type definition
typedef typename BaseType::TSystemVectorType TSystemVectorType;
/// Local system matrix type definition
typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType;
/// Local system vector type definition
typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType;
/// Nodes containers definition
typedef ModelPart::NodesContainerType NodesArrayType;
/// Elements containers definition
typedef ModelPart::ElementsContainerType ElementsArrayType;
/// Conditions containers definition
typedef ModelPart::ConditionsContainerType ConditionsArrayType;
/// Index type definition
typedef std::size_t IndexType;
///@}
///@name Life Cycle
///@{
/**
* Constructor.
* The implicit method method
*/
explicit ResidualBasedImplicitTimeScheme()
:BaseType()
{
// Allocate auxiliary memory
const std::size_t num_threads = OpenMPUtils::GetNumThreads();
mMatrix.M.resize(num_threads);
mMatrix.D.resize(num_threads);
}
/** Copy Constructor.
*/
explicit ResidualBasedImplicitTimeScheme(ResidualBasedImplicitTimeScheme& rOther)
:BaseType(rOther)
,mMatrix(rOther.mMatrix)
{
}
/**
* Clone
*/
typename BaseType::Pointer Clone() override
{
return Kratos::make_shared<ResidualBasedImplicitTimeScheme>(*this);
}
/** Destructor.
*/
~ResidualBasedImplicitTimeScheme
() override {}
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* @brief It initializes a non-linear iteration (for the element)
* @param rModelPart The model part of the problem to solve
* @param A LHS matrix
* @param Dx Incremental update of primary variables
* @param b RHS Vector
*/
void InitializeNonLinIteration(
ModelPart& rModelPart,
TSystemMatrixType& A,
TSystemVectorType& Dx,
TSystemVectorType& b
) override
{
KRATOS_TRY;
ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
// Definition of the first element iterator
const auto it_elem_begin = rModelPart.ElementsBegin();
#pragma omp parallel for
for(int i=0; i<static_cast<int>(rModelPart.Elements().size()); ++i) {
auto it_elem = it_elem_begin + i;
it_elem->InitializeNonLinearIteration(r_current_process_info);
}
// Definition of the first condition iterator
const auto it_cond_begin = rModelPart.ConditionsBegin();
#pragma omp parallel for
for(int i=0; i<static_cast<int>(rModelPart.Conditions().size()); ++i) {
auto it_cond = it_cond_begin + i;
it_cond->InitializeNonLinearIteration(r_current_process_info);
}
// Definition of the first constraint iterator
const auto it_const_begin = rModelPart.MasterSlaveConstraintsBegin();
#pragma omp parallel for
for(int i=0; i<static_cast<int>(rModelPart.MasterSlaveConstraints().size()); ++i) {
auto it_const = it_const_begin + i;
it_const->InitializeNonLinearIteration(r_current_process_info);
}
KRATOS_CATCH( "" );
}
/**
* @brief It initializes a non-linear iteration (for an individual condition)
* @param pCurrentCondition The condition to compute
* @param rCurrentProcessInfo The current process info instance
*/
void InitializeNonLinearIteration(
Condition::Pointer pCurrentCondition,
ProcessInfo& rCurrentProcessInfo
) override
{
pCurrentCondition->InitializeNonLinearIteration(rCurrentProcessInfo);
}
/**
* @brief It initializes a non-linear iteration (for an individual element)
* @param pCurrentElement The element to compute
* @param rCurrentProcessInfo The current process info instance
*/
void InitializeNonLinearIteration(
Element::Pointer pCurrentElement,
ProcessInfo& rCurrentProcessInfo
) override
{
pCurrentElement->InitializeNonLinearIteration(rCurrentProcessInfo);
}
/**
* @brief This function is designed to be called in the builder and solver to introduce the selected time integration scheme.
* @details It "asks" the matrix needed to the element and performs the operations needed to introduce the selected time integration scheme. This function calculates at the same time the contribution to the LHS and to the RHS of the system
* @param pCurrentElement The element to compute
* @param LHS_Contribution The LHS matrix contribution
* @param RHS_Contribution The RHS vector contribution
* @param EquationId The ID's of the element degrees of freedom
* @param rCurrentProcessInfo The current process info instance
*/
void CalculateSystemContributions(
Element::Pointer pCurrentElement,
LocalSystemMatrixType& LHS_Contribution,
LocalSystemVectorType& RHS_Contribution,
Element::EquationIdVectorType& EquationId,
ProcessInfo& rCurrentProcessInfo
) override
{
KRATOS_TRY;
const IndexType this_thread = OpenMPUtils::ThisThread();
//pCurrentElement->InitializeNonLinearIteration(rCurrentProcessInfo);
pCurrentElement->CalculateLocalSystem(LHS_Contribution,RHS_Contribution,rCurrentProcessInfo);
pCurrentElement->EquationIdVector(EquationId,rCurrentProcessInfo);
pCurrentElement->CalculateMassMatrix(mMatrix.M[this_thread],rCurrentProcessInfo);
pCurrentElement->CalculateDampingMatrix(mMatrix.D[this_thread],rCurrentProcessInfo);
AddDynamicsToLHS(LHS_Contribution, mMatrix.D[this_thread], mMatrix.M[this_thread], rCurrentProcessInfo);
AddDynamicsToRHS(pCurrentElement, RHS_Contribution, mMatrix.D[this_thread], mMatrix.M[this_thread], rCurrentProcessInfo);
KRATOS_CATCH("ResidualBasedImplicitTimeScheme.CalculateSystemContributions");
}
/**
* @brief This function is designed to calculate just the RHS contribution
* @param pCurrentElement The element to compute
* @param rRHSContribution The RHS vector contribution
* @param rEquationId The ID's of the element degrees of freedom
* @param rCurrentProcessInfo The current process info instance
*/
void Calculate_RHS_Contribution(
Element::Pointer pCurrentElement,
LocalSystemVectorType& rRHSContribution,
Element::EquationIdVectorType& rEquationId,
ProcessInfo& rCurrentProcessInfo
) override
{
KRATOS_TRY;
const IndexType this_thread = OpenMPUtils::ThisThread();
// Initializing the non linear iteration for the current element
// pCurrentElement->InitializeNonLinearIteration(rCurrentProcessInfo);
// Basic operations for the element considered
pCurrentElement->CalculateRightHandSide(rRHSContribution,rCurrentProcessInfo);
pCurrentElement->CalculateMassMatrix(mMatrix.M[this_thread], rCurrentProcessInfo);
pCurrentElement->CalculateDampingMatrix(mMatrix.D[this_thread],rCurrentProcessInfo);
pCurrentElement->EquationIdVector(rEquationId,rCurrentProcessInfo);
AddDynamicsToRHS (pCurrentElement, rRHSContribution, mMatrix.D[this_thread], mMatrix.M[this_thread], rCurrentProcessInfo);
KRATOS_CATCH("ResidualBasedImplicitTimeScheme.Calculate_RHS_Contribution");
}
/**
* @brief Functions totally analogous to the precedent but applied to the "condition" objects
* @param pCurrentCondition The condition to compute
* @param rLHSContribution The LHS matrix contribution
* @param rRHSContribution The RHS vector contribution
* @param rEquationId The ID's of the element degrees of freedom
* @param rCurrentProcessInfo The current process info instance
*/
void Condition_CalculateSystemContributions(
Condition::Pointer pCurrentCondition,
LocalSystemMatrixType& rLHSContribution,
LocalSystemVectorType& rRHSContribution,
Element::EquationIdVectorType& rEquationId,
ProcessInfo& rCurrentProcessInfo
) override
{
KRATOS_TRY;
const IndexType this_thread = OpenMPUtils::ThisThread();
// Initializing the non linear iteration for the current condition
//pCurrentCondition->InitializeNonLinearIteration(rCurrentProcessInfo);
// Basic operations for the condition considered
pCurrentCondition->CalculateLocalSystem(rLHSContribution,rRHSContribution, rCurrentProcessInfo);
pCurrentCondition->EquationIdVector(rEquationId, rCurrentProcessInfo);
pCurrentCondition->CalculateMassMatrix(mMatrix.M[this_thread], rCurrentProcessInfo);
pCurrentCondition->CalculateDampingMatrix(mMatrix.D[this_thread], rCurrentProcessInfo);
AddDynamicsToLHS(rLHSContribution, mMatrix.D[this_thread], mMatrix.M[this_thread], rCurrentProcessInfo);
AddDynamicsToRHS(pCurrentCondition, rRHSContribution, mMatrix.D[this_thread], mMatrix.M[this_thread], rCurrentProcessInfo);
// AssembleTimeSpaceLHS_Condition(pCurrentCondition, LHS_Contribution,DampMatrix, MassMatrix,rCurrentProcessInfo);
KRATOS_CATCH("ResidualBasedImplicitTimeScheme.Condition_CalculateSystemContributions");
}
/**
* @brief Functions that calculates the RHS of a "condition" object
* @param pCurrentCondition The condition to compute
* @param rRHSContribution The RHS vector contribution
* @param rEquationId The ID's of the condition degrees of freedom
* @param rCurrentProcessInfo The current process info instance
*/
void Condition_Calculate_RHS_Contribution(
Condition::Pointer pCurrentCondition,
LocalSystemVectorType& rRHSContribution,
Element::EquationIdVectorType& rEquationId,
ProcessInfo& rCurrentProcessInfo
) override
{
KRATOS_TRY;
const IndexType this_thread = OpenMPUtils::ThisThread();
// Initializing the non linear iteration for the current condition
//pCurrentCondition->InitializeNonLinearIteration(rCurrentProcessInfo);
// Basic operations for the condition considered
pCurrentCondition->CalculateRightHandSide(rRHSContribution, rCurrentProcessInfo);
pCurrentCondition->EquationIdVector(rEquationId, rCurrentProcessInfo);
pCurrentCondition->CalculateMassMatrix(mMatrix.M[this_thread], rCurrentProcessInfo);
pCurrentCondition->CalculateDampingMatrix(mMatrix.D[this_thread], rCurrentProcessInfo);
// Adding the dynamic contributions (static is already included)
AddDynamicsToRHS(pCurrentCondition, rRHSContribution, mMatrix.D[this_thread], mMatrix.M[this_thread], rCurrentProcessInfo);
KRATOS_CATCH("ResidualBasedImplicitTimeScheme.Condition_Calculate_RHS_Contribution");
}
/**
* @brief It initializes time step solution. Only for reasons if the time step solution is restarted
* @param rModelPart The model part of the problem to solve
* @param rA LHS matrix
* @param rDx Incremental update of primary variables
* @param rb RHS Vector
*/
void InitializeSolutionStep(
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
) override
{
KRATOS_TRY;
ProcessInfo r_current_process_info= rModelPart.GetProcessInfo();
BaseType::InitializeSolutionStep(rModelPart, rA, rDx, rb);
const double delta_time = r_current_process_info[DELTA_TIME];
KRATOS_ERROR_IF(delta_time < 1.0e-24) << "ERROR:: Detected delta_time = 0 in the Solution Scheme DELTA_TIME. PLEASE : check if the time step is created correctly for the current time step" << std::endl;
KRATOS_CATCH("ResidualBasedImplicitTimeScheme.InitializeSolutionStep");
}
/**
* @brief This function is designed to be called once to perform all the checks needed
* on the input provided.
* @details Checks can be "expensive" as the function is designed
* to catch user's errors.
* @param rModelPart The model part of the problem to solve
* @return Zero means all ok
*/
int Check(ModelPart& rModelPart) override
{
KRATOS_TRY;
const int err = BaseType::Check(rModelPart);
if(err!=0) return err;
return 0;
KRATOS_CATCH("ResidualBasedImplicitTimeScheme.Check");
}
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override
{
return "ResidualBasedImplicitTimeScheme";
}
/// Print information about this object.
void PrintInfo(std::ostream& rOStream) const override
{
rOStream << Info();
}
/// Print object's data.
void PrintData(std::ostream& rOStream) const override
{
rOStream << Info();
}
///@}
///@name Friends
///@{
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
struct GeneralMatrices
{
std::vector< Matrix > M; /// First derivative matrix (usually mass matrix)
std::vector< Matrix > D; /// Second derivative matrix (usually damping matrix)
};
GeneralMatrices mMatrix;
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
/**
* @brief It adds the dynamic LHS contribution of the elements LHS = d(-RHS)/d(un0) = c0*c0*M + c0*D + K
* @param LHS_Contribution The dynamic contribution for the LHS
* @param D The damping matrix
* @param M The mass matrix
* @param rCurrentProcessInfo The current process info instance
*/
virtual void AddDynamicsToLHS(
LocalSystemMatrixType& LHS_Contribution,
LocalSystemMatrixType& D,
LocalSystemMatrixType& M,
ProcessInfo& rCurrentProcessInfo
)
{
KRATOS_ERROR << "YOU ARE CALLING THE BASE CLASS OF AddDynamicsToLHS" << std::endl;
}
/**
* @brief It adds the dynamic RHS contribution of the elements b - M*a - D*v
* @param rCurrentElement The element to compute
* @param RHS_Contribution The dynamic contribution for the RHS
* @param D The damping matrix
* @param M The mass matrix
* @param rCurrentProcessInfo The current process info instance
*/
virtual void AddDynamicsToRHS(
Element::Pointer rCurrentElement,
LocalSystemVectorType& RHS_Contribution,
LocalSystemMatrixType& D,
LocalSystemMatrixType& M,
ProcessInfo& rCurrentProcessInfo
)
{
KRATOS_ERROR << "YOU ARE CALLING THE BASE CLASS OF AddDynamicsToRHS" << std::endl;
}
/**
* @brief It adds the dynamic RHS contribution of the condition RHS = fext - M*an0 - D*vn0 - K*dn0
* @param rCurrentCondition The condition to compute
* @param RHS_Contribution The dynamic contribution for the RHS
* @param D The damping matrix
* @param M The mass matrix
* @param rCurrentProcessInfo The current process info instance
*/
virtual void AddDynamicsToRHS(
Condition::Pointer rCurrentCondition,
LocalSystemVectorType& RHS_Contribution,
LocalSystemMatrixType& D,
LocalSystemMatrixType& M,
ProcessInfo& rCurrentProcessInfo
)
{
KRATOS_ERROR << "YOU ARE CALLING THE BASE CLASS OF AddDynamicsToRHS" << std::endl;
}
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@{
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@}
///@name Serialization
///@{
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
///@}
}; /* Class ResidualBasedImplicitTimeScheme */
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
///@}
} /* namespace Kratos.*/
#endif /* KRATOS_RESIDUAL_BASED_IMPLICIT_TIME_SCHEME defined */
|
rose_axpy.c | #include "rex_kmp.h"
struct __tgt_bin_desc *__cubin_desc = 0;
void __attribute__((destructor)) unregister_kernel_entries()
{
__tgt_unregister_lib(__cubin_desc);
}
char OUT__1__7253__axpy_ompacc__68__id__[] = "OUT__1__7253__axpy_ompacc__68__";
struct __tgt_offload_entry __offload_entries[1];
struct __tgt_offload_entry *__start_omp_offloading_entries = &__offload_entries[0];
struct __tgt_offload_entry *__stop_omp_offloading_entries = 0;
void __attribute__((constructor)) register_kernel_entries()
{
void *OUT__1__7253__axpy_ompacc__68__entry_ptr__ = (void *)OUT__1__7253__axpy_ompacc__68__id__;
struct __tgt_offload_entry OUT__1__7253__axpy_ompacc__68__omp_offload_entry__ = {OUT__1__7253__axpy_ompacc__68__entry_ptr__, "OUT__1__7253__axpy_ompacc__68__kernel__", 0, 0, 0};
__offload_entries[0] = OUT__1__7253__axpy_ompacc__68__omp_offload_entry__;
__stop_omp_offloading_entries = &__offload_entries[1];
char cuda_entry_name[] = "rex_lib_axpy.cubin";
__cubin_desc = register_cubin(cuda_entry_name,__start_omp_offloading_entries,__stop_omp_offloading_entries);
}
// Experimental test input for Accelerator directives
// simplest scalar*vector operations
// Liao 1/15/2013
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <sys/timeb.h>
#define NUM_RUNS 10
double read_timer_ms()
{
struct timeb tm;
ftime(&tm);
return ((double )tm . time) * 1000.0 + ((double )tm . millitm);
}
/* change this to do saxpy or daxpy : single precision or double precision*/
#define REAL double
#define VEC_LEN 1024000 //use a fixed number for now
/* zero out the entire vector */
void zero(double *A,int n)
{
int i;
for (i = 0; i < n; i++) {
A[i] = 0.0;
}
}
/* initialize a vector with random floating point numbers */
void init(double *A,int n)
{
int i;
for (i = 0; i < n; i++) {
A[i] = ((double )(drand48()));
}
}
/*serial version */
void axpy(double *x,double *y,long n,double a)
{
int i;
for (i = 0; i < n; i++) {
y[i] += a * x[i];
}
}
/* compare two arrays and return percentage of difference */
double check(double *A,double *B,int n)
{
int i;
double diffsum = 0.0;
double sum = 0.0;
for (i = 0; i < n; i++) {
diffsum += fabs(A[i] - B[i]);
sum += fabs(B[i]);
}
return diffsum / sum;
}
void axpy_ompacc(double *x,double *y,int n,double a)
{
int i;
/* //implementation of the following omp target region
#pragma omp target teams distribute parallel for device (0) map(tofrom: y[0:n]) map(to: x[0:n],a,n) shared(x, y, n, a) private(i)
for (i = 0; i < n; ++i)
y[i] += a * x[i];
*/
{
double *_dev_x;
int _dev_x_size[1] = {n};
int _dev_x_offset[1] = {0};
int _dev_x_Dim[1] = {n};
double *_dev_y;
int _dev_y_size[1] = {n};
int _dev_y_offset[1] = {0};
int _dev_y_Dim[1] = {n};
/* Launch CUDA kernel ... */
int _threads_per_block_ = 1024;
int _num_blocks_ = 256;
int64_t __device_id = 0;
void *__host_ptr = (void *)OUT__1__7253__axpy_ompacc__68__id__;
void *__args_base[] = {&n, &a, x, y};
void *__args[] = {&n, &a, x + 0, y + 0};
int64_t __arg_sizes[] = {((int64_t )(sizeof(int ))), ((int64_t )(sizeof(double ))), ((int64_t )(sizeof(double ) * n)), ((int64_t )(sizeof(double ) * n))};
int64_t __arg_types[] = {33, 33, 33, 35};
int32_t __arg_num = 4;
__tgt_target_teams(__device_id,__host_ptr,__arg_num,__args_base,__args,__arg_sizes,__arg_types,_threads_per_block_,_num_blocks_);
}
}
int main(int argc,char *argv[])
{
int status = 0;
int n;
double *y_ompacc;
double *y;
double *x;
double a = 123.456;
n = 1 << 23;
// 2^23, 8 million
fprintf(stderr,"Usage: axpy <n>, where the problem size is 2^n.\n");
if (argc >= 2) {
n = 1 << atoi(argv[1]);
}
y_ompacc = ((double *)(malloc(n * sizeof(double ))));
y = ((double *)(malloc(n * sizeof(double ))));
x = ((double *)(malloc(n * sizeof(double ))));
srand48((1 << 12));
init(x,n);
init(y_ompacc,n);
memcpy(y,y_ompacc,n * sizeof(double ));
axpy(x,y,n,a);
int i;
double elapsed = read_timer_ms();
for (i = 0; i < 10; i++)
axpy_ompacc(x,y,n,a);
elapsed = (read_timer_ms() - elapsed) / 10;
double checkresult = check(y_ompacc,y,n);
fprintf(stderr,"axpy(%d): checksum: %g, time: %0.2fms\n",n,checkresult,elapsed);
//assert (checkresult < 1.0e-10);
printf("%g",elapsed);
free(y_ompacc);
free(y);
free(x);
return 0;
}
|
convolution_3x3_pack8to4_fp16s.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void conv3x3s1_winograd64_transform_kernel_pack8to4_fp16sa_neon(const Mat& kernel, Mat& kernel_tm_pack8to4, int inch, int outch, const Option& opt)
{
// winograd63 transform kernel
Mat kernel_tm;
kernel_tm.create(8 * 8, inch, outch);
const float ktm[8][3] = {
{1.0f, 0.0f, 0.0f},
{-2.0f / 9, -2.0f / 9, -2.0f / 9},
{-2.0f / 9, 2.0f / 9, -2.0f / 9},
{1.0f / 90, 1.0f / 45, 2.0f / 45},
{1.0f / 90, -1.0f / 45, 2.0f / 45},
{1.0f / 45, 1.0f / 90, 1.0f / 180},
{1.0f / 45, -1.0f / 90, 1.0f / 180},
{0.0f, 0.0f, 1.0f}
};
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
for (int q = 0; q < inch; q++)
{
const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9;
float* kernel_tm0 = kernel_tm.channel(p).row(q);
// transform kernel, transposed
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
// h
float tmp[8][3];
for (int i = 0; i < 8; i++)
{
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// v
for (int j = 0; j < 8; j++)
{
float* tmpp = &tmp[j][0];
for (int i = 0; i < 8; i++)
{
kernel_tm0[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
// interleave
// src = 64-inch-outch
// dst = 4b-8a-inch/8a-64-outch/4b
kernel_tm_pack8to4.create(2 * inch / 8, 64, outch / 8 + (outch % 8) / 4, (size_t)2u * 32, 32);
int p = 0;
for (; p + 7 < outch; p += 8)
{
const Mat k0 = kernel_tm.channel(p);
const Mat k1 = kernel_tm.channel(p + 1);
const Mat k2 = kernel_tm.channel(p + 2);
const Mat k3 = kernel_tm.channel(p + 3);
const Mat k4 = kernel_tm.channel(p + 4);
const Mat k5 = kernel_tm.channel(p + 5);
const Mat k6 = kernel_tm.channel(p + 6);
const Mat k7 = kernel_tm.channel(p + 7);
Mat g0 = kernel_tm_pack8to4.channel(p / 8);
for (int k = 0; k < 64; k++)
{
__fp16* g00 = g0.row<__fp16>(k);
for (int q = 0; q + 7 < inch; q += 8)
{
for (int i = 0; i < 8; i++)
{
g00[0] = (__fp16)k0.row(q + i)[k];
g00[1] = (__fp16)k1.row(q + i)[k];
g00[2] = (__fp16)k2.row(q + i)[k];
g00[3] = (__fp16)k3.row(q + i)[k];
g00[4] = (__fp16)k4.row(q + i)[k];
g00[5] = (__fp16)k5.row(q + i)[k];
g00[6] = (__fp16)k6.row(q + i)[k];
g00[7] = (__fp16)k7.row(q + i)[k];
g00 += 8;
}
}
}
}
for (; p + 3 < outch; p += 4)
{
const Mat k0 = kernel_tm.channel(p);
const Mat k1 = kernel_tm.channel(p + 1);
const Mat k2 = kernel_tm.channel(p + 2);
const Mat k3 = kernel_tm.channel(p + 3);
Mat g0 = kernel_tm_pack8to4.channel(p / 8 + (p % 8) / 4);
for (int k = 0; k < 64; k++)
{
__fp16* g00 = g0.row<__fp16>(k);
for (int q = 0; q + 7 < inch; q += 8)
{
for (int i = 0; i < 8; i++)
{
g00[0] = (__fp16)k0.row(q + i)[k];
g00[1] = (__fp16)k1.row(q + i)[k];
g00[2] = (__fp16)k2.row(q + i)[k];
g00[3] = (__fp16)k3.row(q + i)[k];
g00 += 4;
}
}
}
}
}
static void conv3x3s1_winograd64_pack8to4_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
//size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
// pad to 6n+2
Mat bottom_blob_bordered = bottom_blob;
outw = (outw + 5) / 6 * 6;
outh = (outh + 5) / 6 * 6;
w = outw + 2;
h = outh + 2;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt);
const __fp16* bias = _bias;
// BEGIN transform input
Mat bottom_blob_tm;
{
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = w_tm / 8 * h_tm / 8;
// bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator);
bottom_blob_tm.create(tiles, 64, inch, 2u * elempack, elempack, opt.workspace_allocator);
// const float itm[8][8] = {
// {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f},
//
// {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f},
// {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f},
//
// {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f},
// {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f},
//
// {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f},
// {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f},
//
// {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f}
// };
// 0 = r00 - r06 + (r04 - r02) * 5.25
// 7 = r07 - r01 + (r03 - r05) * 5.25
// 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05)
// 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05)
// 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2)
// 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2)
// reuse r04 * 1.25
// reuse r03 * 2.5
// 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5)
// 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5)
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < inch; q++)
{
const Mat img0 = bottom_blob_bordered.channel(q);
Mat img0_tm = bottom_blob_tm.channel(q);
__fp16 tmp[8][8][8];
// tile
for (int i = 0; i < h_tm / 8; i++)
{
for (int j = 0; j < w_tm / 8; j++)
{
const __fp16* r0 = img0.row<const __fp16>(i * 6) + (j * 6) * 8;
for (int m = 0; m < 8; m++)
{
float16x8_t _r00 = vld1q_f16(r0);
float16x8_t _r01 = vld1q_f16(r0 + 8);
float16x8_t _r02 = vld1q_f16(r0 + 16);
float16x8_t _r03 = vld1q_f16(r0 + 24);
float16x8_t _r04 = vld1q_f16(r0 + 32);
float16x8_t _r05 = vld1q_f16(r0 + 40);
float16x8_t _r06 = vld1q_f16(r0 + 48);
float16x8_t _r07 = vld1q_f16(r0 + 56);
float16x8_t _tmp0m = vfmaq_n_f16(vsubq_f16(_r00, _r06), vsubq_f16(_r04, _r02), 5.25f);
float16x8_t _tmp7m = vfmaq_n_f16(vsubq_f16(_r07, _r01), vsubq_f16(_r03, _r05), 5.25f);
vst1q_f16(tmp[0][m], _tmp0m);
vst1q_f16(tmp[7][m], _tmp7m);
// tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25;
// tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25;
float16x8_t _tmp12a = vfmsq_n_f16(vaddq_f16(_r02, _r06), _r04, 4.25f);
float16x8_t _tmp12b = vfmsq_n_f16(vaddq_f16(_r01, _r05), _r03, 4.25f);
// float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25);
// float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25);
float16x8_t _tmp1m = vaddq_f16(_tmp12a, _tmp12b);
float16x8_t _tmp2m = vsubq_f16(_tmp12a, _tmp12b);
vst1q_f16(tmp[1][m], _tmp1m);
vst1q_f16(tmp[2][m], _tmp2m);
// tmp[1][m] = tmp12a + tmp12b;
// tmp[2][m] = tmp12a - tmp12b;
float16x8_t _tmp34a = vfmsq_n_f16(vfmaq_n_f16(_r06, _r02, 0.25f), _r04, 1.25f);
float16x8_t _tmp34b = vfmaq_n_f16(vfmsq_n_f16(vmulq_n_f16(_r01, 0.5f), _r03, 2.5f), _r05, 2.f);
// float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25);
// float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2);
float16x8_t _tmp3m = vaddq_f16(_tmp34a, _tmp34b);
float16x8_t _tmp4m = vsubq_f16(_tmp34a, _tmp34b);
vst1q_f16(tmp[3][m], _tmp3m);
vst1q_f16(tmp[4][m], _tmp4m);
// tmp[3][m] = tmp34a + tmp34b;
// tmp[4][m] = tmp34a - tmp34b;
float16x8_t _tmp56a = vfmaq_n_f16(_r06, vfmsq_n_f16(_r02, _r04, 1.25f), 4.f);
float16x8_t _tmp56b = vfmaq_n_f16(vfmsq_n_f16(vmulq_n_f16(_r01, 2.f), _r03, 2.5f), _r05, 0.5f);
// float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4);
// float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5);
float16x8_t _tmp5m = vaddq_f16(_tmp56a, _tmp56b);
float16x8_t _tmp6m = vsubq_f16(_tmp56a, _tmp56b);
vst1q_f16(tmp[5][m], _tmp5m);
vst1q_f16(tmp[6][m], _tmp6m);
// tmp[5][m] = tmp56a + tmp56b;
// tmp[6][m] = tmp56a - tmp56b;
r0 += w * 8;
}
__fp16* r0_tm_0 = (__fp16*)img0_tm + (i * w_tm / 8 + j) * 8;
__fp16* r0_tm_1 = r0_tm_0 + tiles * 8;
__fp16* r0_tm_2 = r0_tm_0 + tiles * 16;
__fp16* r0_tm_3 = r0_tm_0 + tiles * 24;
__fp16* r0_tm_4 = r0_tm_0 + tiles * 32;
__fp16* r0_tm_5 = r0_tm_0 + tiles * 40;
__fp16* r0_tm_6 = r0_tm_0 + tiles * 48;
__fp16* r0_tm_7 = r0_tm_0 + tiles * 56;
for (int m = 0; m < 8; m++)
{
float16x8_t _tmp00 = vld1q_f16(tmp[m][0]);
float16x8_t _tmp01 = vld1q_f16(tmp[m][1]);
float16x8_t _tmp02 = vld1q_f16(tmp[m][2]);
float16x8_t _tmp03 = vld1q_f16(tmp[m][3]);
float16x8_t _tmp04 = vld1q_f16(tmp[m][4]);
float16x8_t _tmp05 = vld1q_f16(tmp[m][5]);
float16x8_t _tmp06 = vld1q_f16(tmp[m][6]);
float16x8_t _tmp07 = vld1q_f16(tmp[m][7]);
float16x8_t _r0tm0 = vfmaq_n_f16(vsubq_f16(_tmp00, _tmp06), vsubq_f16(_tmp04, _tmp02), 5.25f);
float16x8_t _r0tm7 = vfmaq_n_f16(vsubq_f16(_tmp07, _tmp01), vsubq_f16(_tmp03, _tmp05), 5.25f);
// r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25;
// r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25;
float16x8_t _tmp12a = vfmsq_n_f16(vaddq_f16(_tmp02, _tmp06), _tmp04, 4.25f);
float16x8_t _tmp12b = vfmsq_n_f16(vaddq_f16(_tmp01, _tmp05), _tmp03, 4.25f);
// float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25);
// float tmp12b = (tmp0[1] + tmp0[5] - tmp0[3] * 4.25);
float16x8_t _r0tm1 = vaddq_f16(_tmp12a, _tmp12b);
float16x8_t _r0tm2 = vsubq_f16(_tmp12a, _tmp12b);
// r0_tm[1] = tmp12a + tmp12b;
// r0_tm[2] = tmp12a - tmp12b;
float16x8_t _tmp34a = vfmsq_n_f16(vfmaq_n_f16(_tmp06, _tmp02, 0.25f), _tmp04, 1.25f);
float16x8_t _tmp34b = vfmaq_n_f16(vfmsq_n_f16(vmulq_n_f16(_tmp01, 0.5f), _tmp03, 2.5f), _tmp05, 2.f);
// float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25);
// float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2);
float16x8_t _r0tm3 = vaddq_f16(_tmp34a, _tmp34b);
float16x8_t _r0tm4 = vsubq_f16(_tmp34a, _tmp34b);
// r0_tm[3] = tmp34a + tmp34b;
// r0_tm[4] = tmp34a - tmp34b;
float16x8_t _tmp56a = vfmaq_n_f16(_tmp06, vfmsq_n_f16(_tmp02, _tmp04, 1.25f), 4.f);
float16x8_t _tmp56b = vfmaq_n_f16(vfmsq_n_f16(vmulq_n_f16(_tmp01, 2.f), _tmp03, 2.5f), _tmp05, 0.5f);
// float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4);
// float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5);
float16x8_t _r0tm5 = vaddq_f16(_tmp56a, _tmp56b);
float16x8_t _r0tm6 = vsubq_f16(_tmp56a, _tmp56b);
// r0_tm[5] = tmp56a + tmp56b;
// r0_tm[6] = tmp56a - tmp56b;
vst1q_f16(r0_tm_0, _r0tm0);
vst1q_f16(r0_tm_1, _r0tm1);
vst1q_f16(r0_tm_2, _r0tm2);
vst1q_f16(r0_tm_3, _r0tm3);
vst1q_f16(r0_tm_4, _r0tm4);
vst1q_f16(r0_tm_5, _r0tm5);
vst1q_f16(r0_tm_6, _r0tm6);
vst1q_f16(r0_tm_7, _r0tm7);
r0_tm_0 += tiles * 64;
r0_tm_1 += tiles * 64;
r0_tm_2 += tiles * 64;
r0_tm_3 += tiles * 64;
r0_tm_4 += tiles * 64;
r0_tm_5 += tiles * 64;
r0_tm_6 += tiles * 64;
r0_tm_7 += tiles * 64;
}
}
}
}
}
bottom_blob_bordered = Mat();
// END transform input
// BEGIN dot
Mat top_blob_tm;
{
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = h_tm / 8 * w_tm / 8;
// permute
// bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator);
Mat bottom_blob_tm2;
if (tiles >= 8)
bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + tiles % 4, 64, 2u * elempack, elempack, opt.workspace_allocator);
else if (tiles >= 4)
bottom_blob_tm2.create(4 * inch, tiles / 4 + tiles % 4, 64, 2u * elempack, elempack, opt.workspace_allocator);
else // if (tiles >= 1)
bottom_blob_tm2.create(1 * inch, tiles, 64, 2u * elempack, elempack, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int r = 0; r < 64; r++)
{
Mat tm2 = bottom_blob_tm2.channel(r);
// tile
int i = 0;
for (; i + 7 < tiles; i += 8)
{
__fp16* tm2p = tm2.row<__fp16>(i / 8);
const __fp16* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
// transpose 8x8
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0], #64 \n"
"ld4 {v4.8h, v5.8h, v6.8h, v7.8h}, [%0] \n"
"sub %0, %0, #64 \n"
"uzp1 v16.8h, v0.8h, v4.8h \n"
"uzp2 v20.8h, v0.8h, v4.8h \n"
"uzp1 v17.8h, v1.8h, v5.8h \n"
"uzp2 v21.8h, v1.8h, v5.8h \n"
"uzp1 v18.8h, v2.8h, v6.8h \n"
"uzp2 v22.8h, v2.8h, v6.8h \n"
"uzp1 v19.8h, v3.8h, v7.8h \n"
"uzp2 v23.8h, v3.8h, v7.8h \n"
"st1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%1], #64 \n"
"st1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%1], #64 \n"
: "=r"(r0), // %0
"=r"(tm2p) // %1
: "0"(r0),
"1"(tm2p)
: "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23");
r0 += bottom_blob_tm.cstep * 8;
}
}
for (; i + 3 < tiles; i += 4)
{
__fp16* tm2p = tm2.row<__fp16>(i / 8 + (i % 8) / 4);
const __fp16* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
// transpose 8x4
asm volatile(
"prfm pldl1keep, [%0, #256] \n"
"ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0] \n"
"st4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%1], #64 \n"
: "=r"(r0), // %0
"=r"(tm2p) // %1
: "0"(r0),
"1"(tm2p)
: "memory", "v0", "v1", "v2", "v3");
r0 += bottom_blob_tm.cstep * 8;
}
}
for (; i < tiles; i++)
{
__fp16* tm2p = tm2.row<__fp16>(i / 8 + (i % 8) / 4 + i % 4);
const __fp16* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
asm volatile(
"prfm pldl1keep, [%0, #128] \n"
"ld1 {v0.8h}, [%0] \n"
"st1 {v0.8h}, [%1], #16 \n"
: "=r"(r0), // %0
"=r"(tm2p) // %1
: "0"(r0),
"1"(tm2p)
: "memory", "v0");
r0 += bottom_blob_tm.cstep * 8;
}
}
}
bottom_blob_tm = Mat();
// permute end
top_blob_tm.create(tiles, 64, outch, 2u * 4, 4, opt.workspace_allocator);
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp = 0; pp < nn_outch; pp++)
{
int p = pp * 2;
__fp16* output0_tm = top_blob_tm.channel(p);
__fp16* output1_tm = top_blob_tm.channel(p + 1);
const Mat kernel01_tm = kernel_tm.channel(p / 2);
for (int r = 0; r < 64; r++)
{
const Mat bb2 = bottom_blob_tm2.channel(r);
int i = 0;
for (; i + 7 < tiles; i += 8)
{
const __fp16* r0 = bb2.row<const __fp16>(i / 8);
const __fp16* kptr = kernel01_tm.row<const __fp16>(r);
int nn = inch; // inch always > 0
asm volatile(
"eor v24.16b, v24.16b, v24.16b \n"
"eor v25.16b, v25.16b, v25.16b \n"
"eor v26.16b, v26.16b, v26.16b \n"
"eor v27.16b, v27.16b, v27.16b \n"
"eor v28.16b, v28.16b, v28.16b \n"
"eor v29.16b, v29.16b, v29.16b \n"
"eor v30.16b, v30.16b, v30.16b \n"
"eor v31.16b, v31.16b, v31.16b \n"
"0: \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%4], #64 \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%3], #64 \n"
"fmla v24.8h, v16.8h, v0.h[0] \n"
"fmla v25.8h, v16.8h, v0.h[1] \n"
"fmla v26.8h, v16.8h, v0.h[2] \n"
"fmla v27.8h, v16.8h, v0.h[3] \n"
"fmla v28.8h, v16.8h, v0.h[4] \n"
"fmla v29.8h, v16.8h, v0.h[5] \n"
"fmla v30.8h, v16.8h, v0.h[6] \n"
"fmla v31.8h, v16.8h, v0.h[7] \n"
"fmla v24.8h, v17.8h, v1.h[0] \n"
"fmla v25.8h, v17.8h, v1.h[1] \n"
"fmla v26.8h, v17.8h, v1.h[2] \n"
"fmla v27.8h, v17.8h, v1.h[3] \n"
"fmla v28.8h, v17.8h, v1.h[4] \n"
"fmla v29.8h, v17.8h, v1.h[5] \n"
"fmla v30.8h, v17.8h, v1.h[6] \n"
"fmla v31.8h, v17.8h, v1.h[7] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%4], #64 \n"
"fmla v24.8h, v18.8h, v2.h[0] \n"
"fmla v25.8h, v18.8h, v2.h[1] \n"
"fmla v26.8h, v18.8h, v2.h[2] \n"
"fmla v27.8h, v18.8h, v2.h[3] \n"
"fmla v28.8h, v18.8h, v2.h[4] \n"
"fmla v29.8h, v18.8h, v2.h[5] \n"
"fmla v30.8h, v18.8h, v2.h[6] \n"
"fmla v31.8h, v18.8h, v2.h[7] \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v4.8h, v5.8h, v6.8h, v7.8h}, [%3], #64 \n"
"fmla v24.8h, v19.8h, v3.h[0] \n"
"fmla v25.8h, v19.8h, v3.h[1] \n"
"fmla v26.8h, v19.8h, v3.h[2] \n"
"fmla v27.8h, v19.8h, v3.h[3] \n"
"fmla v28.8h, v19.8h, v3.h[4] \n"
"fmla v29.8h, v19.8h, v3.h[5] \n"
"fmla v30.8h, v19.8h, v3.h[6] \n"
"fmla v31.8h, v19.8h, v3.h[7] \n"
"fmla v24.8h, v20.8h, v4.h[0] \n"
"fmla v25.8h, v20.8h, v4.h[1] \n"
"fmla v26.8h, v20.8h, v4.h[2] \n"
"fmla v27.8h, v20.8h, v4.h[3] \n"
"fmla v28.8h, v20.8h, v4.h[4] \n"
"fmla v29.8h, v20.8h, v4.h[5] \n"
"fmla v30.8h, v20.8h, v4.h[6] \n"
"fmla v31.8h, v20.8h, v4.h[7] \n"
"fmla v24.8h, v21.8h, v5.h[0] \n"
"fmla v25.8h, v21.8h, v5.h[1] \n"
"fmla v26.8h, v21.8h, v5.h[2] \n"
"fmla v27.8h, v21.8h, v5.h[3] \n"
"fmla v28.8h, v21.8h, v5.h[4] \n"
"fmla v29.8h, v21.8h, v5.h[5] \n"
"fmla v30.8h, v21.8h, v5.h[6] \n"
"fmla v31.8h, v21.8h, v5.h[7] \n"
"fmla v24.8h, v22.8h, v6.h[0] \n"
"fmla v25.8h, v22.8h, v6.h[1] \n"
"fmla v26.8h, v22.8h, v6.h[2] \n"
"fmla v27.8h, v22.8h, v6.h[3] \n"
"fmla v28.8h, v22.8h, v6.h[4] \n"
"fmla v29.8h, v22.8h, v6.h[5] \n"
"fmla v30.8h, v22.8h, v6.h[6] \n"
"fmla v31.8h, v22.8h, v6.h[7] \n"
"subs %w0, %w0, #1 \n"
"fmla v24.8h, v23.8h, v7.h[0] \n"
"fmla v25.8h, v23.8h, v7.h[1] \n"
"fmla v26.8h, v23.8h, v7.h[2] \n"
"fmla v27.8h, v23.8h, v7.h[3] \n"
"fmla v28.8h, v23.8h, v7.h[4] \n"
"fmla v29.8h, v23.8h, v7.h[5] \n"
"fmla v30.8h, v23.8h, v7.h[6] \n"
"fmla v31.8h, v23.8h, v7.h[7] \n"
"bne 0b \n"
"st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%1], #32 \n"
"st1 {v28.4h, v29.4h, v30.4h, v31.4h}, [%1], #32 \n"
"ext v24.16b, v24.16b, v24.16b, #8 \n"
"ext v25.16b, v25.16b, v25.16b, #8 \n"
"ext v26.16b, v26.16b, v26.16b, #8 \n"
"ext v27.16b, v27.16b, v27.16b, #8 \n"
"ext v28.16b, v28.16b, v28.16b, #8 \n"
"ext v29.16b, v29.16b, v29.16b, #8 \n"
"ext v30.16b, v30.16b, v30.16b, #8 \n"
"ext v31.16b, v31.16b, v31.16b, #8 \n"
"st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%2], #32 \n"
"st1 {v28.4h, v29.4h, v30.4h, v31.4h}, [%2], #32 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(r0), // %3
"=r"(kptr) // %4
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(r0),
"4"(kptr)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
}
for (; i + 3 < tiles; i += 4)
{
const __fp16* r0 = bb2.row<const __fp16>(i / 8 + (i % 8) / 4);
const __fp16* kptr = kernel01_tm.row<const __fp16>(r);
int nn = inch; // inch always > 0
asm volatile(
"eor v24.16b, v24.16b, v24.16b \n"
"eor v25.16b, v25.16b, v25.16b \n"
"eor v26.16b, v26.16b, v26.16b \n"
"eor v27.16b, v27.16b, v27.16b \n"
"eor v28.16b, v28.16b, v28.16b \n"
"eor v29.16b, v29.16b, v29.16b \n"
"eor v30.16b, v30.16b, v30.16b \n"
"eor v31.16b, v31.16b, v31.16b \n"
"0: \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%4], #64 \n"
"prfm pldl1keep, [%3, #512] \n"
"ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%3], #64 \n"
"fmla v24.8h, v16.8h, v0.h[0] \n"
"fmla v25.8h, v16.8h, v0.h[1] \n"
"fmla v26.8h, v16.8h, v0.h[2] \n"
"fmla v27.8h, v16.8h, v0.h[3] \n"
"fmla v24.8h, v17.8h, v0.h[4] \n"
"fmla v25.8h, v17.8h, v0.h[5] \n"
"fmla v26.8h, v17.8h, v0.h[6] \n"
"fmla v27.8h, v17.8h, v0.h[7] \n"
"prfm pldl1keep, [%4, #512] \n"
"ld1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%4], #64 \n"
"fmla v24.8h, v18.8h, v1.h[0] \n"
"fmla v25.8h, v18.8h, v1.h[1] \n"
"fmla v26.8h, v18.8h, v1.h[2] \n"
"fmla v27.8h, v18.8h, v1.h[3] \n"
"fmla v24.8h, v19.8h, v1.h[4] \n"
"fmla v25.8h, v19.8h, v1.h[5] \n"
"fmla v26.8h, v19.8h, v1.h[6] \n"
"fmla v27.8h, v19.8h, v1.h[7] \n"
"fmla v24.8h, v20.8h, v2.h[0] \n"
"fmla v25.8h, v20.8h, v2.h[1] \n"
"fmla v26.8h, v20.8h, v2.h[2] \n"
"fmla v27.8h, v20.8h, v2.h[3] \n"
"fmla v24.8h, v21.8h, v2.h[4] \n"
"fmla v25.8h, v21.8h, v2.h[5] \n"
"fmla v26.8h, v21.8h, v2.h[6] \n"
"fmla v27.8h, v21.8h, v2.h[7] \n"
"subs %w0, %w0, #1 \n"
"fmla v24.8h, v22.8h, v3.h[0] \n"
"fmla v25.8h, v22.8h, v3.h[1] \n"
"fmla v26.8h, v22.8h, v3.h[2] \n"
"fmla v27.8h, v22.8h, v3.h[3] \n"
"fmla v24.8h, v23.8h, v3.h[4] \n"
"fmla v25.8h, v23.8h, v3.h[5] \n"
"fmla v26.8h, v23.8h, v3.h[6] \n"
"fmla v27.8h, v23.8h, v3.h[7] \n"
"bne 0b \n"
"st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%1], #32 \n"
"ext v24.16b, v24.16b, v24.16b, #8 \n"
"ext v25.16b, v25.16b, v25.16b, #8 \n"
"ext v26.16b, v26.16b, v26.16b, #8 \n"
"ext v27.16b, v27.16b, v27.16b, #8 \n"
"st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%2], #32 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(output1_tm), // %2
"=r"(r0), // %3
"=r"(kptr) // %4
: "0"(nn),
"1"(output0_tm),
"2"(output1_tm),
"3"(r0),
"4"(kptr)
: "cc", "memory", "v0", "v1", "v2", "v3", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
}
for (; i < tiles; i++)
{
const __fp16* r0 = bb2.row<const __fp16>(i / 8 + (i % 8) / 4 + i % 4);
const __fp16* kptr = kernel01_tm.row<const __fp16>(r);
float16x8_t _sum0 = vdupq_n_f16((__fp16)0.f);
for (int q = 0; q < inch; q++)
{
float16x8_t _r0 = vld1q_f16(r0);
float16x8_t _k0 = vld1q_f16(kptr);
float16x8_t _k1 = vld1q_f16(kptr + 8);
float16x8_t _k2 = vld1q_f16(kptr + 16);
float16x8_t _k3 = vld1q_f16(kptr + 24);
float16x8_t _k4 = vld1q_f16(kptr + 32);
float16x8_t _k5 = vld1q_f16(kptr + 40);
float16x8_t _k6 = vld1q_f16(kptr + 48);
float16x8_t _k7 = vld1q_f16(kptr + 56);
_sum0 = vfmaq_laneq_f16(_sum0, _k0, _r0, 0);
_sum0 = vfmaq_laneq_f16(_sum0, _k1, _r0, 1);
_sum0 = vfmaq_laneq_f16(_sum0, _k2, _r0, 2);
_sum0 = vfmaq_laneq_f16(_sum0, _k3, _r0, 3);
_sum0 = vfmaq_laneq_f16(_sum0, _k4, _r0, 4);
_sum0 = vfmaq_laneq_f16(_sum0, _k5, _r0, 5);
_sum0 = vfmaq_laneq_f16(_sum0, _k6, _r0, 6);
_sum0 = vfmaq_laneq_f16(_sum0, _k7, _r0, 7);
kptr += 64;
r0 += 8;
}
vst1_f16(output0_tm, vget_low_f16(_sum0));
vst1_f16(output1_tm, vget_high_f16(_sum0));
output0_tm += 4;
output1_tm += 4;
}
}
}
remain_outch_start += nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = remain_outch_start; p < outch; p++)
{
__fp16* output0_tm = top_blob_tm.channel(p);
const Mat kernel0_tm = kernel_tm.channel(p / 2 + p % 2);
for (int r = 0; r < 64; r++)
{
const Mat bb2 = bottom_blob_tm2.channel(r);
int i = 0;
for (; i + 7 < tiles; i += 8)
{
const __fp16* r0 = bb2.row<const __fp16>(i / 8);
const __fp16* kptr = kernel0_tm.row<const __fp16>(r);
int nn = inch; // inch always > 0
asm volatile(
"eor v24.16b, v24.16b, v24.16b \n"
"eor v25.16b, v25.16b, v25.16b \n"
"eor v26.16b, v26.16b, v26.16b \n"
"eor v27.16b, v27.16b, v27.16b \n"
"eor v28.16b, v28.16b, v28.16b \n"
"eor v29.16b, v29.16b, v29.16b \n"
"eor v30.16b, v30.16b, v30.16b \n"
"eor v31.16b, v31.16b, v31.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v16.4h, v17.4h, v18.4h, v19.4h}, [%3], #32 \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%2], #64 \n"
"fmla v24.4h, v16.4h, v0.h[0] \n"
"fmla v25.4h, v16.4h, v0.h[1] \n"
"fmla v26.4h, v16.4h, v0.h[2] \n"
"fmla v27.4h, v16.4h, v0.h[3] \n"
"fmla v28.4h, v16.4h, v0.h[4] \n"
"fmla v29.4h, v16.4h, v0.h[5] \n"
"fmla v30.4h, v16.4h, v0.h[6] \n"
"fmla v31.4h, v16.4h, v0.h[7] \n"
"fmla v24.4h, v17.4h, v1.h[0] \n"
"fmla v25.4h, v17.4h, v1.h[1] \n"
"fmla v26.4h, v17.4h, v1.h[2] \n"
"fmla v27.4h, v17.4h, v1.h[3] \n"
"fmla v28.4h, v17.4h, v1.h[4] \n"
"fmla v29.4h, v17.4h, v1.h[5] \n"
"fmla v30.4h, v17.4h, v1.h[6] \n"
"fmla v31.4h, v17.4h, v1.h[7] \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v20.4h, v21.4h, v22.4h, v23.4h}, [%3], #32 \n"
"fmla v24.4h, v18.4h, v2.h[0] \n"
"fmla v25.4h, v18.4h, v2.h[1] \n"
"fmla v26.4h, v18.4h, v2.h[2] \n"
"fmla v27.4h, v18.4h, v2.h[3] \n"
"fmla v28.4h, v18.4h, v2.h[4] \n"
"fmla v29.4h, v18.4h, v2.h[5] \n"
"fmla v30.4h, v18.4h, v2.h[6] \n"
"fmla v31.4h, v18.4h, v2.h[7] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v4.8h, v5.8h, v6.8h, v7.8h}, [%2], #64 \n"
"fmla v24.4h, v19.4h, v3.h[0] \n"
"fmla v25.4h, v19.4h, v3.h[1] \n"
"fmla v26.4h, v19.4h, v3.h[2] \n"
"fmla v27.4h, v19.4h, v3.h[3] \n"
"fmla v28.4h, v19.4h, v3.h[4] \n"
"fmla v29.4h, v19.4h, v3.h[5] \n"
"fmla v30.4h, v19.4h, v3.h[6] \n"
"fmla v31.4h, v19.4h, v3.h[7] \n"
"fmla v24.4h, v20.4h, v4.h[0] \n"
"fmla v25.4h, v20.4h, v4.h[1] \n"
"fmla v26.4h, v20.4h, v4.h[2] \n"
"fmla v27.4h, v20.4h, v4.h[3] \n"
"fmla v28.4h, v20.4h, v4.h[4] \n"
"fmla v29.4h, v20.4h, v4.h[5] \n"
"fmla v30.4h, v20.4h, v4.h[6] \n"
"fmla v31.4h, v20.4h, v4.h[7] \n"
"fmla v24.4h, v21.4h, v5.h[0] \n"
"fmla v25.4h, v21.4h, v5.h[1] \n"
"fmla v26.4h, v21.4h, v5.h[2] \n"
"fmla v27.4h, v21.4h, v5.h[3] \n"
"fmla v28.4h, v21.4h, v5.h[4] \n"
"fmla v29.4h, v21.4h, v5.h[5] \n"
"fmla v30.4h, v21.4h, v5.h[6] \n"
"fmla v31.4h, v21.4h, v5.h[7] \n"
"fmla v24.4h, v22.4h, v6.h[0] \n"
"fmla v25.4h, v22.4h, v6.h[1] \n"
"fmla v26.4h, v22.4h, v6.h[2] \n"
"fmla v27.4h, v22.4h, v6.h[3] \n"
"fmla v28.4h, v22.4h, v6.h[4] \n"
"fmla v29.4h, v22.4h, v6.h[5] \n"
"fmla v30.4h, v22.4h, v6.h[6] \n"
"fmla v31.4h, v22.4h, v6.h[7] \n"
"subs %w0, %w0, #1 \n"
"fmla v24.4h, v23.4h, v7.h[0] \n"
"fmla v25.4h, v23.4h, v7.h[1] \n"
"fmla v26.4h, v23.4h, v7.h[2] \n"
"fmla v27.4h, v23.4h, v7.h[3] \n"
"fmla v28.4h, v23.4h, v7.h[4] \n"
"fmla v29.4h, v23.4h, v7.h[5] \n"
"fmla v30.4h, v23.4h, v7.h[6] \n"
"fmla v31.4h, v23.4h, v7.h[7] \n"
"bne 0b \n"
"st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%1], #32 \n"
"st1 {v28.4h, v29.4h, v30.4h, v31.4h}, [%1], #32 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(r0), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(output0_tm),
"2"(r0),
"3"(kptr)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31");
}
for (; i + 3 < tiles; i += 4)
{
const __fp16* r0 = bb2.row<const __fp16>(i / 8 + (i % 8) / 4);
const __fp16* kptr = kernel0_tm.row<const __fp16>(r);
int nn = inch; // inch always > 0
asm volatile(
"eor v24.16b, v24.16b, v24.16b \n"
"eor v25.16b, v25.16b, v25.16b \n"
"eor v26.16b, v26.16b, v26.16b \n"
"eor v27.16b, v27.16b, v27.16b \n"
"0: \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v16.4h, v17.4h, v18.4h, v19.4h}, [%3], #32 \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%2], #64 \n"
"fmla v24.4h, v16.4h, v0.h[0] \n"
"fmla v25.4h, v16.4h, v0.h[1] \n"
"fmla v26.4h, v16.4h, v0.h[2] \n"
"fmla v27.4h, v16.4h, v0.h[3] \n"
"fmla v24.4h, v17.4h, v0.h[4] \n"
"fmla v25.4h, v17.4h, v0.h[5] \n"
"fmla v26.4h, v17.4h, v0.h[6] \n"
"fmla v27.4h, v17.4h, v0.h[7] \n"
"prfm pldl1keep, [%3, #256] \n"
"ld1 {v20.4h, v21.4h, v22.4h, v23.4h}, [%3], #32 \n"
"fmla v24.4h, v18.4h, v1.h[0] \n"
"fmla v25.4h, v18.4h, v1.h[1] \n"
"fmla v26.4h, v18.4h, v1.h[2] \n"
"fmla v27.4h, v18.4h, v1.h[3] \n"
"fmla v24.4h, v19.4h, v1.h[4] \n"
"fmla v25.4h, v19.4h, v1.h[5] \n"
"fmla v26.4h, v19.4h, v1.h[6] \n"
"fmla v27.4h, v19.4h, v1.h[7] \n"
"fmla v24.4h, v20.4h, v2.h[0] \n"
"fmla v25.4h, v20.4h, v2.h[1] \n"
"fmla v26.4h, v20.4h, v2.h[2] \n"
"fmla v27.4h, v20.4h, v2.h[3] \n"
"fmla v24.4h, v21.4h, v2.h[4] \n"
"fmla v25.4h, v21.4h, v2.h[5] \n"
"fmla v26.4h, v21.4h, v2.h[6] \n"
"fmla v27.4h, v21.4h, v2.h[7] \n"
"subs %w0, %w0, #1 \n"
"fmla v24.4h, v22.4h, v3.h[0] \n"
"fmla v25.4h, v22.4h, v3.h[1] \n"
"fmla v26.4h, v22.4h, v3.h[2] \n"
"fmla v27.4h, v22.4h, v3.h[3] \n"
"fmla v24.4h, v23.4h, v3.h[4] \n"
"fmla v25.4h, v23.4h, v3.h[5] \n"
"fmla v26.4h, v23.4h, v3.h[6] \n"
"fmla v27.4h, v23.4h, v3.h[7] \n"
"bne 0b \n"
"st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%1], #32 \n"
: "=r"(nn), // %0
"=r"(output0_tm), // %1
"=r"(r0), // %2
"=r"(kptr) // %3
: "0"(nn),
"1"(output0_tm),
"2"(r0),
"3"(kptr)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27");
}
for (; i < tiles; i++)
{
const __fp16* r0 = bb2.row<const __fp16>(i / 8 + (i % 8) / 4 + i % 4);
const __fp16* kptr = kernel0_tm.row<const __fp16>(r);
float16x4_t _sum0 = vdup_n_f16((__fp16)0.f);
for (int q = 0; q < inch; q++)
{
float16x8_t _r0 = vld1q_f16(r0);
float16x4_t _k0 = vld1_f16(kptr);
float16x4_t _k1 = vld1_f16(kptr + 4);
float16x4_t _k2 = vld1_f16(kptr + 8);
float16x4_t _k3 = vld1_f16(kptr + 12);
float16x4_t _k4 = vld1_f16(kptr + 16);
float16x4_t _k5 = vld1_f16(kptr + 20);
float16x4_t _k6 = vld1_f16(kptr + 24);
float16x4_t _k7 = vld1_f16(kptr + 28);
_sum0 = vfma_laneq_f16(_sum0, _k0, _r0, 0);
_sum0 = vfma_laneq_f16(_sum0, _k1, _r0, 1);
_sum0 = vfma_laneq_f16(_sum0, _k2, _r0, 2);
_sum0 = vfma_laneq_f16(_sum0, _k3, _r0, 3);
_sum0 = vfma_laneq_f16(_sum0, _k4, _r0, 4);
_sum0 = vfma_laneq_f16(_sum0, _k5, _r0, 5);
_sum0 = vfma_laneq_f16(_sum0, _k6, _r0, 6);
_sum0 = vfma_laneq_f16(_sum0, _k7, _r0, 7);
kptr += 32;
r0 += 8;
}
vst1_f16(output0_tm, _sum0);
output0_tm += 4;
}
}
}
}
bottom_blob_tm = Mat();
// END dot
// BEGIN transform output
Mat top_blob_bordered;
if (outw == top_blob.w && outh == top_blob.h)
{
top_blob_bordered = top_blob;
}
else
{
top_blob_bordered.create(outw, outh, outch, 2u * 4, 4, opt.workspace_allocator);
}
{
// const float otm[6][8] = {
// {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f}
// };
// 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32
// 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16
// 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8
// 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4
// 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2
// 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6)
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = w_tm / 8 * h_tm / 8;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
const Mat out0_tm = top_blob_tm.channel(p);
Mat out0 = top_blob_bordered.channel(p);
// const float bias0 = bias ? bias[p] : 0.f;
float16x4_t _bias0 = bias ? vld1_f16((const __fp16*)bias + p * 4) : vdup_n_f16(0.f);
__fp16 tmp[6][8][4];
// tile
for (int i = 0; i < outh / 6; i++)
{
for (int j = 0; j < outw / 6; j++)
{
// top_blob_tm.create(tiles, 64, outch, elemsize, elempack);
const __fp16* output0_tm_0 = (const __fp16*)out0_tm + (i * w_tm / 8 + j) * 4;
const __fp16* output0_tm_1 = output0_tm_0 + tiles * 4;
const __fp16* output0_tm_2 = output0_tm_0 + tiles * 8;
const __fp16* output0_tm_3 = output0_tm_0 + tiles * 12;
const __fp16* output0_tm_4 = output0_tm_0 + tiles * 16;
const __fp16* output0_tm_5 = output0_tm_0 + tiles * 20;
const __fp16* output0_tm_6 = output0_tm_0 + tiles * 24;
const __fp16* output0_tm_7 = output0_tm_0 + tiles * 28;
__fp16* output0 = out0.row<__fp16>(i * 6) + (j * 6) * 4;
// TODO neon optimize
for (int m = 0; m < 8; m++)
{
float16x4_t _out0tm0 = vld1_f16(output0_tm_0);
float16x4_t _out0tm1 = vld1_f16(output0_tm_1);
float16x4_t _out0tm2 = vld1_f16(output0_tm_2);
float16x4_t _out0tm3 = vld1_f16(output0_tm_3);
float16x4_t _out0tm4 = vld1_f16(output0_tm_4);
float16x4_t _out0tm5 = vld1_f16(output0_tm_5);
float16x4_t _out0tm6 = vld1_f16(output0_tm_6);
float16x4_t _out0tm7 = vld1_f16(output0_tm_7);
float16x4_t _tmp024a = vadd_f16(_out0tm1, _out0tm2);
float16x4_t _tmp135a = vsub_f16(_out0tm1, _out0tm2);
// float tmp024a = output0_tm[1] + output0_tm[2];
// float tmp135a = output0_tm[1] - output0_tm[2];
float16x4_t _tmp024b = vadd_f16(_out0tm3, _out0tm4);
float16x4_t _tmp135b = vsub_f16(_out0tm3, _out0tm4);
// float tmp024b = output0_tm[3] + output0_tm[4];
// float tmp135b = output0_tm[3] - output0_tm[4];
float16x4_t _tmp024c = vadd_f16(_out0tm5, _out0tm6);
float16x4_t _tmp135c = vsub_f16(_out0tm5, _out0tm6);
// float tmp024c = output0_tm[5] + output0_tm[6];
// float tmp135c = output0_tm[5] - output0_tm[6];
float16x4_t _tmp0m = vadd_f16(vadd_f16(_out0tm0, _tmp024a), vfma_n_f16(_tmp024b, _tmp024c, 32.f));
float16x4_t _tmp2m = vfma_n_f16(vfma_n_f16(_tmp024a, _tmp024b, 4.f), _tmp024c, 8.f);
float16x4_t _tmp4m = vfma_n_f16(vfma_n_f16(_tmp024a, _tmp024b, 16.f), _tmp024c, 2.f);
vst1_f16(tmp[0][m], _tmp0m);
vst1_f16(tmp[2][m], _tmp2m);
vst1_f16(tmp[4][m], _tmp4m);
// tmp[0][m] = output0_tm[0] + tmp024a + tmp024b + tmp024c * 32;
// tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8;
// tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c;
float16x4_t _tmp1m = vfma_n_f16(vfma_n_f16(_tmp135a, _tmp135b, 2.f), _tmp135c, 16.f);
float16x4_t _tmp3m = vfma_n_f16(vfma_n_f16(_tmp135a, _tmp135b, 8.f), _tmp135c, 4.f);
float16x4_t _tmp5m = vadd_f16(vadd_f16(_out0tm7, _tmp135a), vfma_n_f16(_tmp135c, _tmp135b, 32.f));
vst1_f16(tmp[1][m], _tmp1m);
vst1_f16(tmp[3][m], _tmp3m);
vst1_f16(tmp[5][m], _tmp5m);
// tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16;
// tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4;
// tmp[5][m] = output0_tm[7] + tmp135a + tmp135b * 32 + tmp135c;
output0_tm_0 += tiles * 32;
output0_tm_1 += tiles * 32;
output0_tm_2 += tiles * 32;
output0_tm_3 += tiles * 32;
output0_tm_4 += tiles * 32;
output0_tm_5 += tiles * 32;
output0_tm_6 += tiles * 32;
output0_tm_7 += tiles * 32;
}
for (int m = 0; m < 6; m++)
{
float16x4_t _tmp00 = vld1_f16(tmp[m][0]);
float16x4_t _tmp01 = vld1_f16(tmp[m][1]);
float16x4_t _tmp02 = vld1_f16(tmp[m][2]);
float16x4_t _tmp03 = vld1_f16(tmp[m][3]);
float16x4_t _tmp04 = vld1_f16(tmp[m][4]);
float16x4_t _tmp05 = vld1_f16(tmp[m][5]);
float16x4_t _tmp06 = vld1_f16(tmp[m][6]);
float16x4_t _tmp07 = vld1_f16(tmp[m][7]);
float16x4_t _tmp024a = vadd_f16(_tmp01, _tmp02);
float16x4_t _tmp135a = vsub_f16(_tmp01, _tmp02);
// float tmp024a = tmp0[1] + tmp0[2];
// float tmp135a = tmp0[1] - tmp0[2];
float16x4_t _tmp024b = vadd_f16(_tmp03, _tmp04);
float16x4_t _tmp135b = vsub_f16(_tmp03, _tmp04);
// float tmp024b = tmp0[3] + tmp0[4];
// float tmp135b = tmp0[3] - tmp0[4];
float16x4_t _tmp024c = vadd_f16(_tmp05, _tmp06);
float16x4_t _tmp135c = vsub_f16(_tmp05, _tmp06);
// float tmp024c = tmp0[5] + tmp0[6];
// float tmp135c = tmp0[5] - tmp0[6];
float16x4_t _out00 = vadd_f16(_bias0, vadd_f16(vadd_f16(_tmp00, _tmp024a), vfma_n_f16(_tmp024b, _tmp024c, 32.f)));
float16x4_t _out02 = vadd_f16(_bias0, vfma_n_f16(vfma_n_f16(_tmp024a, _tmp024b, 4.f), _tmp024c, 8.f));
float16x4_t _out04 = vadd_f16(_bias0, vfma_n_f16(vfma_n_f16(_tmp024a, _tmp024b, 16.f), _tmp024c, 2.f));
vst1_f16(output0, _out00);
vst1_f16(output0 + 8, _out02);
vst1_f16(output0 + 16, _out04);
// output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32;
// output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8;
// output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c;
float16x4_t _out01 = vadd_f16(_bias0, vfma_n_f16(vfma_n_f16(_tmp135a, _tmp135b, 2.f), _tmp135c, 16.f));
float16x4_t _out03 = vadd_f16(_bias0, vfma_n_f16(vfma_n_f16(_tmp135a, _tmp135b, 8.f), _tmp135c, 4.f));
float16x4_t _out05 = vadd_f16(_bias0, vadd_f16(vadd_f16(_tmp07, _tmp135a), vfma_n_f16(_tmp135c, _tmp135b, 32.f)));
vst1_f16(output0 + 4, _out01);
vst1_f16(output0 + 12, _out03);
vst1_f16(output0 + 20, _out05);
// output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16;
// output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4;
// output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c;
output0 += outw * 4;
}
}
}
}
}
// END transform output
// cut result pad
copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt);
}
|
stream.c | // Copyright 2009-2015 Sandia Corporation. Under the terms
// of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S.
// Government retains certain rights in this software.
//
// Copyright (c) 2009-2015, Sandia Corporation
// All rights reserved.
//
// This file is part of the SST software package. For license
// information, see the LICENSE file in the top level directory of the
// distribution.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
const int LENGTH = 2000;
printf("Allocating arrays of size %d elements.\n", LENGTH);
double* a = (double*) malloc(sizeof(double) * LENGTH);
double* b = (double*) malloc(sizeof(double) * LENGTH);
double* c = (double*) malloc(sizeof(double) * LENGTH);
printf("Done allocating arrays.\n");
int i;
for(i = 0; i < LENGTH; ++i) {
a[i] = i;
b[i] = LENGTH - i;
c[i] = 0;
}
printf("Perfoming the fast_c compute loop...\n");
#pragma omp parallel for
for(i = 0; i < LENGTH; ++i) {
//printf("issuing a write to: %llu (fast_c)\n", ((unsigned long long int) &fast_c[i]));
c[i] = 2.0 * a[i] + 1.5 * b[i];
}
double sum = 0;
for(i = 0; i < LENGTH; ++i) {
sum += c[i];
}
printf("Sum of arrays is: %f\n", sum);
printf("Freeing arrays...\n");
free(a);
free(b);
free(c);
printf("Done.\n");
}
|
YAKL_parallel_for_fortran.h |
#pragma once
namespace fortran {
template <class T> constexpr T fastmod(T a , T b) {
return a < b ? a : a-b*(a/b);
}
///////////////////////////////////////////////////////////
// LBnd: Loop Bound -- Describes the bounds of one loop
///////////////////////////////////////////////////////////
class LBnd {
public:
int l, u, s;
LBnd(int u) {
this->l = 1;
this->u = u;
this->s = 1;
}
LBnd(int l, int u) {
this->l = l;
this->u = u;
this->s = 1;
if (u < l) yakl_throw("ERROR: cannot specify an upper bound < lower bound");
}
LBnd(int l, int u, int s) {
this->l = l;
this->u = u;
this->s = s;
if (s < 1) yakl_throw("ERROR: negative strides not yet supported.");
}
index_t to_scalar() {
return (index_t) u;
}
};
///////////////////////////////////////////////////////////
// Bounds: Describes a set of loop bounds
///////////////////////////////////////////////////////////
// N == number of loops
// simple == all lower bounds are 1, and all strides are 1
template <int N, bool simple = false> class Bounds;
template<> class Bounds<8,false> {
public:
index_t nIter;
int lbounds[8];
index_t dims[8];
index_t strides[8];
Bounds( LBnd const &b0 , LBnd const &b1 , LBnd const &b2 , LBnd const &b3 , LBnd const &b4 , LBnd const &b5 , LBnd const &b6 , LBnd const &b7 ) {
lbounds[0] = b0.l; strides[0] = b0.s; dims[0] = ( b0.u - b0.l + 1 ) / b0.s;
lbounds[1] = b1.l; strides[1] = b1.s; dims[1] = ( b1.u - b1.l + 1 ) / b1.s;
lbounds[2] = b2.l; strides[2] = b2.s; dims[2] = ( b2.u - b2.l + 1 ) / b2.s;
lbounds[3] = b3.l; strides[3] = b3.s; dims[3] = ( b3.u - b3.l + 1 ) / b3.s;
lbounds[4] = b4.l; strides[4] = b4.s; dims[4] = ( b4.u - b4.l + 1 ) / b4.s;
lbounds[5] = b5.l; strides[5] = b5.s; dims[5] = ( b5.u - b5.l + 1 ) / b5.s;
lbounds[6] = b6.l; strides[6] = b6.s; dims[6] = ( b6.u - b6.l + 1 ) / b6.s;
lbounds[7] = b7.l; strides[7] = b7.s; dims[7] = ( b7.u - b7.l + 1 ) / b7.s;
nIter = 1;
for (int i=0; i<8; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[8] ) const {
// Compute base indices
index_t fac ; indices[7] = fastmod( (iGlob ) , dims[7] );
fac = dims[7]; indices[6] = fastmod( (iGlob/fac) , dims[6] );
fac *= dims[6]; indices[5] = fastmod( (iGlob/fac) , dims[5] );
fac *= dims[5]; indices[4] = fastmod( (iGlob/fac) , dims[4] );
fac *= dims[4]; indices[3] = fastmod( (iGlob/fac) , dims[3] );
fac *= dims[3]; indices[2] = fastmod( (iGlob/fac) , dims[2] );
fac *= dims[2]; indices[1] = fastmod( (iGlob/fac) , dims[1] );
fac *= dims[1]; indices[0] = (iGlob/fac) ;
// Apply strides and lower bounds
indices[0] = indices[0]*strides[0] + lbounds[0];
indices[1] = indices[1]*strides[1] + lbounds[1];
indices[2] = indices[2]*strides[2] + lbounds[2];
indices[3] = indices[3]*strides[3] + lbounds[3];
indices[4] = indices[4]*strides[4] + lbounds[4];
indices[5] = indices[5]*strides[5] + lbounds[5];
indices[6] = indices[6]*strides[6] + lbounds[6];
indices[7] = indices[7]*strides[7] + lbounds[7];
}
};
template<> class Bounds<8,true> {
public:
index_t nIter;
index_t dims[8];
Bounds( index_t b0 , index_t b1 , index_t b2 , index_t b3 , index_t b4 , index_t b5 , index_t b6 , index_t b7 ) {
dims[0] = b0;
dims[1] = b1;
dims[2] = b2;
dims[3] = b3;
dims[4] = b4;
dims[5] = b5;
dims[6] = b6;
dims[7] = b7;
nIter = 1;
for (int i=0; i<8; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[8] ) const {
// Compute base indices
index_t fac ; indices[7] = fastmod( (iGlob ) , dims[7] ) + 1;
fac = dims[7]; indices[6] = fastmod( (iGlob/fac) , dims[6] ) + 1;
fac *= dims[6]; indices[5] = fastmod( (iGlob/fac) , dims[5] ) + 1;
fac *= dims[5]; indices[4] = fastmod( (iGlob/fac) , dims[4] ) + 1;
fac *= dims[4]; indices[3] = fastmod( (iGlob/fac) , dims[3] ) + 1;
fac *= dims[3]; indices[2] = fastmod( (iGlob/fac) , dims[2] ) + 1;
fac *= dims[2]; indices[1] = fastmod( (iGlob/fac) , dims[1] ) + 1;
fac *= dims[1]; indices[0] = (iGlob/fac) + 1;
}
};
template<> class Bounds<7,false> {
public:
index_t nIter;
int lbounds[7];
index_t dims[7];
index_t strides[7];
Bounds( LBnd const &b0 , LBnd const &b1 , LBnd const &b2 , LBnd const &b3 , LBnd const &b4 , LBnd const &b5 , LBnd const &b6 ) {
lbounds[0] = b0.l; strides[0] = b0.s; dims[0] = ( b0.u - b0.l + 1 ) / b0.s;
lbounds[1] = b1.l; strides[1] = b1.s; dims[1] = ( b1.u - b1.l + 1 ) / b1.s;
lbounds[2] = b2.l; strides[2] = b2.s; dims[2] = ( b2.u - b2.l + 1 ) / b2.s;
lbounds[3] = b3.l; strides[3] = b3.s; dims[3] = ( b3.u - b3.l + 1 ) / b3.s;
lbounds[4] = b4.l; strides[4] = b4.s; dims[4] = ( b4.u - b4.l + 1 ) / b4.s;
lbounds[5] = b5.l; strides[5] = b5.s; dims[5] = ( b5.u - b5.l + 1 ) / b5.s;
lbounds[6] = b6.l; strides[6] = b6.s; dims[6] = ( b6.u - b6.l + 1 ) / b6.s;
nIter = 1;
for (int i=0; i<7; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[7] ) const {
// Compute base indices
index_t fac ; indices[6] = fastmod( (iGlob ) , dims[6] );
fac = dims[6]; indices[5] = fastmod( (iGlob/fac) , dims[5] );
fac *= dims[5]; indices[4] = fastmod( (iGlob/fac) , dims[4] );
fac *= dims[4]; indices[3] = fastmod( (iGlob/fac) , dims[3] );
fac *= dims[3]; indices[2] = fastmod( (iGlob/fac) , dims[2] );
fac *= dims[2]; indices[1] = fastmod( (iGlob/fac) , dims[1] );
fac *= dims[1]; indices[0] = (iGlob/fac) ;
// Apply strides and lower bounds
indices[0] = indices[0]*strides[0] + lbounds[0];
indices[1] = indices[1]*strides[1] + lbounds[1];
indices[2] = indices[2]*strides[2] + lbounds[2];
indices[3] = indices[3]*strides[3] + lbounds[3];
indices[4] = indices[4]*strides[4] + lbounds[4];
indices[5] = indices[5]*strides[5] + lbounds[5];
indices[6] = indices[6]*strides[6] + lbounds[6];
}
};
template<> class Bounds<7,true> {
public:
index_t nIter;
index_t dims[7];
Bounds( index_t b0 , index_t b1 , index_t b2 , index_t b3 , index_t b4 , index_t b5 , index_t b6 ) {
dims[0] = b0;
dims[1] = b1;
dims[2] = b2;
dims[3] = b3;
dims[4] = b4;
dims[5] = b5;
dims[6] = b6;
nIter = 1;
for (int i=0; i<7; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[7] ) const {
// Compute base indices
index_t fac ; indices[6] = fastmod( (iGlob ) , dims[6] ) + 1;
fac = dims[6]; indices[5] = fastmod( (iGlob/fac) , dims[5] ) + 1;
fac *= dims[5]; indices[4] = fastmod( (iGlob/fac) , dims[4] ) + 1;
fac *= dims[4]; indices[3] = fastmod( (iGlob/fac) , dims[3] ) + 1;
fac *= dims[3]; indices[2] = fastmod( (iGlob/fac) , dims[2] ) + 1;
fac *= dims[2]; indices[1] = fastmod( (iGlob/fac) , dims[1] ) + 1;
fac *= dims[1]; indices[0] = (iGlob/fac) + 1;
}
};
template<> class Bounds<6,false> {
public:
index_t nIter;
int lbounds[6];
index_t dims[6];
index_t strides[6];
Bounds( LBnd const &b0 , LBnd const &b1 , LBnd const &b2 , LBnd const &b3 , LBnd const &b4 , LBnd const &b5 ) {
lbounds[0] = b0.l; strides[0] = b0.s; dims[0] = ( b0.u - b0.l + 1 ) / b0.s;
lbounds[1] = b1.l; strides[1] = b1.s; dims[1] = ( b1.u - b1.l + 1 ) / b1.s;
lbounds[2] = b2.l; strides[2] = b2.s; dims[2] = ( b2.u - b2.l + 1 ) / b2.s;
lbounds[3] = b3.l; strides[3] = b3.s; dims[3] = ( b3.u - b3.l + 1 ) / b3.s;
lbounds[4] = b4.l; strides[4] = b4.s; dims[4] = ( b4.u - b4.l + 1 ) / b4.s;
lbounds[5] = b5.l; strides[5] = b5.s; dims[5] = ( b5.u - b5.l + 1 ) / b5.s;
nIter = 1;
for (int i=0; i<6; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[6] ) const {
// Compute base indices
index_t fac ; indices[5] = fastmod( (iGlob ) , dims[5] );
fac = dims[5]; indices[4] = fastmod( (iGlob/fac) , dims[4] );
fac *= dims[4]; indices[3] = fastmod( (iGlob/fac) , dims[3] );
fac *= dims[3]; indices[2] = fastmod( (iGlob/fac) , dims[2] );
fac *= dims[2]; indices[1] = fastmod( (iGlob/fac) , dims[1] );
fac *= dims[1]; indices[0] = (iGlob/fac) ;
// Apply strides and lower bounds
indices[0] = indices[0]*strides[0] + lbounds[0];
indices[1] = indices[1]*strides[1] + lbounds[1];
indices[2] = indices[2]*strides[2] + lbounds[2];
indices[3] = indices[3]*strides[3] + lbounds[3];
indices[4] = indices[4]*strides[4] + lbounds[4];
indices[5] = indices[5]*strides[5] + lbounds[5];
}
};
template<> class Bounds<6,true> {
public:
index_t nIter;
index_t dims[6];
Bounds( index_t b0 , index_t b1 , index_t b2 , index_t b3 , index_t b4 , index_t b5 ) {
dims[0] = b0;
dims[1] = b1;
dims[2] = b2;
dims[3] = b3;
dims[4] = b4;
dims[5] = b5;
nIter = 1;
for (int i=0; i<6; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[6] ) const {
// Compute base indices
index_t fac ; indices[5] = fastmod( (iGlob ) , dims[5] ) + 1;
fac = dims[5]; indices[4] = fastmod( (iGlob/fac) , dims[4] ) + 1;
fac *= dims[4]; indices[3] = fastmod( (iGlob/fac) , dims[3] ) + 1;
fac *= dims[3]; indices[2] = fastmod( (iGlob/fac) , dims[2] ) + 1;
fac *= dims[2]; indices[1] = fastmod( (iGlob/fac) , dims[1] ) + 1;
fac *= dims[1]; indices[0] = (iGlob/fac) + 1;
}
};
template<> class Bounds<5,false> {
public:
index_t nIter;
int lbounds[5];
index_t dims[5];
index_t strides[5];
Bounds( LBnd const &b0 , LBnd const &b1 , LBnd const &b2 , LBnd const &b3 , LBnd const &b4 ) {
lbounds[0] = b0.l; strides[0] = b0.s; dims[0] = ( b0.u - b0.l + 1 ) / b0.s;
lbounds[1] = b1.l; strides[1] = b1.s; dims[1] = ( b1.u - b1.l + 1 ) / b1.s;
lbounds[2] = b2.l; strides[2] = b2.s; dims[2] = ( b2.u - b2.l + 1 ) / b2.s;
lbounds[3] = b3.l; strides[3] = b3.s; dims[3] = ( b3.u - b3.l + 1 ) / b3.s;
lbounds[4] = b4.l; strides[4] = b4.s; dims[4] = ( b4.u - b4.l + 1 ) / b4.s;
nIter = 1;
for (int i=0; i<5; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[5] ) const {
// Compute base indices
index_t fac ; indices[4] = fastmod( (iGlob ) , dims[4] );
fac = dims[4]; indices[3] = fastmod( (iGlob/fac) , dims[3] );
fac *= dims[3]; indices[2] = fastmod( (iGlob/fac) , dims[2] );
fac *= dims[2]; indices[1] = fastmod( (iGlob/fac) , dims[1] );
fac *= dims[1]; indices[0] = (iGlob/fac) ;
// Apply strides and lower bounds
indices[0] = indices[0]*strides[0] + lbounds[0];
indices[1] = indices[1]*strides[1] + lbounds[1];
indices[2] = indices[2]*strides[2] + lbounds[2];
indices[3] = indices[3]*strides[3] + lbounds[3];
indices[4] = indices[4]*strides[4] + lbounds[4];
}
};
template<> class Bounds<5,true> {
public:
index_t nIter;
index_t dims[5];
Bounds( index_t b0 , index_t b1 , index_t b2 , index_t b3 , index_t b4 ) {
dims[0] = b0;
dims[1] = b1;
dims[2] = b2;
dims[3] = b3;
dims[4] = b4;
nIter = 1;
for (int i=0; i<5; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[5] ) const {
// Compute base indices
index_t fac ; indices[4] = fastmod( (iGlob ) , dims[4] ) + 1;
fac = dims[4]; indices[3] = fastmod( (iGlob/fac) , dims[3] ) + 1;
fac *= dims[3]; indices[2] = fastmod( (iGlob/fac) , dims[2] ) + 1;
fac *= dims[2]; indices[1] = fastmod( (iGlob/fac) , dims[1] ) + 1;
fac *= dims[1]; indices[0] = (iGlob/fac) + 1;
}
};
template<> class Bounds<4,false> {
public:
index_t nIter;
int lbounds[4];
index_t dims[4];
index_t strides[4];
Bounds( LBnd const &b0 , LBnd const &b1 , LBnd const &b2 , LBnd const &b3 ) {
lbounds[0] = b0.l; strides[0] = b0.s; dims[0] = ( b0.u - b0.l + 1 ) / b0.s;
lbounds[1] = b1.l; strides[1] = b1.s; dims[1] = ( b1.u - b1.l + 1 ) / b1.s;
lbounds[2] = b2.l; strides[2] = b2.s; dims[2] = ( b2.u - b2.l + 1 ) / b2.s;
lbounds[3] = b3.l; strides[3] = b3.s; dims[3] = ( b3.u - b3.l + 1 ) / b3.s;
nIter = 1;
for (int i=0; i<4; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[4] ) const {
// Compute base indices
index_t fac ; indices[3] = fastmod( (iGlob ) , dims[3] );
fac = dims[3]; indices[2] = fastmod( (iGlob/fac) , dims[2] );
fac *= dims[2]; indices[1] = fastmod( (iGlob/fac) , dims[1] );
fac *= dims[1]; indices[0] = (iGlob/fac) ;
// Apply strides and lower bounds
indices[0] = indices[0]*strides[0] + lbounds[0];
indices[1] = indices[1]*strides[1] + lbounds[1];
indices[2] = indices[2]*strides[2] + lbounds[2];
indices[3] = indices[3]*strides[3] + lbounds[3];
}
};
template<> class Bounds<4,true> {
public:
index_t nIter;
index_t dims[4];
Bounds( index_t b0 , index_t b1 , index_t b2 , index_t b3 ) {
dims[0] = b0;
dims[1] = b1;
dims[2] = b2;
dims[3] = b3;
nIter = 1;
for (int i=0; i<4; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[4] ) const {
// Compute base indices
index_t fac ; indices[3] = fastmod( (iGlob ) , dims[3] ) + 1;
fac = dims[3]; indices[2] = fastmod( (iGlob/fac) , dims[2] ) + 1;
fac *= dims[2]; indices[1] = fastmod( (iGlob/fac) , dims[1] ) + 1;
fac *= dims[1]; indices[0] = (iGlob/fac) + 1;
}
};
template<> class Bounds<3,false> {
public:
index_t nIter;
int lbounds[3];
index_t dims[3];
index_t strides[3];
Bounds( LBnd const &b0 , LBnd const &b1 , LBnd const &b2 ) {
lbounds[0] = b0.l; strides[0] = b0.s; dims[0] = ( b0.u - b0.l + 1 ) / b0.s;
lbounds[1] = b1.l; strides[1] = b1.s; dims[1] = ( b1.u - b1.l + 1 ) / b1.s;
lbounds[2] = b2.l; strides[2] = b2.s; dims[2] = ( b2.u - b2.l + 1 ) / b2.s;
nIter = 1;
for (int i=0; i<3; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[3] ) const {
// Compute base indices
index_t fac ; indices[2] = fastmod( (iGlob ) , dims[2] );
fac = dims[2]; indices[1] = fastmod( (iGlob/fac) , dims[1] );
fac *= dims[1]; indices[0] = (iGlob/fac) ;
// Apply strides and lower bounds
indices[0] = indices[0]*strides[0] + lbounds[0];
indices[1] = indices[1]*strides[1] + lbounds[1];
indices[2] = indices[2]*strides[2] + lbounds[2];
}
};
template<> class Bounds<3,true> {
public:
index_t nIter;
index_t dims[3];
Bounds( index_t b0 , index_t b1 , index_t b2 ) {
dims[0] = b0;
dims[1] = b1;
dims[2] = b2;
nIter = 1;
for (int i=0; i<3; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[3] ) const {
// Compute base indices
index_t fac ; indices[2] = fastmod( (iGlob ) , dims[2] ) + 1;
fac = dims[2]; indices[1] = fastmod( (iGlob/fac) , dims[1] ) + 1;
fac *= dims[1]; indices[0] = (iGlob/fac) + 1;
}
};
template<> class Bounds<2,false> {
public:
index_t nIter;
int lbounds[2];
index_t dims[2];
index_t strides[2];
Bounds( LBnd const &b0 , LBnd const &b1 ) {
lbounds[0] = b0.l; strides[0] = b0.s; dims[0] = ( b0.u - b0.l + 1 ) / b0.s;
lbounds[1] = b1.l; strides[1] = b1.s; dims[1] = ( b1.u - b1.l + 1 ) / b1.s;
nIter = 1;
for (int i=0; i<2; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[2] ) const {
// Compute base indices
indices[1] = fastmod( (iGlob ) , dims[1] );
indices[0] = (iGlob/dims[1]) ;
// Apply strides and lower bounds
indices[0] = indices[0]*strides[0] + lbounds[0];
indices[1] = indices[1]*strides[1] + lbounds[1];
}
};
template<> class Bounds<2,true> {
public:
index_t nIter;
index_t dims[2];
Bounds( index_t b0 , index_t b1 ) {
dims[0] = b0;
dims[1] = b1;
nIter = 1;
for (int i=0; i<2; i++) { nIter *= dims[i]; }
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[2] ) const {
// Compute base indices
indices[1] = fastmod( (iGlob ) , dims[1] ) + 1;
indices[0] = (iGlob/dims[1]) + 1;
}
};
template<> class Bounds<1,false> {
public:
index_t nIter;
int lbounds[1];
index_t dims[1];
index_t strides[1];
Bounds( LBnd const &b0 ) {
lbounds[0] = b0.l; strides[0] = b0.s; dims[0] = ( b0.u - b0.l + 1 ) / b0.s;
nIter = dims[0];
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[1] ) const {
// Compute base indices
indices[0] = iGlob;
// Apply strides and lower bounds
indices[0] = indices[0]*strides[0] + lbounds[0];
}
};
template<> class Bounds<1,true> {
public:
index_t nIter;
index_t dims[1];
Bounds( index_t b0 ) {
dims[0] = b0;
nIter = dims[0];
}
YAKL_DEVICE_INLINE void unpackIndices( index_t iGlob , int indices[1] ) const {
// Compute base indices
indices[0] = iGlob + 1;
}
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Make it easy for the user to specify that all lower bounds are zero and all strides are one
////////////////////////////////////////////////////////////////////////////////////////////////
template <int N> using SimpleBounds = Bounds<N,true>;
////////////////////////////////////////////////
// Convenience functions to handle the indexing
////////////////////////////////////////////////
template <class F, bool simple> YAKL_DEVICE_INLINE void callFunctor(F const &f , Bounds<1,simple> const &bnd , int const i ) {
int ind[1];
bnd.unpackIndices( i , ind );
f(ind[0]);
}
template <class F, bool simple> YAKL_DEVICE_INLINE void callFunctor(F const &f , Bounds<2,simple> const &bnd , int const i ) {
int ind[2];
bnd.unpackIndices( i , ind );
f(ind[0],ind[1]);
}
template <class F, bool simple> YAKL_DEVICE_INLINE void callFunctor(F const &f , Bounds<3,simple> const &bnd , int const i ) {
int ind[3];
bnd.unpackIndices( i , ind );
f(ind[0],ind[1],ind[2]);
}
template <class F, bool simple> YAKL_DEVICE_INLINE void callFunctor(F const &f , Bounds<4,simple> const &bnd , int const i ) {
int ind[4];
bnd.unpackIndices( i , ind );
f(ind[0],ind[1],ind[2],ind[3]);
}
template <class F, bool simple> YAKL_DEVICE_INLINE void callFunctor(F const &f , Bounds<5,simple> const &bnd , int const i ) {
int ind[5];
bnd.unpackIndices( i , ind );
f(ind[0],ind[1],ind[2],ind[3],ind[4]);
}
template <class F, bool simple> YAKL_DEVICE_INLINE void callFunctor(F const &f , Bounds<6,simple> const &bnd , int const i ) {
int ind[6];
bnd.unpackIndices( i , ind );
f(ind[0],ind[1],ind[2],ind[3],ind[4],ind[5]);
}
template <class F, bool simple> YAKL_DEVICE_INLINE void callFunctor(F const &f , Bounds<7,simple> const &bnd , int const i ) {
int ind[7];
bnd.unpackIndices( i , ind );
f(ind[0],ind[1],ind[2],ind[3],ind[4],ind[5],ind[6]);
}
template <class F, bool simple> YAKL_DEVICE_INLINE void callFunctor(F const &f , Bounds<8,simple> const &bnd , int const i ) {
int ind[8];
bnd.unpackIndices( i , ind );
f(ind[0],ind[1],ind[2],ind[3],ind[4],ind[5],ind[6],ind[7]);
}
////////////////////////////////////////////////
// HARDWARE BACKENDS FOR KERNEL LAUNCHING
////////////////////////////////////////////////
#ifdef YAKL_ARCH_CUDA
template <class F, int N, bool simple> __global__ void cudaKernelVal( Bounds<N,simple> bounds , F f ) {
size_t i = blockIdx.x*blockDim.x + threadIdx.x;
if (i < bounds.nIter) {
callFunctor( f , bounds , i );
}
}
template <class F, int N, bool simple> __global__ void cudaKernelRef( Bounds<N,simple> bounds , F const &f ) {
size_t i = blockIdx.x*blockDim.x + threadIdx.x;
if (i < bounds.nIter) {
callFunctor( f , bounds , i );
}
}
template<class F , int N , bool simple , typename std::enable_if< sizeof(F) <= 3900 , int >::type = 0>
void parallel_for_cuda( Bounds<N,simple> const &bounds , F const &f , int vectorSize = 128 ) {
cudaKernelVal <<< (unsigned int) (bounds.nIter-1)/vectorSize+1 , vectorSize >>> ( bounds , f );
check_last_error();
}
template<class F , int N , bool simple , typename std::enable_if< sizeof(F) >= 3901 , int >::type = 0>
void parallel_for_cuda( Bounds<N,simple> const &bounds , F const &f , int vectorSize = 128 ) {
F *fp = (F *) functorBuffer;
cudaMemcpyAsync(fp,&f,sizeof(F),cudaMemcpyHostToDevice);
check_last_error();
cudaKernelRef <<< (unsigned int) (bounds.nIter-1)/vectorSize+1 , vectorSize >>> ( bounds , *fp );
check_last_error();
}
#endif
#ifdef YAKL_ARCH_HIP
template <class F, int N, bool simple> __global__ void hipKernel( Bounds<N,simple> bounds , F f ) {
size_t i = blockIdx.x*blockDim.x + threadIdx.x;
if (i < bounds.nIter) {
callFunctor( f , bounds , i );
}
}
template<class F, int N, bool simple>
void parallel_for_hip( Bounds<N,simple> const &bounds , F const &f , int vectorSize = 128 ) {
hipLaunchKernelGGL( hipKernel , dim3((bounds.nIter-1)/vectorSize+1) , dim3(vectorSize) ,
(std::uint32_t) 0 , (hipStream_t) 0 , bounds , f );
check_last_error();
}
#endif
#ifdef YAKL_ARCH_SYCL
template<class F, int N, bool simple>
void parallel_for_sycl( Bounds<N,simple> const &bounds , F const &f , int vectorSize = 128 ) {
if constexpr (sycl::is_device_copyable<F>::value) {
sycl_default_stream->parallel_for( sycl::range<1>(bounds.nIter) , [=] (sycl::id<1> i) {
callFunctor( f , bounds , i );
}).wait();
} else {
F *fp = (F *) functorBuffer;
sycl_default_stream->memcpy(fp, &f, sizeof(F)).wait();
sycl_default_stream->parallel_for( sycl::range<1>(bounds.nIter) , [=] (sycl::id<1> i) {
callFunctor( *fp , bounds , i );
}).wait();
}
check_last_error();
}
#endif
template <class F> inline void parallel_for_cpu_serial( int ubnd , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for simd
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for
#endif
for (int i0 = 1; i0 < ubnd; i0++) {
f( i0 );
}
}
template <class F> inline void parallel_for_cpu_serial( LBnd &bnd , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for simd
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for
#endif
for (int i0 = bnd.l; i0 < (int) (bnd.l+(bnd.u-bnd.l+1)); i0+=bnd.s) {
f( i0 );
}
}
template <class F> inline void parallel_for_cpu_serial( Bounds<1,false> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for simd
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for
#endif
for (int i0 = bounds.lbounds[0]; i0 < (int) (bounds.lbounds[0]+bounds.dims[0]*bounds.strides[0]); i0+=bounds.strides[0]) {
f( i0 );
}
}
template <class F> inline void parallel_for_cpu_serial( Bounds<2,false> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(2)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(2)
#endif
for (int i0 = bounds.lbounds[0]; i0 < (int) (bounds.lbounds[0]+bounds.dims[0]*bounds.strides[0]); i0+=bounds.strides[0]) {
for (int i1 = bounds.lbounds[1]; i1 < (int) (bounds.lbounds[1]+bounds.dims[1]*bounds.strides[1]); i1+=bounds.strides[1]) {
f( i0 , i1 );
} }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<3,false> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(3)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(3)
#endif
for (int i0 = bounds.lbounds[0]; i0 < (int) (bounds.lbounds[0]+bounds.dims[0]*bounds.strides[0]); i0+=bounds.strides[0]) {
for (int i1 = bounds.lbounds[1]; i1 < (int) (bounds.lbounds[1]+bounds.dims[1]*bounds.strides[1]); i1+=bounds.strides[1]) {
for (int i2 = bounds.lbounds[2]; i2 < (int) (bounds.lbounds[2]+bounds.dims[2]*bounds.strides[2]); i2+=bounds.strides[2]) {
f( i0 , i1 , i2 );
} } }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<4,false> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(4)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(4)
#endif
for (int i0 = bounds.lbounds[0]; i0 < (int) (bounds.lbounds[0]+bounds.dims[0]*bounds.strides[0]); i0+=bounds.strides[0]) {
for (int i1 = bounds.lbounds[1]; i1 < (int) (bounds.lbounds[1]+bounds.dims[1]*bounds.strides[1]); i1+=bounds.strides[1]) {
for (int i2 = bounds.lbounds[2]; i2 < (int) (bounds.lbounds[2]+bounds.dims[2]*bounds.strides[2]); i2+=bounds.strides[2]) {
for (int i3 = bounds.lbounds[3]; i3 < (int) (bounds.lbounds[3]+bounds.dims[3]*bounds.strides[3]); i3+=bounds.strides[3]) {
f( i0 , i1 , i2 , i3 );
} } } }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<5,false> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(5)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(5)
#endif
for (int i0 = bounds.lbounds[0]; i0 < (int) (bounds.lbounds[0]+bounds.dims[0]*bounds.strides[0]); i0+=bounds.strides[0]) {
for (int i1 = bounds.lbounds[1]; i1 < (int) (bounds.lbounds[1]+bounds.dims[1]*bounds.strides[1]); i1+=bounds.strides[1]) {
for (int i2 = bounds.lbounds[2]; i2 < (int) (bounds.lbounds[2]+bounds.dims[2]*bounds.strides[2]); i2+=bounds.strides[2]) {
for (int i3 = bounds.lbounds[3]; i3 < (int) (bounds.lbounds[3]+bounds.dims[3]*bounds.strides[3]); i3+=bounds.strides[3]) {
for (int i4 = bounds.lbounds[4]; i4 < (int) (bounds.lbounds[4]+bounds.dims[4]*bounds.strides[4]); i4+=bounds.strides[4]) {
f( i0 , i1 , i2 , i3 , i4 );
} } } } }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<6,false> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(6)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(6)
#endif
for (int i0 = bounds.lbounds[0]; i0 < (int) (bounds.lbounds[0]+bounds.dims[0]*bounds.strides[0]); i0+=bounds.strides[0]) {
for (int i1 = bounds.lbounds[1]; i1 < (int) (bounds.lbounds[1]+bounds.dims[1]*bounds.strides[1]); i1+=bounds.strides[1]) {
for (int i2 = bounds.lbounds[2]; i2 < (int) (bounds.lbounds[2]+bounds.dims[2]*bounds.strides[2]); i2+=bounds.strides[2]) {
for (int i3 = bounds.lbounds[3]; i3 < (int) (bounds.lbounds[3]+bounds.dims[3]*bounds.strides[3]); i3+=bounds.strides[3]) {
for (int i4 = bounds.lbounds[4]; i4 < (int) (bounds.lbounds[4]+bounds.dims[4]*bounds.strides[4]); i4+=bounds.strides[4]) {
for (int i5 = bounds.lbounds[5]; i5 < (int) (bounds.lbounds[5]+bounds.dims[5]*bounds.strides[5]); i5+=bounds.strides[5]) {
f( i0 , i1 , i2 , i3 , i4 , i5 );
} } } } } }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<7,false> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(7)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(7)
#endif
for (int i0 = bounds.lbounds[0]; i0 < (int) (bounds.lbounds[0]+bounds.dims[0]*bounds.strides[0]); i0+=bounds.strides[0]) {
for (int i1 = bounds.lbounds[1]; i1 < (int) (bounds.lbounds[1]+bounds.dims[1]*bounds.strides[1]); i1+=bounds.strides[1]) {
for (int i2 = bounds.lbounds[2]; i2 < (int) (bounds.lbounds[2]+bounds.dims[2]*bounds.strides[2]); i2+=bounds.strides[2]) {
for (int i3 = bounds.lbounds[3]; i3 < (int) (bounds.lbounds[3]+bounds.dims[3]*bounds.strides[3]); i3+=bounds.strides[3]) {
for (int i4 = bounds.lbounds[4]; i4 < (int) (bounds.lbounds[4]+bounds.dims[4]*bounds.strides[4]); i4+=bounds.strides[4]) {
for (int i5 = bounds.lbounds[5]; i5 < (int) (bounds.lbounds[5]+bounds.dims[5]*bounds.strides[5]); i5+=bounds.strides[5]) {
for (int i6 = bounds.lbounds[6]; i6 < (int) (bounds.lbounds[6]+bounds.dims[6]*bounds.strides[6]); i6+=bounds.strides[6]) {
f( i0 , i1 , i2 , i3 , i4 , i5 , i6 );
} } } } } } }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<8,false> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(8)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(8)
#endif
for (int i0 = bounds.lbounds[0]; i0 < (int) (bounds.lbounds[0]+bounds.dims[0]*bounds.strides[0]); i0+=bounds.strides[0]) {
for (int i1 = bounds.lbounds[1]; i1 < (int) (bounds.lbounds[1]+bounds.dims[1]*bounds.strides[1]); i1+=bounds.strides[1]) {
for (int i2 = bounds.lbounds[2]; i2 < (int) (bounds.lbounds[2]+bounds.dims[2]*bounds.strides[2]); i2+=bounds.strides[2]) {
for (int i3 = bounds.lbounds[3]; i3 < (int) (bounds.lbounds[3]+bounds.dims[3]*bounds.strides[3]); i3+=bounds.strides[3]) {
for (int i4 = bounds.lbounds[4]; i4 < (int) (bounds.lbounds[4]+bounds.dims[4]*bounds.strides[4]); i4+=bounds.strides[4]) {
for (int i5 = bounds.lbounds[5]; i5 < (int) (bounds.lbounds[5]+bounds.dims[5]*bounds.strides[5]); i5+=bounds.strides[5]) {
for (int i6 = bounds.lbounds[6]; i6 < (int) (bounds.lbounds[6]+bounds.dims[6]*bounds.strides[6]); i6+=bounds.strides[6]) {
for (int i7 = bounds.lbounds[7]; i7 < (int) (bounds.lbounds[7]+bounds.dims[7]*bounds.strides[7]); i7+=bounds.strides[7]) {
f( i0 , i1 , i2 , i3 , i4 , i5 , i6 , i7 );
} } } } } } } }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<1,true> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for simd
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for
#endif
for (int i0 = 1; i0 <= bounds.dims[0]; i0++) {
f( i0 );
}
}
template <class F> inline void parallel_for_cpu_serial( Bounds<2,true> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(2)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(2)
#endif
for (int i0 = 1; i0 <= bounds.dims[0]; i0++) {
for (int i1 = 1; i1 <= bounds.dims[1]; i1++) {
f( i0 , i1 );
} }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<3,true> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(3)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(3)
#endif
for (int i0 = 1; i0 <= bounds.dims[0]; i0++) {
for (int i1 = 1; i1 <= bounds.dims[1]; i1++) {
for (int i2 = 1; i2 <= bounds.dims[2]; i2++) {
f( i0 , i1 , i2 );
} } }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<4,true> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(4)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(4)
#endif
for (int i0 = 1; i0 <= bounds.dims[0]; i0++) {
for (int i1 = 1; i1 <= bounds.dims[1]; i1++) {
for (int i2 = 1; i2 <= bounds.dims[2]; i2++) {
for (int i3 = 1; i3 <= bounds.dims[3]; i3++) {
f( i0 , i1 , i2 , i3 );
} } } }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<5,true> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(5)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(5)
#endif
for (int i0 = 1; i0 <= bounds.dims[0]; i0++) {
for (int i1 = 1; i1 <= bounds.dims[1]; i1++) {
for (int i2 = 1; i2 <= bounds.dims[2]; i2++) {
for (int i3 = 1; i3 <= bounds.dims[3]; i3++) {
for (int i4 = 1; i4 <= bounds.dims[4]; i4++) {
f( i0 , i1 , i2 , i3 , i4 );
} } } } }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<6,true> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(6)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(6)
#endif
for (int i0 = 1; i0 <= bounds.dims[0]; i0++) {
for (int i1 = 1; i1 <= bounds.dims[1]; i1++) {
for (int i2 = 1; i2 <= bounds.dims[2]; i2++) {
for (int i3 = 1; i3 <= bounds.dims[3]; i3++) {
for (int i4 = 1; i4 <= bounds.dims[4]; i4++) {
for (int i5 = 1; i5 <= bounds.dims[5]; i5++) {
f( i0 , i1 , i2 , i3 , i4 , i5 );
} } } } } }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<7,true> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(7)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(7)
#endif
for (int i0 = 1; i0 <= bounds.dims[0]; i0++) {
for (int i1 = 1; i1 <= bounds.dims[1]; i1++) {
for (int i2 = 1; i2 <= bounds.dims[2]; i2++) {
for (int i3 = 1; i3 <= bounds.dims[3]; i3++) {
for (int i4 = 1; i4 <= bounds.dims[4]; i4++) {
for (int i5 = 1; i5 <= bounds.dims[5]; i5++) {
for (int i6 = 1; i6 <= bounds.dims[6]; i6++) {
f( i0 , i1 , i2 , i3 , i4 , i5 , i6 );
} } } } } } }
}
template <class F> inline void parallel_for_cpu_serial( Bounds<8,true> const &bounds , F const &f ) {
#ifdef YAKL_ARCH_OPENMP45
#pragma omp target teams distribute parallel for collapse(8)
#endif
#ifdef YAKL_ARCH_OPENMP
#pragma omp parallel for collapse(8)
#endif
for (int i0 = 1; i0 <= bounds.dims[0]; i0++) {
for (int i1 = 1; i1 <= bounds.dims[1]; i1++) {
for (int i2 = 1; i2 <= bounds.dims[2]; i2++) {
for (int i3 = 1; i3 <= bounds.dims[3]; i3++) {
for (int i4 = 1; i4 <= bounds.dims[4]; i4++) {
for (int i5 = 1; i5 <= bounds.dims[5]; i5++) {
for (int i6 = 1; i6 <= bounds.dims[6]; i6++) {
for (int i7 = 1; i7 <= bounds.dims[7]; i7++) {
f( i0 , i1 , i2 , i3 , i4 , i5 , i6 , i7 );
} } } } } } } }
}
////////////////////////////////////////////////
// MAIN USER-LEVEL FUNCTIONS
////////////////////////////////////////////////
// Bounds class, No label
// This serves as the template, which all other user-level functions route into
template <class F, int N, bool simple>
inline void parallel_for( Bounds<N,simple> const &bounds , F const &f , int vectorSize = 128 ) {
#ifdef YAKL_ARCH_CUDA
parallel_for_cuda( bounds , f , vectorSize );
#elif defined(YAKL_ARCH_HIP)
parallel_for_hip ( bounds , f , vectorSize );
#elif defined(YAKL_ARCH_SYCL)
parallel_for_sycl( bounds , f , vectorSize );
#else
parallel_for_cpu_serial( bounds , f );
#endif
#if defined(YAKL_AUTO_FENCE) || defined(YAKL_DEBUG)
fence();
#endif
}
// Bounds class, Label
template <class F, int N, bool simple>
inline void parallel_for( char const * str , Bounds<N,simple> const &bounds , F const &f, int vectorSize = 128 ) {
#ifdef YAKL_ARCH_CUDA
nvtxRangePushA(str);
#endif
#ifdef YAKL_AUTO_PROFILE
timer_start(str);
#endif
parallel_for( bounds , f , vectorSize );
#ifdef YAKL_AUTO_PROFILE
timer_stop(str);
#endif
#ifdef YAKL_ARCH_CUDA
nvtxRangePop();
#endif
}
// Single bound or integer, no label
// Since "bnd" is accepted by value, integers will be accepted as well
template <class F> inline void parallel_for( LBnd bnd , F const &f , int vectorSize = 128 ) {
if (bnd.l == 1 && bnd.s == 1) {
parallel_for( Bounds<1,true>(bnd.to_scalar()) , f , vectorSize );
} else {
parallel_for( Bounds<1,false>(bnd) , f , vectorSize );
}
}
// Single bound or integer, label
// Since "bnd" is accepted by value, integers will be accepted as well
template <class F> inline void parallel_for( char const * str , LBnd bnd , F const &f , int vectorSize = 128 ) {
#ifdef YAKL_ARCH_CUDA
nvtxRangePushA(str);
#endif
#ifdef YAKL_AUTO_PROFILE
timer_start(str);
#endif
if (bnd.l == 1 && bnd.s == 1) {
parallel_for( Bounds<1,true>(bnd.to_scalar()) , f , vectorSize );
} else {
parallel_for( Bounds<1,false>(bnd) , f , vectorSize );
}
#ifdef YAKL_AUTO_PROFILE
timer_stop(str);
#endif
#ifdef YAKL_ARCH_CUDA
nvtxRangePop();
#endif
}
template <class F, class T, typename std::enable_if< std::is_integral<T>::value , int >::type = 0 >
inline void parallel_for( T bnd , F const &f , int vectorSize = 128 ) {
parallel_for( Bounds<1,true>(bnd) , f , vectorSize );
}
template <class F, class T, typename std::enable_if< std::is_integral<T>::value , int >::type = 0 >
inline void parallel_for( char const * str , T bnd , F const &f , int vectorSize = 128 ) {
parallel_for( Bounds<1,true>(bnd) , f , vectorSize );
}
}
|
projectq.h | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MINDQUANTUM_BACKENDS_PROJECTQ_PROJECTQ_H_
#define MINDQUANTUM_BACKENDS_PROJECTQ_PROJECTQ_H_
#include <cmath>
#include <functional>
#include <memory>
#include <random>
#include <string>
#include <thread>
#include <vector>
#include "gate/basic_gate.h"
#include "gate/gates.h"
#include "hamiltonian/hamiltonian.h"
#include "pr/parameter_resolver.h"
#include "projectq/backends/_sim/_cppkernels/simulator.hpp"
#include "projectq_utils.h"
namespace mindquantum {
namespace omp {
#ifdef _MSC_VER
typedef int64_t idx_t;
#else
typedef uint64_t idx_t;
#endif // _MSC_VER
} // namespace omp
namespace projectq {
template <typename T>
class Projectq : public Simulator {
private:
unsigned seed;
unsigned n_qubits_;
VT<unsigned> ordering_;
unsigned len_;
RndEngine rnd_eng_;
std::function<double()> rng_;
public:
Projectq() : Simulator(1, 1), n_qubits_(1), rnd_eng_(1), seed(1) {
for (unsigned i = 0; i < n_qubits_; i++) {
ordering_.push_back(i);
}
len_ = (1UL << (n_qubits_ + 1));
std::uniform_real_distribution<double> dist(0., 1.);
rng_ = std::bind(dist, std::ref(rnd_eng_));
}
Projectq(unsigned seed, unsigned N) : Simulator(seed, N), n_qubits_(N), rnd_eng_(seed), seed(seed) {
for (unsigned i = 0; i < n_qubits_; i++) {
ordering_.push_back(i);
}
len_ = (1UL << (n_qubits_ + 1));
std::uniform_real_distribution<double> dist(0., 1.);
rng_ = std::bind(dist, std::ref(rnd_eng_));
}
Projectq(unsigned seed, unsigned N, calc_type *vec) : Simulator(seed, N), n_qubits_(N), rnd_eng_(seed), seed(seed) {
for (unsigned i = 0; i < n_qubits_; i++) {
ordering_.push_back(i);
}
len_ = (1UL << (n_qubits_ + 1));
set_wavefunction(vec, ordering_);
std::uniform_real_distribution<double> dist(0., 1.);
rng_ = std::bind(dist, std::ref(rnd_eng_));
}
void InitializeSimulator() {
if (vec_ != NULL) {
free(vec_);
}
vec_ = (StateVector) calloc(len_, sizeof(calc_type));
vec_[0] = 1;
}
void InitializeSimulator(const VT<BasicGate<T>> &circ) {
Projectq::InitializeSimulator();
Projectq::ApplyCircuit(circ);
}
void InitializeSimulator(CTP<T> vec) {
}
void SetState(VT<CT<T>> vec) {
set_wavefunction(reinterpret_cast<calc_type *>(vec.data()), ordering_);
}
void ApplyGate(const BasicGate<T> &gate) {
if (gate.is_pauli_channel_) { // gate is constructed be like: BasicGate(cPL, true, px, py, pz)
VT<BasicGate<T>> gate_list_ = {XGate<T>, YGate<T>, ZGate<T>, IGate<T>};
double r = static_cast<double>(rng_());
// std::cout << "r = " << r << std::endl;
auto it = std::lower_bound(gate.cumulative_probs_.begin(), gate.cumulative_probs_.end(), r);
size_t gate_index;
if (it != gate.cumulative_probs_.begin()) {
gate_index = std::distance(gate.cumulative_probs_.begin(), it) - 1;
} else {
gate_index = 0;
}
BasicGate<T> gate_ = gate_list_[gate_index]; // Select the gate to execute according to r.
// std::cout << gate_.name_ << std::endl;
Projectq::apply_controlled_gate(MCast<T>(gate_.base_matrix_.matrix_), VCast(gate.obj_qubits_),
VCast(gate.ctrl_qubits_));
} else if (gate.is_damping_channel_) {
VT<T> base_index;
for (unsigned i = 0; i < (1 << n_qubits_); i++) {
if ((i >> gate.obj_qubits_[0]) & 1) {
base_index.push_back(i);
}
}
VT<CT<T>> curr_state_ = Projectq::cheat();
double reduced_factor_ = 0;
for (unsigned i = 0; i < base_index.size(); i++) {
reduced_factor_ += (curr_state_[base_index[i]] * std::conj(curr_state_[base_index[i]])).real();
}
if (reduced_factor_ < pow(10, -8)) {
return;
}
double prob_ = gate.damping_coeff_ * reduced_factor_;
double r = static_cast<double>(rng_());
VT<CT<T>> aim_state_ = curr_state_;
if (gate.name_ == "ADC") {
unsigned j = 0;
unsigned k = 0;
for (unsigned i = 0; i < aim_state_.size(); i++) {
if (base_index[j] == i) {
aim_state_[i] = 0;
j++;
} else {
aim_state_[i] = aim_state_[base_index[k]] / sqrt(reduced_factor_);
k++;
}
}
} else if (gate.name_ == "PDC") {
unsigned j = 0;
for (unsigned i = 0; i < aim_state_.size(); i++) {
if (base_index[j] == i) {
aim_state_[i] = aim_state_[i] / sqrt(reduced_factor_);
j++;
} else {
aim_state_[i] = 0;
}
}
} else {
return;
}
if (r <= prob_) {
Projectq::SetState(aim_state_);
} else {
VT<CT<T>> remain_state_ = curr_state_;
unsigned j = 0;
for (unsigned i = 0; i < remain_state_.size(); i++) {
if (base_index[j] == i) {
remain_state_[i] = remain_state_[i] * sqrt(1 - gate.damping_coeff_) / sqrt(1 - prob_);
j++;
} else {
remain_state_[i] = remain_state_[i] / sqrt(1 - prob_);
}
}
Projectq::SetState(remain_state_);
}
} else {
Projectq::apply_controlled_gate(MCast<T>(gate.base_matrix_.matrix_), VCast(gate.obj_qubits_),
VCast(gate.ctrl_qubits_));
}
}
void ApplyGate(const BasicGate<T> &gate, const ParameterResolver<T> &pr, bool diff = false) {
T theta = gate.params_.Combination(pr).const_value;
if (diff) {
Projectq::apply_controlled_gate(MCast<T>(gate.param_diff_matrix_(theta).matrix_), VCast(gate.obj_qubits_),
VCast(gate.ctrl_qubits_));
if (gate.ctrl_qubits_.size() != 0) {
auto ctrl_mask = GetControlMask(gate.ctrl_qubits_);
#pragma omp parallel for schedule(static)
for (Index i = 0; i < (len_ >> 1); i++) {
if ((i & ctrl_mask) != ctrl_mask) {
this->vec_[2 * i] = 0;
this->vec_[2 * i + 1] = 0;
}
}
}
} else {
Projectq::apply_controlled_gate(MCast<T>(gate.param_matrix_(theta).matrix_), VCast(gate.obj_qubits_),
VCast(gate.ctrl_qubits_));
}
}
unsigned ApplyMeasure(const BasicGate<T> &gate) {
run();
auto qubit = gate.obj_qubits_[0];
auto mask = (1UL << qubit);
calc_type zero_amps = 0;
// #pragma omp parallel for schedule(static) reduction(+ : zero_amps)
for (unsigned i = 0; i < (len_ >> 1); i++) {
if ((i & mask) == 0) {
zero_amps += vec_[2 * i] * vec_[2 * i] + vec_[2 * i + 1] * vec_[2 * i + 1];
}
}
unsigned collapse = (static_cast<unsigned>(rng_() > zero_amps) << qubit);
auto norm = (collapse == 0) ? sqrt(zero_amps) : sqrt(1 - zero_amps);
#pragma omp parallel for schedule(static)
for (omp::idx_t i = 0; i < (len_ >> 1); i++) {
if ((i & mask) == collapse) {
vec_[2 * i] /= norm;
vec_[2 * i + 1] /= norm;
} else {
vec_[2 * i] = 0;
vec_[2 * i + 1] = 0;
}
}
return (collapse >> qubit);
}
void ApplyCircuit(const VT<BasicGate<T>> &circ) {
for (auto &gate : circ) {
Projectq::ApplyGate(gate);
}
Projectq::run();
}
void ApplyCircuit(const VT<BasicGate<T>> &circ, const ParameterResolver<T> &pr) {
for (auto &gate : circ) {
if (gate.parameterized_) {
Projectq::ApplyGate(gate, pr);
} else {
Projectq::ApplyGate(gate);
}
}
Projectq::run();
}
VT<unsigned> Sampling(const VT<BasicGate<T>> &circ, const ParameterResolver<T> &pr, size_t shots,
const MST<size_t> &key_map, unsigned seed) {
auto key_size = key_map.size();
VT<unsigned> res(shots * key_size);
RndEngine rnd_eng = RndEngine(seed);
std::uniform_real_distribution<double> dist(1.0, (1 << 20) * 1.0);
std::function<double()> rng = std::bind(dist, std::ref(rnd_eng));
for (size_t i = 0; i < shots; i++) {
Projectq<T> sim = Projectq<T>(static_cast<unsigned>(rng()), n_qubits_, vec_);
auto res0 = sim.ApplyCircuitWithMeasure(circ, pr, key_map);
for (size_t j = 0; j < key_size; j++) {
res[i * key_size + j] = res0[j];
}
}
return res;
}
VT<unsigned> ApplyCircuitWithMeasure(const VT<BasicGate<T>> &circ, const ParameterResolver<T> &pr,
const MST<size_t> &key_map) {
auto key_size = key_map.size();
VT<unsigned> res(key_size);
for (auto &gate : circ) {
if (gate.is_measure_) {
auto collapse = ApplyMeasure(gate);
res[key_map.at(gate.name_)] = collapse;
} else if (gate.parameterized_) {
ApplyGate(gate, pr);
} else {
ApplyGate(gate);
}
}
return res;
}
void ApplyHamiltonian(const Hamiltonian<T> &ham) {
Projectq::run();
if (ham.how_to_ == ORIGIN) {
Projectq::apply_qubit_operator(HCast<T>(ham.ham_), Projectq::ordering_);
} else if (ham.how_to_ == BACKEND) {
Projectq::vec_ = sparse::Csr_Dot_Vec<T, double>(ham.ham_sparse_main_, ham.ham_sparse_second_,
Projectq::vec_);
} else {
Projectq::vec_ = sparse::Csr_Dot_Vec<T, double>(ham.ham_sparse_main_, Projectq::vec_);
}
}
VT<CT<T>> RightSizeGrad(calc_type *left_vec, calc_type *right_vec, const Hamiltonian<T> &ham,
const VT<BasicGate<T>> &circ, const VT<BasicGate<T>> &herm_circ,
const ParameterResolver<T> &pr, const MST<size_t> &p_map) {
VT<CT<T>> f_g(p_map.size() + 1, 0);
Projectq<T> sim_left = Projectq<T>(this->seed, n_qubits_, left_vec);
sim_left.ApplyHamiltonian(ham);
f_g[0] = ComplexInnerProduct<T, calc_type>(sim_left.vec_, right_vec, static_cast<Index>(len_));
Projectq<T> sim_right = Projectq<T>(this->seed, n_qubits_, right_vec);
Projectq<T> sim_right_tmp = Projectq<T>(this->seed, n_qubits_);
for (size_t j = 0; j < circ.size(); j++) {
if ((!herm_circ[j].parameterized_)
|| (herm_circ[j].params_.data_.size() == herm_circ[j].params_.no_grad_parameters_.size())) {
if (herm_circ[j].parameterized_) {
sim_left.ApplyGate(herm_circ[j], pr, false);
sim_right.ApplyGate(herm_circ[j], pr, false);
} else {
sim_left.ApplyGate(herm_circ[j]);
sim_right.ApplyGate(herm_circ[j]);
}
} else {
sim_right.ApplyGate(herm_circ[j], pr, false);
sim_right.run();
sim_right_tmp.set_wavefunction(sim_right.vec_, ordering_);
sim_right_tmp.ApplyGate(circ[circ.size() - j - 1], pr, true);
sim_right_tmp.run();
sim_left.run();
CT<T> gi = 0;
if (herm_circ[j].ctrl_qubits_.size() == 0) {
gi = ComplexInnerProduct<T, calc_type>(sim_left.vec_, sim_right_tmp.vec_, static_cast<Index>(len_));
} else {
gi = ComplexInnerProductWithControl<T, calc_type>(sim_left.vec_, sim_right_tmp.vec_,
static_cast<Index>(len_),
GetControlMask(herm_circ[j].ctrl_qubits_));
}
for (auto &it : herm_circ[j].params_.GetRequiresGradParameters()) {
f_g[1 + p_map.at(it)] += circ[circ.size() - j - 1].params_.data_.at(it) * gi;
}
sim_left.ApplyGate(herm_circ[j], pr, false);
}
}
return f_g;
}
CT<T> GetExpectation(const Hamiltonian<T> &ham) {
Projectq<T> sim = Projectq<T>(this->seed, n_qubits_, vec_);
sim.ApplyHamiltonian(ham);
auto out = ComplexInnerProduct<T, calc_type>(sim.vec_, vec_, static_cast<Index>(len_));
return out;
}
VT<VT<CT<T>>> HermitianMeasureWithGrad(const VT<Hamiltonian<T>> &hams, const VT<BasicGate<T>> &circ,
const VT<BasicGate<T>> &herm_circ, const ParameterResolver<T> &pr,
const MST<size_t> &p_map, size_t mea_threads) {
auto n_hams = hams.size();
auto n_params = pr.data_.size();
VT<VT<CT<T>>> output;
for (size_t i = 0; i < n_hams; i++) {
output.push_back({});
for (size_t j = 0; j < n_params + 1; j++) {
output[i].push_back({0, 0});
}
}
Projectq<T> sim = Projectq<T>(this->seed, n_qubits_, vec_);
sim.ApplyCircuit(circ, pr);
if (n_hams == 1) {
auto f_g = sim.RightSizeGrad(sim.vec_, sim.vec_, hams[0], circ, herm_circ, pr, p_map);
for (size_t g = 1; g < n_params + 1; g++) {
f_g[g] += std::conj(f_g[g]);
}
output[0] = f_g;
} else {
std::vector<std::thread> tasks;
tasks.reserve(mea_threads);
size_t end = 0;
size_t offset = n_hams / mea_threads;
size_t left = n_hams % mea_threads;
for (size_t i = 0; i < mea_threads; ++i) {
size_t start = end;
end = start + offset;
if (i < left) {
end += 1;
}
auto task = [&, start, end]() {
for (size_t n = start; n < end; n++) {
auto f_g = sim.RightSizeGrad(sim.vec_, sim.vec_, hams[n], circ, herm_circ, pr, p_map);
for (size_t g = 1; g < n_params + 1; g++) {
f_g[g] += std::conj(f_g[g]);
}
output[n] = f_g;
}
};
tasks.emplace_back(task);
}
for (auto &t : tasks) {
t.join();
}
}
return output;
}
VT<VT<VT<CT<T>>>> HermitianMeasureWithGrad(const VT<Hamiltonian<T>> &hams, const VT<BasicGate<T>> &circ,
const VT<BasicGate<T>> &herm_circ, const VVT<T> &enc_data,
const VT<T> &ans_data, const VS &enc_name, const VS &ans_name,
size_t batch_threads, size_t mea_threads) {
auto n_hams = hams.size();
auto n_prs = enc_data.size();
auto n_params = enc_name.size() + ans_name.size();
VT<VT<VT<CT<T>>>> output;
for (size_t i = 0; i < n_prs; i++) {
output.push_back({});
for (size_t j = 0; j < n_hams; j++) {
output[i].push_back({});
for (size_t k = 0; k < n_params + 1; k++) {
output[i][j].push_back({0, 0});
}
}
}
MST<size_t> p_map;
for (size_t i = 0; i < enc_name.size(); i++) {
p_map[enc_name[i]] = i;
}
for (size_t i = 0; i < ans_name.size(); i++) {
p_map[ans_name[i]] = i + enc_name.size();
}
if (n_prs == 1) {
ParameterResolver<T> pr = ParameterResolver<T>();
pr.SetItems(enc_name, enc_data[0]);
pr.SetItems(ans_name, ans_data);
output[0] = HermitianMeasureWithGrad(hams, circ, herm_circ, pr, p_map, mea_threads);
} else {
std::vector<std::thread> tasks;
tasks.reserve(batch_threads);
size_t end = 0;
size_t offset = n_prs / batch_threads;
size_t left = n_prs % batch_threads;
for (size_t i = 0; i < batch_threads; ++i) {
size_t start = end;
end = start + offset;
if (i < left) {
end += 1;
}
auto task = [&, start, end]() {
for (size_t n = start; n < end; n++) {
ParameterResolver<T> pr = ParameterResolver<T>();
pr.SetItems(enc_name, enc_data[n]);
pr.SetItems(ans_name, ans_data);
auto f_g = HermitianMeasureWithGrad(hams, circ, herm_circ, pr, p_map, mea_threads);
output[n] = f_g;
}
};
tasks.emplace_back(task);
}
for (auto &t : tasks) {
t.join();
}
}
return output;
}
VT<VT<CT<T>>> NonHermitianMeasureWithGrad(const VT<Hamiltonian<T>> &hams, const VT<Hamiltonian<T>> &herm_hams,
const VT<BasicGate<T>> &left_circ, const VT<BasicGate<T>> &herm_left_circ,
const VT<BasicGate<T>> &right_circ,
const VT<BasicGate<T>> &herm_right_circ, const ParameterResolver<T> &pr,
const MST<size_t> &p_map, size_t mea_threads, const StateVector varphi) {
auto n_hams = hams.size();
auto n_params = pr.data_.size();
VT<VT<CT<T>>> output;
for (size_t i = 0; i < n_hams; i++) {
output.push_back({});
for (size_t j = 0; j < n_params + 1; j++) {
output[i].push_back({0, 0});
}
}
Projectq<T> sim = Projectq<T>(this->seed, n_qubits_, vec_);
sim.ApplyCircuit(right_circ, pr);
Projectq<T> sim2 = Projectq<T>(this->seed, n_qubits_, varphi);
sim2.ApplyCircuit(left_circ, pr);
if (n_hams == 1) {
auto f_g1 = sim2.RightSizeGrad(sim.vec_, sim2.vec_, hams[0], left_circ, herm_left_circ, pr, p_map);
auto f_g2 = sim.RightSizeGrad(sim2.vec_, sim.vec_, herm_hams[0], right_circ, herm_right_circ, pr, p_map);
for (size_t g = 1; g < n_params + 1; g++) {
f_g2[g] += std::conj(f_g1[g]);
}
output[0] = f_g2;
} else {
std::vector<std::thread> tasks;
tasks.reserve(mea_threads);
size_t end = 0;
size_t offset = n_hams / mea_threads;
size_t left = n_hams % mea_threads;
for (size_t i = 0; i < mea_threads; i++) {
size_t start = end;
end = start + offset;
if (i < left) {
end += 1;
}
auto task = [&, start, end]() {
for (size_t n = start; n < end; n++) {
auto f_g1 = sim2.RightSizeGrad(sim.vec_, sim2.vec_, hams[n], left_circ, herm_left_circ, pr,
p_map);
auto f_g2 = sim.RightSizeGrad(sim2.vec_, sim.vec_, herm_hams[n], right_circ, herm_right_circ,
pr, p_map);
for (size_t g = 1; g < n_params + 1; g++) {
f_g2[g] += std::conj(f_g1[g]);
}
output[n] = f_g2;
}
};
tasks.emplace_back(task);
}
for (auto &t : tasks) {
t.join();
}
}
return output;
}
VT<VT<VT<CT<T>>>> NonHermitianMeasureWithGrad(
const VT<Hamiltonian<T>> &hams, const VT<Hamiltonian<T>> &herm_hams, const VT<BasicGate<T>> &left_circ,
const VT<BasicGate<T>> &herm_left_circ, const VT<BasicGate<T>> &right_circ,
const VT<BasicGate<T>> &herm_right_circ, const VVT<T> &enc_data, const VT<T> &ans_data, const VS &enc_name,
const VS &ans_name, size_t batch_threads, size_t mea_threads, const Projectq<T> &simulator_left) {
StateVector varphi = simulator_left.vec_;
auto n_hams = hams.size();
auto n_prs = enc_data.size();
auto n_params = enc_name.size() + ans_name.size();
VT<VT<VT<CT<T>>>> output;
for (size_t i = 0; i < n_prs; i++) {
output.push_back({});
for (size_t j = 0; j < n_hams; j++) {
output[i].push_back({});
for (size_t k = 0; k < n_params + 1; k++) {
output[i][j].push_back({0, 0});
}
}
}
MST<size_t> p_map;
for (size_t i = 0; i < enc_name.size(); i++) {
p_map[enc_name[i]] = i;
}
for (size_t i = 0; i < ans_name.size(); i++) {
p_map[ans_name[i]] = i + enc_name.size();
}
if (n_prs == 1) {
ParameterResolver<T> pr = ParameterResolver<T>();
pr.SetItems(enc_name, enc_data[0]);
pr.SetItems(ans_name, ans_data);
output[0] = NonHermitianMeasureWithGrad(hams, herm_hams, left_circ, herm_left_circ, right_circ,
herm_right_circ, pr, p_map, mea_threads, varphi);
} else {
std::vector<std::thread> tasks;
tasks.reserve(batch_threads);
size_t end = 0;
size_t offset = n_prs / batch_threads;
size_t left = n_prs % batch_threads;
for (size_t i = 0; i < batch_threads; ++i) {
size_t start = end;
end = start + offset;
if (i < left) {
end += 1;
}
auto task = [&, start, end]() {
for (size_t n = start; n < end; n++) {
ParameterResolver<T> pr = ParameterResolver<T>();
pr.SetItems(enc_name, enc_data[n]);
pr.SetItems(ans_name, ans_data);
auto f_g = NonHermitianMeasureWithGrad(hams, herm_hams, left_circ, herm_left_circ, right_circ,
herm_right_circ, pr, p_map, mea_threads, varphi);
output[n] = f_g;
}
};
tasks.emplace_back(task);
}
for (auto &t : tasks) {
t.join();
}
}
return output;
}
void PrintInfo() const {
std::cout << n_qubits_ << " qubits simulator with currently quantum state at:" << std::endl;
for (unsigned i = 0; i < (len_ >> 1); i++) {
std::cout << "(" << vec_[2 * i] << ", " << vec_[2 * i + 1] << ")" << std::endl;
}
}
VVT<CT<calc_type>> GetCircuitMatrix(const VT<BasicGate<T>> &circ, const ParameterResolver<T> &pr) {
VVT<CT<calc_type>> out((1 << n_qubits_));
#pragma omp parallel for schedule(static)
for (omp::idx_t i = 0; i < (1UL << n_qubits_); i++) {
Projectq<T> sim = Projectq<T>(this->seed, n_qubits_);
sim.vec_[0] = 0;
sim.vec_[2 * i] = 1;
sim.ApplyCircuit(circ, pr);
out[i] = sim.cheat();
}
return out;
}
auto GetLen() const {
return this->len_;
}
std::shared_ptr<Projectq<T>> Copy() {
return std::make_shared<Projectq<T>>(this->seed, n_qubits_, vec_);
}
};
template <typename T>
CT<T> InnerProduct(const Projectq<T> &bra, const Projectq<T> &ket) {
auto res = ComplexInnerProduct<T, Simulator::calc_type>(bra.vec_, ket.vec_, bra.GetLen());
return res;
}
} // namespace projectq
} // namespace mindquantum
#endif // MINDQUANTUM_BACKENDS_PROJECTQ_PROJECTQ_H_
|
layerramdistancetransform.h | /*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017-2020 Inviwo Foundation
* 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 OWNER 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 IVW_LAYERRAMDISTANCETRANSFORM_H
#define IVW_LAYERRAMDISTANCETRANSFORM_H
#include <modules/base/basemoduledefine.h>
#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/util/indexmapper.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/datastructures/image/layerramprecision.h>
#ifdef IVW_USE_OPENMP
#include <omp.h>
#endif
namespace inviwo {
namespace util {
/**
* Implementation of Euclidean Distance Transform according to Saito's algorithm:
* T. Saito and J.I. Toriwaki. New algorithms for Euclidean distance transformations
* of an n-dimensional digitized picture with applications. Pattern Recognition, 27(11).
* pp. 1551-1565, 1994.
* http://www.cs.jhu.edu/~misha/ReadingSeminar/Papers/Saito94.pdf
*
* Calculates the distance in base mat space
* * Predicate is a function of type (const T &value) -> bool to deside if a value in the input
* is a "feature".
* * ValueTransform is a function of type (const U& squaredDist) -> U that is appiled to all
* squared distance values at the end of the calculation.
* * ProcessCallback is a function of type (double progress) -> void that is called with a value
* from 0 to 1 to indicate the progress of the calculation.
*/
template <typename T, typename U, typename Predicate, typename ValueTransform,
typename ProgressCallback>
void layerRAMDistanceTransform(const LayerRAMPrecision<T> *inLayer,
LayerRAMPrecision<U> *outDistanceField, const Matrix<2, U> basis,
const size2_t upsample, Predicate predicate,
ValueTransform valueTransform, ProgressCallback callback);
template <typename T, typename U>
void layerRAMDistanceTransform(const LayerRAMPrecision<T> *inVolume,
LayerRAMPrecision<U> *outDistanceField, const Matrix<2, U> basis,
const size2_t upsample);
template <typename U, typename Predicate, typename ValueTransform, typename ProgressCallback>
void layerDistanceTransform(const Layer *inLayer, LayerRAMPrecision<U> *outDistanceField,
const size2_t upsample, Predicate predicate,
ValueTransform valueTransform, ProgressCallback callback);
template <typename U, typename ProgressCallback>
void layerDistanceTransform(const Layer *inLayer, LayerRAMPrecision<U> *outDistanceField,
const size2_t upsample, double threshold, bool normalize, bool flip,
bool square, double scale, ProgressCallback callback);
template <typename U>
void layerDistanceTransform(const Layer *inLayer, LayerRAMPrecision<U> *outDistanceField,
const size2_t upsample, double threshold, bool normalize, bool flip,
bool square, double scale);
} // namespace util
template <typename T, typename U, typename Predicate, typename ValueTransform,
typename ProgressCallback>
void util::layerRAMDistanceTransform(const LayerRAMPrecision<T> *inLayer,
LayerRAMPrecision<U> *outDistanceField,
const Matrix<2, U> basis, const size2_t upsample,
Predicate predicate, ValueTransform valueTransform,
ProgressCallback callback) {
#ifdef IVW_USE_OPENMP
omp_set_num_threads(std::thread::hardware_concurrency());
#endif
using int64 = glm::int64;
auto square = [](auto a) { return a * a; };
callback(0.0);
const T *src = inLayer->getDataTyped();
U *dst = outDistanceField->getDataTyped();
const i64vec2 srcDim{inLayer->getDimensions()};
const i64vec2 dstDim{outDistanceField->getDimensions()};
const i64vec2 sm{upsample};
const auto squareBasis = glm::transpose(basis) * basis;
const Vector<2, U> squareBasisDiag{squareBasis[0][0], squareBasis[1][1]};
const Vector<2, U> squareVoxelSize{squareBasisDiag / Vector<2, U>{dstDim * dstDim}};
const Vector<2, U> invSquareVoxelSize{Vector<2, U>{1.0f} / squareVoxelSize};
{
const auto maxdist = glm::compMax(squareBasisDiag);
bool orthogonal = true;
for (size_t i = 0; i < squareBasis.length(); i++) {
for (size_t j = 0; j < squareBasis.length(); j++) {
if (i != j) {
if (std::abs(squareBasis[i][j]) > 10.0e-8 * maxdist) {
orthogonal = false;
break;
}
}
}
}
if (!orthogonal) {
LogWarnCustom(
"layerRAMDistanceTransform",
"Calculating the distance transform on a non-orthogonal layer will not give "
"correct values");
}
}
if (srcDim * sm != dstDim) {
throw Exception(
"DistanceTransformRAM: Dimensions does not match src = " + toString(srcDim) +
" dst = " + toString(dstDim) + " scaling = " + toString(sm),
IVW_CONTEXT_CUSTOM("layerRAMDistanceTransform"));
}
util::IndexMapper<2, int64> srcInd(srcDim);
util::IndexMapper<2, int64> dstInd(dstDim);
auto is_feature = [&](const int64 x, const int64 y) {
return predicate(src[srcInd(x / sm.x, y / sm.y)]);
};
// first pass, forward and backward scan along x
// result: min distance in x direction
#pragma omp parallel for
for (int64 y = 0; y < dstDim.y; ++y) {
// forward
U dist = static_cast<U>(dstDim.x);
for (int64 x = 0; x < dstDim.x; ++x) {
if (!is_feature(x, y)) {
++dist;
} else {
dist = U(0);
}
dst[dstInd(x, y)] = squareVoxelSize.x * square(dist);
}
// backward
dist = static_cast<U>(dstDim.x);
for (int64 x = dstDim.x - 1; x >= 0; --x) {
if (!is_feature(x, y)) {
++dist;
} else {
dist = U(0);
}
dst[dstInd(x, y)] = std::min<U>(dst[dstInd(x, y)], squareVoxelSize.x * square(dist));
}
}
// second pass, scan y direction
// for each voxel v(x,y,z) find min_i(data(x,i,z) + (y - i)^2), 0 <= i < dimY
// result: min distance in x and y direction
callback(0.45);
#pragma omp parallel
{
std::vector<U> buff;
buff.resize(dstDim.y);
#pragma omp for
for (int64 x = 0; x < dstDim.x; ++x) {
// cache column data into temporary buffer
for (int64 y = 0; y < dstDim.y; ++y) {
buff[y] = dst[dstInd(x, y)];
}
for (int64 y = 0; y < dstDim.y; ++y) {
auto d = buff[y];
if (d != U(0)) {
const auto rMax = static_cast<int64>(std::sqrt(d * invSquareVoxelSize.y)) + 1;
const auto rStart = std::min(rMax, y - 1);
const auto rEnd = std::min(rMax, dstDim.y - y);
for (int64 n = -rStart; n < rEnd; ++n) {
const auto w = buff[y + n] + squareVoxelSize.y * square(n);
if (w < d) d = w;
}
}
dst[dstInd(x, y)] = d;
}
}
}
// scale data
callback(0.9);
const int64 layerSize = dstDim.x * dstDim.y;
#pragma omp parallel for
for (int64 i = 0; i < layerSize; ++i) {
dst[i] = valueTransform(dst[i]);
}
callback(1.0);
}
template <typename T, typename U>
void util::layerRAMDistanceTransform(const LayerRAMPrecision<T> *inLayer,
LayerRAMPrecision<U> *outDistanceField,
const Matrix<2, U> basis, const size2_t upsample) {
util::layerRAMDistanceTransform(
inLayer, outDistanceField, basis, upsample,
[](const T &val) { return util::glm_convert_normalized<double>(val) > 0.5; },
[](const U &squareDist) {
return static_cast<U>(std::sqrt(static_cast<double>(squareDist)));
},
[](double f) {});
}
template <typename U, typename Predicate, typename ValueTransform, typename ProgressCallback>
void util::layerDistanceTransform(const Layer *inLayer, LayerRAMPrecision<U> *outDistanceField,
const size2_t upsample, Predicate predicate,
ValueTransform valueTransform, ProgressCallback callback) {
const auto inputLayerRep = inLayer->getRepresentation<LayerRAM>();
inputLayerRep->dispatch<void, dispatching::filter::Scalars>([&](const auto lrprecision) {
layerRAMDistanceTransform(lrprecision, outDistanceField, inLayer->getBasis(), upsample,
predicate, valueTransform, callback);
});
}
template <typename U, typename ProgressCallback>
void util::layerDistanceTransform(const Layer *inLayer, LayerRAMPrecision<U> *outDistanceField,
const size2_t upsample, double threshold, bool normalize,
bool flip, bool square, double scale, ProgressCallback progress) {
const auto inputLayerRep = inLayer->getRepresentation<LayerRAM>();
inputLayerRep->dispatch<void, dispatching::filter::Scalars>([&](const auto lrprecision) {
using ValueType = util::PrecisionValueType<decltype(lrprecision)>;
const auto predicateIn = [threshold](const ValueType &val) { return val < threshold; };
const auto predicateOut = [threshold](const ValueType &val) { return val > threshold; };
const auto normPredicateIn = [threshold](const ValueType &val) {
return util::glm_convert_normalized<double>(val) < threshold;
};
const auto normPredicateOut = [threshold](const ValueType &val) {
return util::glm_convert_normalized<double>(val) > threshold;
};
const auto valTransIdent = [scale](const float &squareDist) {
return static_cast<float>(scale * squareDist);
};
const auto valTransSqrt = [scale](const float &squareDist) {
return static_cast<float>(scale * std::sqrt(squareDist));
};
if (normalize && square && flip) {
util::layerRAMDistanceTransform(lrprecision, outDistanceField, inLayer->getBasis(),
upsample, normPredicateIn, valTransIdent, progress);
} else if (normalize && square && !flip) {
util::layerRAMDistanceTransform(lrprecision, outDistanceField, inLayer->getBasis(),
upsample, normPredicateOut, valTransIdent, progress);
} else if (normalize && !square && flip) {
util::layerRAMDistanceTransform(lrprecision, outDistanceField, inLayer->getBasis(),
upsample, normPredicateIn, valTransSqrt, progress);
} else if (normalize && !square && !flip) {
util::layerRAMDistanceTransform(lrprecision, outDistanceField, inLayer->getBasis(),
upsample, normPredicateOut, valTransSqrt, progress);
} else if (!normalize && square && flip) {
util::layerRAMDistanceTransform(lrprecision, outDistanceField, inLayer->getBasis(),
upsample, predicateIn, valTransIdent, progress);
} else if (!normalize && square && !flip) {
util::layerRAMDistanceTransform(lrprecision, outDistanceField, inLayer->getBasis(),
upsample, predicateOut, valTransIdent, progress);
} else if (!normalize && !square && flip) {
util::layerRAMDistanceTransform(lrprecision, outDistanceField, inLayer->getBasis(),
upsample, predicateIn, valTransSqrt, progress);
} else if (!normalize && !square && !flip) {
util::layerRAMDistanceTransform(lrprecision, outDistanceField, inLayer->getBasis(),
upsample, predicateOut, valTransSqrt, progress);
}
});
}
template <typename U>
void util::layerDistanceTransform(const Layer *inLayer, LayerRAMPrecision<U> *outDistanceField,
const size2_t upsample, double threshold, bool normalize,
bool flip, bool square, double scale) {
util::layerDistanceTransform(inLayer, outDistanceField, upsample, threshold, normalize, flip,
square, scale, [](double) {});
}
} // namespace inviwo
#endif // IVW_LAYERRAMDISTANCETRANSFORM_H
|
pyfr_gemm_rm.c | /******************************************************************************
** Copyright (c) 2016-2018, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. Redistributions in binary form must reproduce the above copyright **
** notice, this list of conditions and the following disclaimer in the **
** documentation and/or other materials provided with the distribution. **
** 3. Neither the name of the copyright holder nor the names of its **
** contributors may be used to endorse or promote products derived **
** from this software without specific prior written permission. **
** **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **
******************************************************************************/
/* Alexander Heinecke (Intel Corp.)
******************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <mkl.h>
#include <libxsmm.h>
static double sec(struct timeval start, struct timeval end) {
return ((double)(((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)))) / 1.0e6;
}
int main(int argc, char *argv[])
{
int n,m,k;
int lda,ldb,ldc;
double* a;
double* b;
double* c1;
double* c2;
struct timeval l_start, l_end;
double l_total = 0.0;
int reps, i, j;
const int nblock = 16;
double alpha = 1.0, beta = 1.0;
char transa = 'N', transb = 'N';
libxsmm_gemm_prefetch_type l_prefetch_op = LIBXSMM_PREFETCH_NONE;
libxsmm_dmmfunction kernel = NULL;
if (argc != 5) {
fprintf(stderr, "Invalid ./a,out M N K reps\n");
exit(-1);
}
m = atoi(argv[1]);
n = atoi(argv[2]);
k = atoi(argv[3]);
reps = atoi(argv[4]);
/* this is col-major what you want to use for the sizes in question */
lda = k;
ldb = n;
ldc = n;
if (n % nblock != 0) {
fprintf(stderr, "N needs to be divisable by %i\n", nblock);
exit(-1);
}
a = (double*)_mm_malloc(lda*m*sizeof(double), 64);
b = (double*)_mm_malloc(ldb*k*sizeof(double), 64);
c1 = (double*)_mm_malloc(ldc*m*sizeof(double), 64);
c2 = (double*)_mm_malloc(ldc*m*sizeof(double), 64);
#pragma omp parallel for
for (i = 0; i < lda*m; i++) {
a[i] = libxsmm_rand_f64();
}
#pragma omp parallel for
for (i = 0; i < ldb*k; i++) {
b[i] = libxsmm_rand_f64();
}
#pragma omp parallel for
for (i = 0; i < ldc*m; i++) {
c1[i] = 0;
c2[i] = 0;
}
/* JIT Kernel */
kernel = libxsmm_dmmdispatch(nblock, m, k, &ldb, &lda, &ldc, NULL, NULL, NULL, &l_prefetch_op );
if (kernel == 0) {
printf("JIT failed, exiting\n");
exit(-1);
}
/* init MKL */
dgemm(&transb, &transa, &n, &m, &k, &alpha, b, &ldb, a, &lda, &beta, c1, &ldc);
#pragma omp parallel for
for (i = 0; i < ldc*m; i++) {
c1[i] = 0;
c2[i] = 0;
}
gettimeofday(&l_start, NULL);
for ( j = 0; j < reps; j++ ) {
dgemm(&transb, &transa, &n, &m, &k, &alpha, b, &ldb, a, &lda, &beta, c1, &ldc);
}
gettimeofday(&l_end, NULL);
l_total = sec(l_start, l_end);
fprintf(stdout, "time[s] MKL (RM, M=%i, N=%i, K=%i): %f\n", m, n, k, l_total/(double)reps );
fprintf(stdout, "GFLOPS MKL (RM, M=%i, N=%i, K=%i): %f\n", m, n, k, (2.0 * (double)m * (double)n * (double)k * (double)reps * 1.0e-9) / l_total );
fprintf(stdout, "GB/s MKL (RM, M=%i, N=%i, K=%i): %f\n", m, n, k, ((double)sizeof(double) * (((double)m * (double)n) + ((double)k * (double)n)) * (double)reps * 1.0e-9) / l_total );
gettimeofday(&l_start, NULL);
for ( j = 0; j < reps; j++ ) {
#pragma omp parallel for private(i)
for ( i = 0; i < n; i+=nblock) {
kernel( b+i, a, c2+i, NULL, NULL, NULL );
}
gettimeofday(&l_end, NULL);
}
l_total = sec(l_start, l_end);
fprintf(stdout, "time[s] libxsmm (RM, M=%i, N=%i, K=%i): %f\n", m, n, k, l_total/(double)reps );
fprintf(stdout, "GFLOPS libxsmm (RM, M=%i, N=%i, K=%i): %f\n", m, n, k, (2.0 * (double)m * (double)n * (double)k * (double)reps * 1.0e-9) / l_total );
fprintf(stdout, "GB/s libxsmm (RM, M=%i, N=%i, K=%i): %f\n", m, n, k, ((double)sizeof(double) * (((double)m * (double)n) + ((double)k * (double)n)) * (double)reps * 1.0e-9) / l_total );
/* test result */
double max_error = 0.0;
for ( i = 0; i < ldc*m; i++) {
if (max_error < fabs(c1[i] - c2[i])) {
max_error = fabs(c1[i] - c2[i]);
}
}
printf("max error: %f\n\n", max_error);
}
|
multiplications.c | /*
This source file is part of the Geophysical Fluids Modeling Framework (GAME), which is released under the MIT license.
Github repository: https://github.com/OpenNWP/GAME
*/
/*
In this file, algebraic multiplications of fields are collected.
*/
#include <stdio.h>
#include "../game_types.h"
#include "spatial_operators.h"
#include "../thermodynamics/thermodynamics.h"
int scalar_times_scalar(Scalar_field in_field_0, Scalar_field in_field_1, Scalar_field out_field)
{
#pragma omp parallel for
for (int i = 0; i < NO_OF_SCALARS; ++i)
{
out_field[i] = in_field_0[i]*in_field_1[i];
}
return 0;
}
int vector_times_vector(Vector_field in_field_0, Vector_field in_field_1, Vector_field out_field)
{
#pragma omp parallel for
for (int i = 0; i < NO_OF_VECTORS; ++i)
{
out_field[i] = in_field_0[i]*in_field_1[i];
}
return 0;
}
int scalar_times_vector(Scalar_field scalar_field, Vector_field vector_field, Vector_field out_field, Grid *grid)
{
/*
This function multiplies the vector field vector_field by the scalar field scalar_field.
*/
scalar_times_vector_h(scalar_field, vector_field, out_field, grid);
scalar_times_vector_v(scalar_field, vector_field, out_field, grid);
return 0;
}
int scalar_times_vector_h(Scalar_field in_field_h, Vector_field vector_field, Vector_field out_field, Grid *grid)
{
int vector_index;
double scalar_value;
#pragma omp parallel for private (vector_index, scalar_value)
for (int h_index = 0; h_index < NO_OF_VECTORS_H; ++h_index)
{
for (int layer_index = 0; layer_index < NO_OF_LAYERS; ++layer_index)
{
vector_index = NO_OF_SCALARS_H + layer_index*NO_OF_VECTORS_PER_LAYER + h_index;
scalar_value
= 0.5*(
in_field_h[grid -> to_index[h_index] + layer_index*NO_OF_SCALARS_H]
+ in_field_h[grid -> from_index[h_index] + layer_index*NO_OF_SCALARS_H]);
out_field[vector_index] = scalar_value*vector_field[vector_index];
}
}
return 0;
}
int scalar_times_vector_v(Scalar_field in_field_v, Vector_field vector_field, Vector_field out_field, Grid *grid)
{
int i, lower_index, upper_index;
double scalar_value;
#pragma omp parallel for private (i, lower_index, upper_index, scalar_value)
for (int h_index = 0; h_index < NO_OF_SCALARS_H; ++h_index)
{
for (int layer_index = 1; layer_index < NO_OF_LAYERS; ++layer_index)
{
i = layer_index*NO_OF_VECTORS_PER_LAYER + h_index;
lower_index = h_index + layer_index*NO_OF_SCALARS_H;
upper_index = h_index + (layer_index - 1)*NO_OF_SCALARS_H;
scalar_value = 0.5*(
in_field_v[upper_index]
+ in_field_v[lower_index]);
out_field[i] = scalar_value*vector_field[i];
}
}
return 0;
}
|
MinMax.h | #ifndef DDM__ALGORITHM__MIN_MAX_H__
#define DDM__ALGORITHM__MIN_MAX_H__
#include "../../ddm/internal/Config.h"
#include "../../ddm/Allocator.h"
#include "../../ddm/algorithm/LocalRange.h"
#include "../../ddm/util/Config.h"
#include "../../ddm/util/Trace.h"
#include "../../ddm/util/UnitLocality.h"
#include "../../ddm/iterator/GlobIter.h"
#include "../../ddm/internal/Logging.h"
#include <algorithm>
#include <memory>
#ifdef DDM_ENABLE_OPENMP
#include <omp.h>
#endif
namespace ddm {
/**
* Finds an iterator pointing to the element with the smallest value in
* the range [first,last).
* Specialization for local range, delegates to std::min_element.
*
* \return An iterator to the first occurrence of the smallest value
* in the range, or \c last if the range is empty.
*
* \tparam ElementType Type of the elements in the sequence
* \tparam Compare Binary comparison function with signature
* \c bool (const TypeA &a, const TypeB &b)
*
* \complexity O(d) + O(nl), with \c d dimensions in the global iterators'
* pattern and \c nl local elements within the global range
*
* \ingroup DDMAlgorithms
*/
template <
class ElementType,
class Compare = std::less<const ElementType &> >
const ElementType * min_element(
/// Iterator to the initial position in the sequence
const ElementType * l_range_begin,
/// Iterator to the final position in the sequence
const ElementType * l_range_end,
/// Element comparison function, defaults to std::less
Compare compare
= std::less<const ElementType &>())
{
#ifdef DDM_ENABLE_OPENMP
ddm::util::UnitLocality uloc;
auto n_threads = uloc.num_domain_threads();
DDM_LOG_DEBUG("ddm::min_element", "thread capacity:", n_threads);
// TODO: Should also restrict on elements/units > ~10240.
// Find a model for the minimum work laod.
if (n_threads > 1) {
auto l_size = l_range_end - l_range_begin;
int min_idx_l = 0;
ElementType min_val_l = *l_range_begin;
typedef struct min_pos_t { ElementType val; size_t idx; } min_pos;
DDM_LOG_DEBUG("ddm::min_element", "local range size:", l_size);
int align_bytes = uloc.cache_line_size(0);
size_t min_vals_t_size = n_threads + 1 +
(align_bytes / sizeof(min_pos));
size_t min_vals_t_bytes = min_vals_t_size * sizeof(min_pos);
min_pos * min_vals_t_raw = new min_pos[min_vals_t_size];
void * min_vals_t_alg = min_vals_t_raw;
min_pos * min_vals_t = static_cast<min_pos *>(
ddm::align(
align_bytes,
sizeof(min_pos),
min_vals_t_alg,
min_vals_t_bytes));
DDM_LOG_TRACE("ddm::min_element", "min * alloc:", min_vals_t_raw);
DDM_LOG_TRACE("ddm::min_element", "min * aligned:", min_vals_t);
DDM_LOG_TRACE("ddm::min_element", "min * size:", min_vals_t_bytes);
DDM_ASSERT_GE(min_vals_t_bytes, n_threads * sizeof(min_pos),
"Aligned buffer of min_pos has insufficient size");
DDM_ASSERT_MSG(nullptr != min_vals_t,
"Aligned allocation of min_pos returned nullptr");
// Cannot use user-defined reduction (OpenMP 4.0) as the compare
// predicate cannot be used in `omp declare reduction`.
// Avoid omp for + omp critical section by using array of
// thread-local minimum values, aligned to prevent false sharing:
int t_id;
#pragma omp parallel num_threads(n_threads) private(t_id)
{
// Documentation of Intel MIC intrinsics, see:
// https://software.intel.com/de-de/node/523533
// https://software.intel.com/de-de/node/523387
t_id = omp_get_thread_num();
DDM_LOG_TRACE("ddm::min_element", "starting thread", t_id);
min_vals_t[t_id].idx = min_idx_l;
min_vals_t[t_id].val = min_val_l;
// Cannot use explicit private(min_val_t) as ElementType might
// not be default-constructible:
#pragma omp for schedule(static)
// #pragma ivdep
// #pragma vector aligned nontemporal
for (int i = 0; i < l_size; i++) {
const ElementType & val_t = *(l_range_begin + i);
if (compare(val_t, min_vals_t[t_id].val)) {
min_vals_t[t_id].val = val_t;
min_vals_t[t_id].idx = i;
}
}
DDM_LOG_TRACE("ddm::min_element", "local minimum at thread", t_id,
"idx:", min_vals_t[t_id].idx,
"val:", min_vals_t[t_id].val);
}
min_pos min_pos_l = min_vals_t[0];
for (int t = 1; t < n_threads; t++) {
const min_pos & mpt = min_vals_t[t];
if (compare(mpt.val, min_pos_l.val)) {
min_pos_l = mpt;
}
}
delete[] min_vals_t_raw;
return (l_range_begin + min_pos_l.idx);
}
#endif // DDM_ENABLE_OPENMP
return ::std::min_element(l_range_begin, l_range_end, compare);
}
/**
* Finds an iterator pointing to the element with the smallest value in
* the range [first,last).
*
* \return An iterator to the first occurrence of the smallest value
* in the range, or \c last if the range is empty.
*
* \tparam ElementType Type of the elements in the sequence
* \tparam Compare Binary comparison function with signature
* \c bool (const TypeA &a, const TypeB &b)
*
* \complexity O(d) + O(nl), with \c d dimensions in the global iterators'
* pattern and \c nl local elements within the global range
*
* \ingroup DDMAlgorithms
*/
template <
class ElementType,
class PatternType,
class Compare = std::less<const ElementType &> >
GlobIter<ElementType, PatternType> min_element(
/// Iterator to the initial position in the sequence
const GlobIter<ElementType, PatternType> & first,
/// Iterator to the final position in the sequence
const GlobIter<ElementType, PatternType> & last,
/// Element comparison function, defaults to std::less
Compare compare
= std::less<const ElementType &>())
{
typedef ddm::GlobIter<ElementType, PatternType> globiter_t;
typedef PatternType pattern_t;
typedef typename pattern_t::index_type index_t;
// return last for empty array
if (first == last) {
DDM_LOG_DEBUG("ddm::min_element >",
"empty range, returning last", last);
return last;
}
ddm::util::Trace trace("min_element");
auto & pattern = first.pattern();
auto & team = pattern.team();
DDM_LOG_DEBUG("ddm::min_element()",
"allocate minarr, size", team.size());
// Global position of end element in range:
auto gi_last = last.gpos();
// Find the local min. element in parallel
// Get local address range between global iterators:
auto local_idx_range = ddm::local_index_range(first, last);
// Pointer to local minimum element:
const ElementType * lmin = nullptr;
// Local offset of local minimum element, or -1 if no element found:
index_t l_idx_lmin = -1;
if (local_idx_range.begin == local_idx_range.end) {
// local range is empty
DDM_LOG_DEBUG("ddm::min_element", "local range empty");
} else {
trace.enter_state("local");
// Pointer to first element in local memory:
const ElementType * lbegin = first.globmem().lbegin();
// Pointers to first / final element in local range:
const ElementType * l_range_begin = lbegin + local_idx_range.begin;
const ElementType * l_range_end = lbegin + local_idx_range.end;
lmin = ddm::min_element(l_range_begin, l_range_end, compare);
if (lmin != l_range_end) {
DDM_LOG_TRACE_VAR("ddm::min_element", *lmin);
// Offset of local minimum in local memory:
l_idx_lmin = lmin - lbegin;
}
trace.exit_state("local");
}
DDM_LOG_TRACE("ddm::min_element",
"local index of local minimum:", l_idx_lmin);
DDM_LOG_TRACE("ddm::min_element",
"waiting for local min of other units");
trace.enter_state("barrier");
team.barrier();
trace.exit_state("barrier");
typedef struct {
ElementType value;
index_t g_index;
} local_min_t;
std::vector<local_min_t> local_min_values(team.size());
// Set global index of local minimum to -1 if no local minimum has been
// found:
local_min_t local_min;
local_min.value = l_idx_lmin < 0
? ElementType()
: *lmin;
local_min.g_index = l_idx_lmin < 0
? -1
: pattern.global(l_idx_lmin);
DDM_LOG_TRACE("ddm::min_element", "sending local minimum: {",
"value:", local_min.value,
"g.index:", local_min.g_index, "}");
DDM_LOG_TRACE("ddm::min_element", "dart_allgather()");
trace.enter_state("allgather");
DDM_ASSERT_RETURNS(
dart_allgather(
&local_min,
local_min_values.data(),
sizeof(local_min_t),
DART_TYPE_BYTE,
team.dart_id()),
DART_OK);
trace.exit_state("allgather");
#ifdef DDM_ENABLE_LOGGING
for (int lmin_u = 0; lmin_u < local_min_values.size(); lmin_u++) {
auto lmin_entry = local_min_values[lmin_u];
DDM_LOG_TRACE("ddm::min_element", "dart_allgather >",
"unit:", lmin_u,
"value:", lmin_entry.value,
"g_index:", lmin_entry.g_index);
}
#endif
auto gmin_elem_it = ::std::min_element(
local_min_values.begin(),
local_min_values.end(),
[&](const local_min_t & a,
const local_min_t & b) {
// Ignore elements with global index -1 (no
// element found):
return (b.g_index < 0 ||
(a.g_index > 0 &&
compare(a.value, b.value)));
});
if (gmin_elem_it == local_min_values.end()) {
DDM_LOG_DEBUG_VAR("ddm::min_element >", last);
return last;
}
auto gi_minimum = gmin_elem_it->g_index;
DDM_LOG_TRACE("ddm::min_element",
"min. value:", gmin_elem_it->value,
"at unit:", (gmin_elem_it - local_min_values.begin()),
"global idx:", gi_minimum);
DDM_LOG_TRACE_VAR("ddm::min_element", gi_minimum);
if (gi_minimum < 0 || gi_minimum == gi_last) {
DDM_LOG_DEBUG_VAR("ddm::min_element >", last);
return last;
}
// iterator 'first' is relative to start of input range, convert to start
// of its referenced container (= container.begin()), then apply global
// offset of minimum element:
globiter_t minimum = (first - first.gpos()) + gi_minimum;
DDM_LOG_DEBUG("ddm::min_element >", minimum,
"=", static_cast<ElementType>(*minimum));
return minimum;
}
/**
* Finds an iterator pointing to the element with the greatest value in
* the range [first,last).
*
* \return An iterator to the first occurrence of the greatest value
* in the range, or \c last if the range is empty.
*
* \tparam ElementType Type of the elements in the sequence
* \tparam Compare Binary comparison function with signature
* \c bool (const TypeA &a, const TypeB &b)
*
* \complexity O(d) + O(nl), with \c d dimensions in the global iterators'
* pattern and \c nl local elements within the global range
*
* \ingroup DDMAlgorithms
*/
template <
class ElementType,
class PatternType,
class Compare = std::greater<const ElementType &> >
GlobIter<ElementType, PatternType> max_element(
/// Iterator to the initial position in the sequence
const GlobIter<ElementType, PatternType> & first,
/// Iterator to the final position in the sequence
const GlobIter<ElementType, PatternType> & last,
/// Element comparison function, defaults to std::less
Compare compare
= std::greater<const ElementType &>())
{
// Same as min_element with different compare function
return ddm::min_element(first, last, compare);
}
/**
* Finds an iterator pointing to the element with the greatest value in
* the range [first,last).
* Specialization for local range, delegates to std::min_element.
*
* \return An iterator to the first occurrence of the greatest value
* in the range, or \c last if the range is empty.
*
* \tparam ElementType Type of the elements in the sequence
* \tparam Compare Binary comparison function with signature
* \c bool (const TypeA &a, const TypeB &b)
*
* \complexity O(d) + O(nl), with \c d dimensions in the global iterators'
* pattern and \c nl local elements within the global range
*
* \ingroup DDMAlgorithms
*/
template <
class ElementType,
class Compare = std::greater<const ElementType &> >
const ElementType * max_element(
/// Iterator to the initial position in the sequence
const ElementType * first,
/// Iterator to the final position in the sequence
const ElementType * last,
/// Element comparison function, defaults to std::less
Compare compare
= std::greater<const ElementType &>())
{
// Same as min_element with different compare function
return ddm::min_element(first, last, compare);
}
} // namespace ddm
#endif // DDM__ALGORITHM__MIN_MAX_H__
|
cpd.c |
/******************************************************************************
* INCLUDES
*****************************************************************************/
#include "base.h"
#include "cpd.h"
#include "matrix.h"
#include "mttkrp.h"
#include "timer.h"
#include "thd_info.h"
#include "util.h"
#include <math.h>
#include <omp.h>
#ifndef __AVX512F__
#define SPLATT_USE_DSYRK
#endif
/******************************************************************************
* API FUNCTIONS
*****************************************************************************/
int splatt_cpd_als(
splatt_csf const * const tensors,
splatt_idx_t const nfactors,
double const * const options,
splatt_kruskal * factored)
{
matrix_t * mats[MAX_NMODES+1];
idx_t nmodes = tensors->nmodes;
rank_info rinfo;
rinfo.rank = 0;
/* allocate factor matrices */
idx_t maxdim = tensors->dims[argmax_elem(tensors->dims, nmodes)];
for(idx_t m=0; m < nmodes; ++m) {
mats[m] = (matrix_t *) mat_rand(tensors[0].dims[m], nfactors);
}
mats[MAX_NMODES] = mat_alloc(maxdim, nfactors);
val_t * lambda = splatt_malloc(nfactors * sizeof(*lambda));
/* do the factorization! */
factored->fit = cpd_als_iterate(tensors, mats, lambda, nfactors, &rinfo,
options);
/* store output */
factored->rank = nfactors;
factored->nmodes = nmodes;
factored->lambda = lambda;
for(idx_t m=0; m < nmodes; ++m) {
factored->dims[m] = tensors->dims[m];
factored->factors[m] = mats[m]->vals;
}
/* clean up */
mat_free(mats[MAX_NMODES]);
for(idx_t m=0; m < nmodes; ++m) {
free(mats[m]); /* just the matrix_t ptr, data is safely in factored */
}
return SPLATT_SUCCESS;
}
void splatt_free_kruskal(
splatt_kruskal * factored)
{
free(factored->lambda);
for(idx_t m=0; m < factored->nmodes; ++m) {
#if SPLATT_MAT_HBW
splatt_hbw_free(factored->factors[m]);
#else
splatt_free(factored->factors[m]);
#endif
}
}
/******************************************************************************
* PRIVATE FUNCTIONS
*****************************************************************************/
/**
* @brief Resets serial and MPI timers that were activated during some CPD
* pre-processing.
*
* @param rinfo MPI rank information.
*/
static void p_reset_cpd_timers(
rank_info const * const rinfo)
{
timer_reset(&timers[TIMER_ATA]);
#ifdef SPLATT_USE_MPI
timer_reset(&timers[TIMER_MPI]);
timer_reset(&timers[TIMER_MPI_IDLE]);
timer_reset(&timers[TIMER_MPI_COMM]);
timer_reset(&timers[TIMER_MPI_ATA]);
timer_reset(&timers[TIMER_MPI_REDUCE]);
timer_reset(&timers[TIMER_MPI_NORM]);
timer_reset(&timers[TIMER_MPI_UPDATE]);
timer_reset(&timers[TIMER_MPI_FIT]);
MPI_Barrier(rinfo->comm_3d);
#endif
}
/**
* @brief Find the Frobenius norm squared of a Kruskal tensor. This equivalent
* to via computing <X,X>, the inner product of X with itself. We find
* this via \lambda^T (AtA * BtB * ...) \lambda, where * is the Hadamard
* product.
*
* @param nmodes The number of modes in the tensor.
* @param lambda The vector of column norms.
* @param aTa An array of Gram Matrices (AtA, BtB, ...).
*
* @return The Frobenius norm of X, squared.
*/
static val_t p_kruskal_norm(
idx_t const nmodes,
val_t const * const restrict lambda,
matrix_t ** aTa)
{
idx_t const rank = aTa[0]->J;
val_t * const restrict av = aTa[MAX_NMODES]->vals;
val_t norm_mats = 0;
/* use aTa[MAX_NMODES] as scratch space */
for(idx_t x=0; x < rank*rank; ++x) {
av[x] = 1.;
}
/* aTa[MAX_NMODES] = hada(aTa) */
for(idx_t m=0; m < nmodes; ++m) {
val_t const * const restrict atavals = aTa[m]->vals;
for(idx_t x=0; x < rank*rank; ++x) {
av[x] *= atavals[x];
}
}
/* now compute lambda^T * aTa[MAX_NMODES] * lambda */
for(idx_t i=0; i < rank; ++i) {
for(idx_t j=0; j < rank; ++j) {
norm_mats += av[j+(i*rank)] * lambda[i] * lambda[j];
}
}
return fabs(norm_mats);
}
/**
* @brief Compute the inner product of a Kruskal tensor and an unfactored
* tensor. Assumes that 'm1' contains the MTTKRP result along the last
* mode of the two input tensors. This naturally follows the end of a
* CPD iteration.
*
* @param nmodes The number of modes in the input tensors.
* @param rinfo MPI rank information.
* @param thds OpenMP thread data structures.
* @param lambda The vector of column norms.
* @param mats The Kruskal-tensor matrices.
* @param m1 The result of doing MTTKRP along the last mode.
*
* @return The inner product of the two tensors, computed via:
* 1^T hadamard(mats[nmodes-1], m1) \lambda.
*/
static val_t p_tt_kruskal_inner(
idx_t const nmodes,
rank_info * const rinfo,
thd_info * const thds,
val_t const * const restrict lambda,
matrix_t ** mats,
matrix_t const * const m1)
{
idx_t const rank = mats[0]->J;
idx_t const lastm = nmodes - 1;
idx_t const dim = m1->I;
val_t const * const m0 = mats[lastm]->vals;
val_t const * const mv = m1->vals;
val_t myinner = 0;
#pragma omp parallel reduction(+:myinner)
{
int const tid = omp_get_thread_num();
val_t * const restrict accumF = (val_t *) thds[tid].scratch[0];
for(idx_t r=0; r < rank; ++r) {
accumF[r] = 0.;
}
#pragma omp for
for(idx_t i=0; i < dim; ++i) {
for(idx_t r=0; r < rank; ++r) {
accumF[r] += m0[r+(i*rank)] * mv[r+(i*rank)];
}
}
/* accumulate everything into 'myinner' */
for(idx_t r=0; r < rank; ++r) {
myinner += accumF[r] * lambda[r];
}
}
val_t inner = 0.;
#ifdef SPLATT_USE_MPI
timer_start(&timers[TIMER_MPI_FIT]);
timer_start(&timers[TIMER_MPI_IDLE]);
MPI_Barrier(rinfo->comm_3d);
timer_stop(&timers[TIMER_MPI_IDLE]);
MPI_Allreduce(&myinner, &inner, 1, SPLATT_MPI_VAL, MPI_SUM, rinfo->comm_3d);
timer_stop(&timers[TIMER_MPI_FIT]);
#else
inner = myinner;
#endif
return inner;
}
/**
* @brief Compute the fit of a Kruskal tensor, Z, to an input tensor, X. This
* is computed via 1 - [sqrt(<X,X> + <Z,Z> - 2<X,Z>) / sqrt(<X,X>)].
*
* @param nmodes The number of modes in the input tensors.
* @param rinfo MPI rank information.
* @param thds OpenMP thread data structures.
* @param ttnormsq The norm (squared) of the original input tensor, <X,X>.
* @param lambda The vector of column norms.
* @param mats The Kruskal-tensor matrices.
* @param m1 The result of doing MTTKRP along the last mode.
* @param aTa An array of matrices (length MAX_NMODES)containing BtB, CtC, etc.
*
* @return The inner product of the two tensors, computed via:
* \lambda^T hadamard(mats[nmodes-1], m1) \lambda.
*/
static val_t p_calc_fit(
idx_t const nmodes,
rank_info * const rinfo,
thd_info * const thds,
val_t const ttnormsq,
val_t const * const restrict lambda,
matrix_t ** mats,
matrix_t const * const m1,
matrix_t ** aTa)
{
timer_start(&timers[TIMER_FIT]);
/* First get norm of new model: lambda^T * (hada aTa) * lambda. */
val_t const norm_mats = p_kruskal_norm(nmodes, lambda, aTa);
/* Compute inner product of tensor with new model */
val_t const inner = p_tt_kruskal_inner(nmodes, rinfo, thds, lambda, mats,m1);
val_t const residual = sqrt(ttnormsq + norm_mats - (2 * inner));
timer_stop(&timers[TIMER_FIT]);
return 1 - (residual / sqrt(ttnormsq));
}
/******************************************************************************
* PUBLIC FUNCTIONS
*****************************************************************************/
double cpd_als_iterate(
splatt_csf const * const tensors,
matrix_t ** mats,
val_t * const lambda,
idx_t const nfactors,
rank_info * const rinfo,
double const * const opts)
{
idx_t const nmodes = tensors[0].nmodes;
idx_t const nthreads = (idx_t) opts[SPLATT_OPTION_NTHREADS];
/* Compute thread-private scratch size for reduction */
idx_t reduction_scratch_size = 0;
for(int m=0; m < nmodes; ++m) {
splatt_csf_type which = (splatt_csf_type)opts[SPLATT_OPTION_CSF_ALLOC];
idx_t outdepth = MAX_NMODES;
switch(which) {
case SPLATT_CSF_ONEMODE:
outdepth = csf_mode_depth(m, tensors[0].dim_perm, nmodes);
if(outdepth > 0) {
if(mttkrp_use_privatization(tensors->nnz, mats[m]->I, opts)) {
printf("mode %d use privatization\n", m);
reduction_scratch_size = SS_MAX(reduction_scratch_size, mats[m]->I);
}
}
break;
case SPLATT_CSF_TWOMODE:
if(m != tensors[0].dim_perm[nmodes-1]) { /* longest mode handled via second tensor's root */
outdepth = csf_mode_depth(m, tensors[0].dim_perm, nmodes);
if(outdepth > 0) {
if(mttkrp_use_privatization(tensors->nnz, mats[m]->I, opts)) {
printf("mode %d use privatization\n", m);
reduction_scratch_size = SS_MAX(reduction_scratch_size, mats[m]->I);
}
}
}
break;
default:
break;
}
}
/* Setup thread structures. + 64 bytes is to avoid false sharing.
* TODO make this better */
omp_set_num_threads(nthreads);
thd_info * thds = thd_init(nthreads, 3,
(nfactors * nfactors * sizeof(val_t)) + 64,
(nfactors * reduction_scratch_size * sizeof(val_t)) + 64,
(nmodes * nfactors * sizeof(val_t)) + 64);
matrix_t * m1 = mats[MAX_NMODES];
/* Initialize first A^T * A mats. We redundantly do the first because it
* makes communication easier. */
matrix_t * aTa[MAX_NMODES+1];
for(idx_t m=0; m < nmodes; ++m) {
aTa[m] = mat_alloc(nfactors, nfactors);
mat_aTa(mats[m], aTa[m], rinfo, thds, nthreads);
}
/* used as buffer space */
aTa[MAX_NMODES] = mat_alloc(nfactors, nfactors);
/* Compute input tensor norm */
double oldfit = 0;
double fit = 0;
val_t ttnormsq = csf_frobsq(tensors);
/* setup timers */
p_reset_cpd_timers(rinfo);
sp_timer_t itertime;
sp_timer_t modetime[MAX_NMODES];
timer_start(&timers[TIMER_CPD]);
idx_t const niters = (idx_t) opts[SPLATT_OPTION_NITER];
for(idx_t it=0; it < niters; ++it) {
timer_fstart(&itertime);
for(idx_t m=0; m < nmodes; ++m) {
timer_fstart(&modetime[m]);
mats[MAX_NMODES]->I = tensors[0].dims[m];
m1->I = mats[m]->I;
/* M1 = X * (C o B) */
timer_start(&timers[TIMER_MTTKRP]);
mttkrp_csf(tensors, mats, m, thds, opts);
timer_stop(&timers[TIMER_MTTKRP]);
#ifdef SPLATT_USE_DSYRK
par_memcpy(mats[m]->vals, m1->vals, m1->I * nfactors * sizeof(val_t));
mat_solve_normals(m, nmodes, aTa, mats[m], 0.);
#else
calc_gram_inv(m, nmodes, aTa);
/* A = M1 * M2 */
mat_matmul(m1, aTa[MAX_NMODES], mats[m]);
#endif
/* normalize columns and extract lambda */
if(it == 0) {
mat_normalize(mats[m], lambda, MAT_NORM_2, rinfo, thds, nthreads);
} else {
mat_normalize(mats[m], lambda, MAT_NORM_MAX, rinfo, thds,nthreads);
}
/* update A^T*A */
mat_aTa(mats[m], aTa[m], rinfo, thds, nthreads);
timer_stop(&modetime[m]);
} /* foreach mode */
fit = p_calc_fit(nmodes, rinfo, thds, ttnormsq, lambda, mats, m1, aTa);
timer_stop(&itertime);
if(rinfo->rank == 0 &&
opts[SPLATT_OPTION_VERBOSITY] > SPLATT_VERBOSITY_NONE) {
printf(" its = %3"SPLATT_PF_IDX" (%0.3fs) fit = %0.5f delta = %+0.4e\n",
it+1, itertime.seconds, fit, fit - oldfit);
if(opts[SPLATT_OPTION_VERBOSITY] > SPLATT_VERBOSITY_LOW) {
for(idx_t m=0; m < nmodes; ++m) {
printf(" mode = %1"SPLATT_PF_IDX" (%0.3fs)\n", m+1,
modetime[m].seconds);
}
}
}
if(it > 0 && fabs(fit - oldfit) < opts[SPLATT_OPTION_TOLERANCE]) {
break;
}
oldfit = fit;
}
timer_stop(&timers[TIMER_CPD]);
cpd_post_process(nfactors, nmodes, mats, lambda, thds, nthreads, rinfo);
/* CLEAN UP */
for(idx_t m=0; m < nmodes; ++m) {
mat_free(aTa[m]);
}
mat_free(aTa[MAX_NMODES]);
thd_free(thds, nthreads);
return fit;
}
void cpd_post_process(
idx_t const nfactors,
idx_t const nmodes,
matrix_t ** mats,
val_t * const lambda,
thd_info * const thds,
idx_t const nthreads,
rank_info * const rinfo)
{
val_t * tmp = splatt_malloc(nfactors * sizeof(*tmp));
/* normalize each matrix and adjust lambda */
for(idx_t m=0; m < nmodes; ++m) {
mat_normalize(mats[m], tmp, MAT_NORM_2, rinfo, thds, nthreads);
for(idx_t f=0; f < nfactors; ++f) {
lambda[f] *= tmp[f];
}
}
free(tmp);
}
|
GB_binop__copysign_fp64.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__copysign_fp64)
// A.*B function (eWiseMult): GB (_AemultB_01__copysign_fp64)
// A.*B function (eWiseMult): GB (_AemultB_02__copysign_fp64)
// A.*B function (eWiseMult): GB (_AemultB_03__copysign_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__copysign_fp64)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__copysign_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__copysign_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__copysign_fp64)
// C=scalar+B GB (_bind1st__copysign_fp64)
// C=scalar+B' GB (_bind1st_tran__copysign_fp64)
// C=A+scalar GB (_bind2nd__copysign_fp64)
// C=A'+scalar GB (_bind2nd_tran__copysign_fp64)
// C type: double
// A type: double
// B,b type: double
// BinaryOp: cij = copysign (aij, bij)
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
double
// 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) \
double aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
double bij = GBX (Bx, pB, B_iso)
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
double 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 = copysign (x, y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
1
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_COPYSIGN || GxB_NO_FP64 || GxB_NO_COPYSIGN_FP64)
//------------------------------------------------------------------------------
// 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__copysign_fp64)
(
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__copysign_fp64)
(
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__copysign_fp64)
(
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 double
double bwork = (*((double *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *restrict Cx = (double *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *restrict Cx = (double *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__copysign_fp64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_01__copysign_fp64)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_01_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__copysign_fp64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__copysign_fp64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_03_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__copysign_fp64)
(
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__copysign_fp64)
(
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
double *Cx = (double *) Cx_output ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) 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 ;
double bij = GBX (Bx, p, false) ;
Cx [p] = copysign (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__copysign_fp64)
(
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 ;
double *Cx = (double *) Cx_output ;
double *Ax = (double *) Ax_input ;
double y = (*((double *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
double aij = GBX (Ax, p, false) ;
Cx [p] = copysign (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) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = copysign (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__copysign_fp64)
(
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 \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
double
}
//------------------------------------------------------------------------------
// 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) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = copysign (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__copysign_fp64)
(
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
double y = (*((const double *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
dipoledipoleinteraction.h | /*
* Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#ifndef VOTCA_XTP_DIPOLEDIPOLEINTERACTION_H
#define VOTCA_XTP_DIPOLEDIPOLEINTERACTION_H
// Local VOTCA includes
#include "eeinteractor.h"
#include "eigen.h"
namespace votca {
namespace xtp {
class DipoleDipoleInteraction;
}
} // namespace votca
namespace Eigen {
namespace internal {
// MatrixReplacement looks-like a SparseMatrix, so let's inherits its traits:
template <>
struct traits<votca::xtp::DipoleDipoleInteraction>
: public Eigen::internal::traits<Eigen::MatrixXd> {};
} // namespace internal
} // namespace Eigen
namespace votca {
namespace xtp {
class DipoleDipoleInteraction
: public Eigen::EigenBase<DipoleDipoleInteraction> {
public:
// Required typedefs, constants, and method:
using Scalar = double;
using RealScalar = double;
using StorageIndex = votca::Index;
enum {
ColsAtCompileTime = Eigen::Dynamic,
MaxColsAtCompileTime = Eigen::Dynamic,
IsRowMajor = false
};
DipoleDipoleInteraction(const eeInteractor& interactor,
const std::vector<PolarSegment>& segs)
: _interactor(interactor) {
_size = 0;
for (const PolarSegment& seg : segs) {
_size += 3 * seg.size();
}
_sites.reserve(_size / 3);
for (const PolarSegment& seg : segs) {
for (const PolarSite& site : seg) {
_sites.push_back(&site);
}
}
}
class InnerIterator {
public:
InnerIterator(const DipoleDipoleInteraction& xpr, const Index& id)
: _xpr(xpr), _id(id){};
InnerIterator& operator++() {
_row++;
return *this;
}
operator bool() const {
return _row < _xpr._size;
} // DO not use the size method, it returns linear dimension*linear
// dimension i.e _size^2
double value() const { return _xpr(_row, _id); }
Index row() const { return _row; }
Index col() const { return _id; }
Index index() const { return row(); }
private:
const DipoleDipoleInteraction& _xpr;
const Index _id;
Index _row = 0;
};
Index rows() const { return this->_size; }
Index cols() const { return this->_size; }
Index outerSize() const { return this->_size; }
template <typename Vtype>
Eigen::Product<DipoleDipoleInteraction, Vtype, Eigen::AliasFreeProduct>
operator*(const Eigen::MatrixBase<Vtype>& x) const {
return Eigen::Product<DipoleDipoleInteraction, Vtype,
Eigen::AliasFreeProduct>(*this, x.derived());
}
// this is not a fast method
const double& operator()(const Index i, const Index j) const {
Index seg1id = Index(i / 3);
Index xyz1 = Index(i % 3);
Index seg2id = Index(j / 3);
Index xyz2 = Index(j % 3);
if (seg1id == seg2id) {
return _sites[seg1id]->getPInv()(xyz1, xyz2);
} else {
const PolarSite& site1 = *_sites[seg1id];
const PolarSite& site2 = *_sites[seg2id];
return _interactor.FillTholeInteraction(site1, site2)(xyz1, xyz2);
}
};
Eigen::VectorXd multiply(const Eigen::VectorXd& v) const {
assert(v.size() == _size &&
"input vector has the wrong size for multiply with operator");
const Index segment_size = Index(_sites.size());
Eigen::VectorXd result = Eigen::VectorXd::Zero(_size);
#pragma omp parallel for schedule(dynamic) reduction(+ : result)
for (Index i = 0; i < segment_size; i++) {
const PolarSite& site1 = *_sites[i];
result.segment<3>(3 * i) += site1.getPInv() * v.segment<3>(3 * i);
for (Index j = i + 1; j < segment_size; j++) {
const PolarSite& site2 = *_sites[j];
Eigen::Matrix3d block = _interactor.FillTholeInteraction(site1, site2);
result.segment<3>(3 * i) += block * v.segment<3>(3 * j);
result.segment<3>(3 * j) += block.transpose() * v.segment<3>(3 * i);
}
}
return result;
}
private:
const eeInteractor& _interactor;
std::vector<const PolarSite*> _sites;
Index _size;
};
} // namespace xtp
} // namespace votca
namespace Eigen {
namespace internal {
// replacement of the mat*vect operation
template <typename Vtype>
struct generic_product_impl<votca::xtp::DipoleDipoleInteraction, Vtype,
DenseShape, DenseShape, GemvProduct>
: generic_product_impl_base<
votca::xtp::DipoleDipoleInteraction, Vtype,
generic_product_impl<votca::xtp::DipoleDipoleInteraction, Vtype>> {
typedef typename Product<votca::xtp::DipoleDipoleInteraction, Vtype>::Scalar
Scalar;
template <typename Dest>
static void scaleAndAddTo(Dest& dst,
const votca::xtp::DipoleDipoleInteraction& op,
const Vtype& v, const Scalar& alpha) {
// returns dst = alpha * op * v
// alpha must be 1 here
assert(alpha == Scalar(1) && "scaling is not implemented");
EIGEN_ONLY_USED_FOR_DEBUG(alpha);
Eigen::VectorXd temp = op.multiply(v);
dst = temp.cast<Scalar>(); // tumbleweed fix do not delete
}
};
} // namespace internal
} // namespace Eigen
#endif // VOTCA_XTP_DIPOLEDIPOLEINTERACTION_H
|
jacobi-ompacc-opt2.c | // Liao, 7/9/2014, add collapse() inside jacobi()
// Liao, 1/22/2015, test nested map() clauses supported by device data environment reuse.
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <stdlib.h>
#ifdef _OPENMP
#include <omp.h>
#endif
// Add timing support
#include <sys/time.h>
double time_stamp()
{
struct timeval t;
double time;
gettimeofday(&t,(struct timezone*)NULL);
time = t.tv_sec + 1.0e-6*t.tv_usec;
return time;
}
double time1, time2;
void driver(void);
void initialize(void);
void jacobi(void);
void error_check(void);
/************************************************************
* program to solve a finite difference
* discretization of Helmholtz equation :
* (d2/dx2)u + (d2/dy2)u - alpha u = f
* using Jacobi iterative method.
*
* Modified: Sanjiv Shah, Kuck and Associates, Inc. (KAI), 1998
* Author: Joseph Robicheaux, Kuck and Associates, Inc. (KAI), 1998
*
* This c version program is translated by
* Chunhua Liao, University of Houston, Jan, 2005
*
* Directives are used in this code to achieve parallelism.
* All do loops are parallelized with default 'static' scheduling.
*
* Input : n - grid dimension in x direction
* m - grid dimension in y direction
* alpha - Helmholtz constant (always greater than 0.0)
* tol - error tolerance for iterative solver
* relax - Successice over relaxation parameter
* mits - Maximum iterations for iterative solver
*
* On output
* : u(n,m) - Dependent variable (solutions)
* : f(n,m) - Right hand side function
*************************************************************/
#define MSIZE 512
int n,m,mits;
#define REAL float // flexible between float and double
REAL error_ref= 9.212767E-04, resid_ref = 2.355429E-08; // depending on MSIZE!!
REAL tol,relax=1.0,alpha=0.0543;
REAL u[MSIZE][MSIZE],f[MSIZE][MSIZE],uold[MSIZE][MSIZE];
REAL dx,dy;
int main (void)
{
// float toler;
/* printf("Input n,m (< %d) - grid dimension in x,y direction:\n",MSIZE);
scanf ("%d",&n);
scanf ("%d",&m);
printf("Input tol - error tolerance for iterative solver\n");
scanf("%f",&toler);
tol=(double)toler;
printf("Input mits - Maximum iterations for solver\n");
scanf("%d",&mits);
*/
n=MSIZE;
m=MSIZE;
tol=0.0000000001;
mits=5000;
#if 0 // Not yet support concurrent CPU and GPU threads
#ifdef _OPENMP
#pragma omp parallel
{
#pragma omp single
printf("Running using %d threads...\n",omp_get_num_threads());
}
#endif
#endif
driver ( ) ;
return 0;
}
/*************************************************************
* Subroutine driver ()
* This is where the arrays are allocated and initialzed.
*
* Working varaibles/arrays
* dx - grid spacing in x direction
* dy - grid spacing in y direction
*************************************************************/
void driver( )
{
initialize();
time1 = time_stamp();
/* Solve Helmholtz equation */
jacobi ();
time2 = time_stamp();
printf("------------------------\n");
printf("Execution time = %f\n",time2-time1);
/* error_check (n,m,alpha,dx,dy,u,f)*/
error_check ( );
}
/* subroutine initialize (n,m,alpha,dx,dy,u,f)
******************************************************
* Initializes data
* Assumes exact solution is u(x,y) = (1-x^2)*(1-y^2)
*
******************************************************/
void initialize( )
{
int i,j, xx,yy;
//double PI=3.1415926;
dx = 2.0 / (n-1);
dy = 2.0 / (m-1);
/* Initialize initial condition and RHS */
//#pragma omp parallel for private(xx,yy,j,i)
for (i=0;i<n;i++)
for (j=0;j<m;j++)
{
xx =(int)( -1.0 + dx * (i-1));
yy = (int)(-1.0 + dy * (j-1)) ;
u[i][j] = 0.0;
f[i][j] = -1.0*alpha *(1.0-xx*xx)*(1.0-yy*yy)\
- 2.0*(1.0-xx*xx)-2.0*(1.0-yy*yy);
}
}
/* subroutine jacobi (n,m,dx,dy,alpha,omega,u,f,tol,maxit)
******************************************************************
* Subroutine HelmholtzJ
* Solves poisson equation on rectangular grid assuming :
* (1) Uniform discretization in each direction, and
* (2) Dirichlect boundary conditions
*
* Jacobi method is used in this routine
*
* Input : n,m Number of grid points in the X/Y directions
* dx,dy Grid spacing in the X/Y directions
* alpha Helmholtz eqn. coefficient
* omega Relaxation factor
* f(n,m) Right hand side function
* u(n,m) Dependent variable/Solution
* tol Tolerance for iterative solver
* maxit Maximum number of iterations
*
* Output : u(n,m) - Solution
*****************************************************************/
void jacobi( )
{
REAL omega;
int i,j,k;
REAL error,resid,ax,ay,b;
// double error_local;
// float ta,tb,tc,td,te,ta1,ta2,tb1,tb2,tc1,tc2,td1,td2;
// float te1,te2;
// float second;
omega=relax;
/*
* Initialize coefficients */
ax = 1.0/(dx*dx); /* X-direction coef */
ay = 1.0/(dy*dy); /* Y-direction coef */
b = -2.0/(dx*dx)-2.0/(dy*dy) - alpha; /* Central coeff */
error = 10.0 * tol;
k = 1;
// An optimization on top of naive coding: promoting data handling outside the while loop
// data properties may change since the scope is bigger:
#pragma omp target data map(to:n, m, omega, ax, ay, b, f[0:n][0:m]) map(tofrom:u[0:n][0:m]) map(alloc:uold[0:n][0:m])
while ((k<=mits)&&(error>tol))
{
error = 0.0;
/* Copy new solution into old */
//#pragma omp parallel
// {
#pragma omp target map(to:n, m, u[0:n][0:m]) map(from:uold[0:n][0:m])
#pragma omp parallel for private(j,i) collapse(2)
for(i=0;i<n;i++)
for(j=0;j<m;j++)
uold[i][j] = u[i][j];
#pragma omp target map(to:n, m, omega, ax, ay, b, f[0:n][0:m], uold[0:n][0:m]) map(from:u[0:n][0:m])
#pragma omp parallel for private(resid,j,i) reduction(+:error) collapse(2) // nowait
for (i=1;i<(n-1);i++)
for (j=1;j<(m-1);j++)
{
resid = (ax*(uold[i-1][j] + uold[i+1][j])\
+ ay*(uold[i][j-1] + uold[i][j+1])+ b * uold[i][j] - f[i][j])/b;
u[i][j] = uold[i][j] - omega * resid;
error = error + resid*resid ;
}
// }
/* omp end parallel */
/* Error check */
if (k%500==0)
printf("Finished %d iteration with error =%f\n",k, error);
error = sqrt(error)/(n*m);
k = k + 1;
} /* End iteration loop */
printf("Total Number of Iterations:%d\n",k);
printf("Residual:%E\n", error);
printf("Residual_ref :%E\n", resid_ref);
printf ("Diff ref=%E\n", fabs(error-resid_ref));
assert (fabs(error-resid_ref) < 1E-14);
}
/* subroutine error_check (n,m,alpha,dx,dy,u,f)
implicit none
************************************************************
* Checks error between numerical and exact solution
*
************************************************************/
void error_check ( )
{
int i,j;
REAL xx,yy,temp,error;
dx = 2.0 / (n-1);
dy = 2.0 / (m-1);
error = 0.0 ;
//#pragma omp parallel for private(xx,yy,temp,j,i) reduction(+:error)
for (i=0;i<n;i++)
for (j=0;j<m;j++)
{
xx = -1.0 + dx * (i-1);
yy = -1.0 + dy * (j-1);
temp = u[i][j] - (1.0-xx*xx)*(1.0-yy*yy);
error = error + temp*temp;
}
error = sqrt(error)/(n*m);
printf("Solution Error :%E \n",error);
printf("Solution Error Ref :%E \n",error_ref);
printf ("Diff ref=%E\n", fabs(error-error_ref));
assert (fabs(error-error_ref) < 1E-14);
}
|
gesummv_teams.c | /**
* gesummv.c: This file was adapted from PolyBench/GPU 1.0 test
* suite to run on GPU with OpenMP 4.0 pragmas and OpenCL driver.
*
* http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU
*
* Contacts: Marcio M Pereira <mpereira@ic.unicamp.br>
* Rafael Cardoso F Sousa <rafael.cardoso@students.ic.unicamp.br>
* Luís Felipe Mattos <ra107822@students.ic.unicamp.br>
*/
#include <omp.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include "../../common/polybenchUtilFuncts.h"
// define the error threshold for the results "not matching"
#define PERCENT_DIFF_ERROR_THRESHOLD 0.05
#define GPU 1
/* Problem size */
#define N 8192
/* Declared constant values for ALPHA and BETA (same as values in PolyBench 2.0)
*/
#define ALPHA 43532.0f
#define BETA 12313.0f
/* Can switch DATA_TYPE between float and double */
typedef float DATA_TYPE;
void gesummv(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *x, DATA_TYPE *y) {
for (int i = 0; i < N; i++) {
DATA_TYPE tmp = 0;
y[i] = 0;
for (int j = 0; j < N; j++) {
tmp = A[i * N + j] * x[j] + tmp;
y[i] = B[i * N + j] * x[j] + y[i];
}
y[i] = ALPHA * tmp + BETA * y[i];
}
}
void gesummv_OMP(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *x, DATA_TYPE *y) {
#pragma omp target device(GPU) map(to : A[:N * N], B[:N * N], x[:N]) \
map(from : y[:N])
#pragma omp teams distribute parallel for
for (int i = 0; i < N; i++) {
DATA_TYPE tmp = 0;
y[i] = 0;
for (int j = 0; j < N; j++) {
tmp = A[i * N + j] * x[j] + tmp;
y[i] = B[i * N + j] * x[j] + y[i];
}
y[i] = ALPHA * tmp + BETA * y[i];
}
}
void init(DATA_TYPE *A, DATA_TYPE *B, DATA_TYPE *x) {
int i, j;
for (i = 0; i < N; i++) {
x[i] = ((DATA_TYPE)i) / N;
for (j = 0; j < N; j++) {
A[i * N + j] = ((DATA_TYPE)i * j) / N;
B[i * N + j] = ((DATA_TYPE)i * j) / N;
}
}
}
void compareResults(DATA_TYPE *y, DATA_TYPE *y_outputFromGpu) {
int i, fail;
fail = 0;
for (i = 0; i < (N); i++) {
if (percentDiff(y[i], y_outputFromGpu[i]) > PERCENT_DIFF_ERROR_THRESHOLD) {
fail++;
}
}
// Print results
printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f "
"Percent: %d\n",
PERCENT_DIFF_ERROR_THRESHOLD, fail);
}
int main(int argc, char *argv[]) {
double t_start, t_end;
DATA_TYPE *A;
DATA_TYPE *B;
DATA_TYPE *x;
DATA_TYPE *y;
DATA_TYPE *y_outputFromGpu;
A = (DATA_TYPE *)malloc(N * N * sizeof(DATA_TYPE));
B = (DATA_TYPE *)malloc(N * N * sizeof(DATA_TYPE));
x = (DATA_TYPE *)malloc(N * sizeof(DATA_TYPE));
y = (DATA_TYPE *)malloc(N * sizeof(DATA_TYPE));
y_outputFromGpu = (DATA_TYPE *)malloc(N * sizeof(DATA_TYPE));
fprintf(stdout, "<< Scalar, Vector and Matrix Multiplication >>\n");
init(A, B, x);
t_start = rtclock();
gesummv_OMP(A, B, x, y_outputFromGpu);
t_end = rtclock();
fprintf(stdout, "GPU Runtime: %0.6lfs\n", t_end - t_start);
init(A, B, x);
t_start = rtclock();
gesummv(A, B, x, y);
t_end = rtclock();
fprintf(stdout, "CPU Runtime: %0.6lfs\n", t_end - t_start);
compareResults(y, y_outputFromGpu);
free(A);
free(B);
free(x);
free(y);
free(y_outputFromGpu);
return 0;
}
|
pmv-OpenMP-reduction.c | /*
* pmv-OpenMp-b.c
*
* Created on: 12/04/2014
* Author: Carlos de la Torre
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h> // biblioteca para programas paralelos
#define PRINT_ALL_MIN 15
// Ponemos que los elementos mínimos para que se
// impriman todos los valores de la matriz sea 15
int main(int argc, char* argv[]) {
int i,j,N,TIME;
double tr, acumulador=0;
// estas son las variables que sirven para medir el tiempo
double t1, t2;
switch (argc){ // coneste switch nos aseguramos de que la entrada de parametros sea correcta
case 1:
printf("Faltan las filas/columnas de la Matriz, y el tamaño del vector\n");
printf("\nUso: %s [numero] [0/1]\n",argv[0]);
printf("\nDonde numero es el tamaño de las filas y las columnas de la matriz y el tamaño del vector\n");
printf("y el 0 o el 1 especifica si queremos solo los tiempos (1) o no\n");
exit(-1);
break;
case 2:
N = atoi(argv[1]); // Este sera el tamaño del vector y de las filas/columnas de la matriz
TIME = 0;
break;
case 3:
N = atoi(argv[1]); // Este sera el tamaño del vector y de las filas/columnas de la matriz
TIME = atoi(argv[2]); // si tiene un valor de 0 se imprime toda la info si tiene un valor de 1 se imprime solo el tiempo
break;
default:
printf("La cantidad de parametros es incorrecta\n");
exit(-1);
break;
}
int *vector, *Vresultado;
int **Matriz;
Matriz = (int**) malloc(N * sizeof(int*));
for (i = 0; i < N; i++)
Matriz[i] = (int*) malloc(N * sizeof(int));
vector = (int*) malloc(N * sizeof(int)); //si no hay espacio suficiente malloc devuelve NULL
Vresultado = (int*) malloc(N * sizeof(int));
if ((Matriz == NULL) || (vector == NULL) || (Vresultado == NULL)) {
printf("Error en la reserva de espacio para los Vectores o Matriz\n");
exit(-2);
}
srand(time(NULL)); // esta es la semilla que se usa para los random
#pragma omp parallel for private(i,j)// Inicializamos la Matriz y el vector
for (i = 0; i < N; i++){
for (j = 0; j < N; j++){
Matriz[i][j] = 2;
}
vector[i] = 4;
}
// imprimimos la matriz y el vector si el tamaño de N es menor de PRINT_ALL_MIN
if (N <= PRINT_ALL_MIN && TIME!=1){
printf ("\nEsta es la matriz: \n");
for (i = 0; i < N; i++){
for (j = 0; j < N; j++){
printf ("%d ",Matriz[i][j]);
}
printf ("\n");
}
printf ("\nEste es el vector: \n");
for (i = 0; i < N; i++)
printf ("%d ",vector[i]);
printf("\n\n");
}
t1 = omp_get_wtime(); // Calcular la multiplicación de una matriz por un vector
#pragma omp parallel private (i,j)
{
for (i = 0; i < N; i++){
acumulador = 0;
#pragma omp for reduction(+:acumulador)
for (j = 0; j < N; j++){
acumulador = Matriz[i][j]*vector[j];
}
#pragma omp single
Vresultado[i]=acumulador;
}
}
t2 = omp_get_wtime();
tr = t2 - t1; // Calculo el tiempo que he tardado en multiplicarlo
// Ahora imprimimos por pantalla los resultados obtenidos segun las restricciones del problema
if (N <= PRINT_ALL_MIN){
printf("Tiempo(seg.):%11.9f\nTamaño Matriz y Vector:%u\n",tr,N);// si queremos imprimir datos completos y N < PRINT_ALL_MIN
printf ("Este es el vector resultante: \n");
printf("{");
for (i = 0; i < N; i++){
printf ("VR[%d]=%d, ",i,Vresultado[i]);
}
printf("}\n");
}else if (TIME==1) // si queremos imprimir unicamente el tiempo de cálculo
printf("%11.9f\n",tr);//
else{ // y si queremos imprimir el tiempo la primera y la ultima multiplicacón
printf("Tiempo(seg.):%11.9f\n",tr);
printf("Tamaño Matriz y Vector:%u\n",N);
printf("(Matriz[0][0]=%d)*%d=%d\n",Matriz[0][0],vector[0],Matriz[0][0]*vector[0]);
printf("(Matriz[%d][%d]=%d)*%d=%d\n",N-1,N-1,Matriz[N-1][N-1],vector[N-1],Matriz[N-1][N-1]*vector[N-1]);
printf("VectorResultado[0]=%d\n",Vresultado[0]);
printf("VectorResultado[%d]=%d\n",N-1,Vresultado[N-1]);
}
free(vector);
free(Vresultado);
for(i=0; i<N; i++)
free(Matriz[i]);
free(Matriz);
return 0;
}
|
api_test.c |
#include "ctest/ctest.h"
#include "splatt_test.h"
#include "../src/sptensor.h"
/* API includes */
#include "../include/splatt.h"
#ifdef _OPENMP
#include <omp.h>
#endif
CTEST_DATA(api)
{
splatt_idx_t ntensors;
sptensor_t * tensors[MAX_DSETS];
};
CTEST_SETUP(api)
{
data->ntensors = sizeof(datasets) / sizeof(datasets[0]);
for(idx_t i=0; i < data->ntensors; ++i) {
data->tensors[i] = tt_read(datasets[i]);
}
}
CTEST_TEARDOWN(api)
{
for(idx_t i=0; i < data->ntensors; ++i) {
tt_free(data->tensors[i]);
}
}
CTEST(api, opts_alloc)
{
double * opts = splatt_default_opts();
ASSERT_NOT_NULL(opts);
/* test defaults */
#ifdef _OPENMP
ASSERT_EQUAL(omp_get_max_threads(), (int) opts[SPLATT_OPTION_NTHREADS]);
#else
ASSERT_EQUAL(1, (int) opts[SPLATT_OPTION_NTHREADS]);
#endif
splatt_free_opts(opts);
splatt_global_opts * gopts = splatt_alloc_global_opts();
#ifdef _OPENMP
ASSERT_EQUAL(omp_get_max_threads(), gopts->num_threads);
#else
ASSERT_EQUAL(1, gopts->num_threads);
#endif
splatt_free_global_opts(gopts);
}
CTEST(api, par_opts_alloc)
{
#pragma omp parallel num_threads(5)
{
double * opts = splatt_default_opts();
ASSERT_EQUAL(1, (int) opts[SPLATT_OPTION_NTHREADS]);
splatt_free_opts(opts);
splatt_global_opts * gopts = splatt_alloc_global_opts();
ASSERT_EQUAL(1, gopts->num_threads);
splatt_free_global_opts(gopts);
}
}
CTEST(api, version_major)
{
ASSERT_EQUAL(SPLATT_VER_MAJOR, splatt_version_major());
}
CTEST(api, version_minor)
{
ASSERT_EQUAL(SPLATT_VER_MINOR, splatt_version_minor());
}
CTEST(api, version_subminor)
{
ASSERT_EQUAL(SPLATT_VER_SUBMINOR, splatt_version_subminor());
}
/*
* Test dummy MPI functions.
*/
#ifndef SPLATT_USE_MPI
CTEST(mpi_comm_info, alloc)
{
splatt_comm_info * mpi = splatt_alloc_comm_info();
ASSERT_NOT_NULL(mpi);
ASSERT_EQUAL(0, mpi->world_rank);
ASSERT_EQUAL(1, mpi->world_npes);
/* don't crash */
splatt_free_comm_info(mpi);
}
#endif
|
search_function.h | #include <random>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <map>
#include <cmath>
#include <ctime>
#include <queue>
#include <vector>
#include <omp.h>
#include <chrono>
#include <limits>
#include <sys/time.h>
#include <algorithm>
#include <ctime>
#include "support_classes.h"
#include "visited_list_pool.h"
using namespace std;
struct triple_result {
priority_queue<pair<float, int > > topk;
int hops;
int dist_calc;
int degree;
};
void MakeStep(vector <uint32_t> &graph_level, const float *query, const float* db,
priority_queue<pair<float, int > > &topResults,
priority_queue<std::pair<float, int > > &candidateSet,
Metric *metric, uint32_t d, int &query_dist_calc, bool &found, int &ef, int &k,
VisitedList *vl) {
vl_type *massVisited = vl->mass;
vl_type currentV = vl->curV;
for (int j = 0; j < graph_level.size(); ++j) {
int neig_num = graph_level[j];
if (massVisited[neig_num] != currentV) {
massVisited[neig_num] = currentV;
const float *neig_coord = db + neig_num * d;
float dist = metric->Dist(query, neig_coord, d);
query_dist_calc++;
if (topResults.top().first > dist || topResults.size() < ef) {
candidateSet.emplace(-dist, neig_num);
found = true;
topResults.emplace(dist, neig_num);
if (topResults.size() > ef)
topResults.pop();
}
}
}
}
triple_result search(const float *query, const float* db, uint32_t N, uint32_t d,
vector<vector <uint32_t> > &main_graph, vector<vector <uint32_t> > &auxiliary_graph,
int ef, int k, vector<uint32_t> &inter_points, Metric *metric,
VisitedListPool *visitedlistpool,
bool use_second_graph, bool llf, uint32_t hops_bound) {
std::priority_queue<std::pair<float, int > > topResults;
int query_dist_calc = 1;
int num_hops = 0;
for (int i = 0; i < inter_points.size(); ++i) {
std::priority_queue<std::pair<float, int > > candidateSet;
const float* start = db + inter_points[i]*d;
float dist = metric->Dist(query, start, d);
topResults.emplace(dist, inter_points[i]);
candidateSet.emplace(-dist, inter_points[i]);
VisitedList *vl = visitedlistpool->getFreeVisitedList();
vl_type *massVisited = vl->mass;
vl_type currentV = vl->curV;
massVisited[inter_points[i]] = currentV;
while (!candidateSet.empty()) {
std::pair<float, int> curr_el_pair = candidateSet.top();
if (-curr_el_pair.first > topResults.top().first) break;
candidateSet.pop();
int curNodeNum = curr_el_pair.second;
bool auxiliary_found = false;
if (use_second_graph and num_hops < hops_bound) {
vector <uint32_t> curAuxiliaryNodeNeighbors = auxiliary_graph[curNodeNum];
MakeStep(curAuxiliaryNodeNeighbors, query, db,
topResults, candidateSet,
metric,
d, query_dist_calc, auxiliary_found, ef, k,
vl);
}
if (!(auxiliary_found * llf) or !use_second_graph) {
vector <uint32_t> curMainNodeNeighbors = main_graph[curNodeNum];
MakeStep(curMainNodeNeighbors, query, db,
topResults, candidateSet,
metric,
d, query_dist_calc, auxiliary_found, ef, k,
vl);
}
num_hops++;
}
visitedlistpool->releaseVisitedList(vl);
}
while (topResults.size() > k) {
topResults.pop();
}
triple_result ans{topResults, num_hops, query_dist_calc};
return ans;
}
int GetRealNearest(const float* point_q, int k, int d, int d_low, priority_queue<pair<float, int > > &topk,
vector<float> &ds,
Metric *metric) {
const float* point_i = ds.data() + d * topk.top().second;
float min_dist = metric->Dist(point_i, point_q, d);
int real_topk = topk.top().second;
topk.pop();
float dist;
while (!topk.empty()) {
point_i = ds.data() + d * topk.top().second;
dist = metric->Dist(point_i, point_q, d);
if (dist < min_dist) {
min_dist = dist;
real_topk = topk.top().second;
}
topk.pop();
}
return real_topk;
}
void get_one_test(vector<vector<uint32_t> > &knn_graph, vector<vector<uint32_t> > &kl_graph,
vector<float> &ds, vector<float> &queries, vector<float> &ds_low, vector<float> &queries_low,
vector<uint32_t> &truth,
int n, int d, int d_low, int n_q, int n_tr, int ef, int k, string graph_name,
Metric *metric, const char* output_txt,
vector<vector<uint32_t> > inter_points, bool use_second_graph, bool llf, uint32_t hops_bound, int dist_calc_boost,
int recheck_size, int number_exper, int number_of_threads) {
std::ofstream outfile;
outfile.open(output_txt, std::ios_base::app);
VisitedListPool *visitedlistpool = new VisitedListPool(1, n);
int hops = 0;
int dist_calc = 0 + dist_calc_boost * n_q;
float acc = 0;
float work_time = 0;
int num_exp = 0;
omp_set_num_threads(number_of_threads);
for (int v = 0; v < number_exper; ++v) {
num_exp += 1;
vector<int> ans(n_q);
StopW stopw = StopW();
#pragma omp parallel for
for (int i = 0; i < n_q; ++i) {
triple_result tr;
const float* point_q = queries.data() + i * d;
const float* point_q_low = queries_low.data() + i * d_low;
if (d != d_low) {
if (recheck_size > 0) {
tr = search(point_q_low, ds_low.data(), n, d_low, knn_graph, kl_graph, recheck_size,
recheck_size, inter_points[i], metric, visitedlistpool, use_second_graph, llf, hops_bound);
ans[i] = GetRealNearest(point_q, k, d, d_low, tr.topk, ds, metric);
dist_calc += recheck_size;
} else {
tr = search(point_q_low, ds_low.data(), n, d_low, knn_graph, kl_graph, ef,
k, inter_points[i], metric, visitedlistpool, use_second_graph, llf, hops_bound);
while (tr.topk.size() > k) {
tr.topk.pop();
}
ans[i] = tr.topk.top().second;
}
} else {
tr = search(point_q, ds.data(), n, d, knn_graph, kl_graph, ef,
k, inter_points[i], metric, visitedlistpool, use_second_graph, llf, hops_bound);
while (tr.topk.size() > k) {
tr.topk.pop();
}
ans[i] = tr.topk.top().second;
}
hops += tr.hops;
dist_calc += tr.dist_calc;
}
work_time += stopw.getElapsedTimeMicro();
int print = 0;
for (int i = 0; i < n_q; ++i) {
acc += ans[i] == truth[i * n_tr];
}
}
cout << "graph_type " << graph_name << " acc " << acc / (num_exp * n_q) << " hops " << hops / (num_exp * n_q) << " dist_calc "
<< dist_calc / (num_exp * n_q) << " work_time " << work_time / (num_exp * 1e6 * n_q) << endl;
outfile << "graph_type " << graph_name << " acc " << acc / (num_exp * n_q) << " hops " << hops / (num_exp * n_q) << " dist_calc "
<< dist_calc / (num_exp * n_q) << " work_time " << work_time / (num_exp * 1e6 * n_q) << endl;
}
void get_synthetic_tests(int n, int d, int n_q, int n_tr, std::mt19937 random_gen,
vector< vector<uint32_t> > &knn, vector< vector<uint32_t> > &kl, vector<float> &db,
vector<float> &queries, vector<uint32_t> &truth, const char* output_txt,
Metric *metric, string graph_name, bool use_second_graph, bool llf, bool beam_search,
bool knn_by_threshold) {
vector<vector<uint32_t> > inter_points(n_q);
int num = 0;
uniform_int_distribution<int> uniform_distr(0, n-1);
for (int j=0; j < n_q; ++j) {
num = uniform_distr(random_gen);
inter_points[j].push_back(num);
}
vector<int> ef_coeff;
vector<int> k_coeff;
vector<float> thr_coeff;
uint32_t hops_bound = 11;
int recheck_size = -1;
int knn_size = FindGraphAverageDegree(knn);
if (beam_search) {
vector<int> k_coeff_{knn_size, knn_size, knn_size, knn_size, knn_size, knn_size};
k_coeff.insert(k_coeff.end(), k_coeff_.begin(), k_coeff_.end());
} else {
vector<int> ef_coeff_{1, 1, 1, 1, 1, 1};
ef_coeff.insert(ef_coeff.end(), ef_coeff_.begin(), ef_coeff_.end());
}
if (d == 3) {
if (beam_search) {
vector<int> ef_coeff_{10, 15, 20, 25, 30};
ef_coeff.insert(ef_coeff.end(), ef_coeff_.begin(), ef_coeff_.end());
} else {
vector<int> k_coeff_{12, 14, 16, 18, 20};
k_coeff.insert(k_coeff.end(), k_coeff_.begin(), k_coeff_.end());
vector<float> thr_coeff_{1.1, 1.2, 1.3, 1.4, 1.5};
thr_coeff.insert(thr_coeff.end(), thr_coeff_.begin(), thr_coeff_.end());
}
hops_bound = 11;
} else if (d == 5) {
if (beam_search) {
vector<int> ef_coeff_{7, 10, 15, 22, 25, 30};
ef_coeff.insert(ef_coeff.end(), ef_coeff_.begin(), ef_coeff_.end());
} else {
vector<int> k_coeff_{15, 20, 25, 30, 40, 60};
k_coeff.insert(k_coeff.end(), k_coeff_.begin(), k_coeff_.end());
vector<float> thr_coeff_{1.1, 1.15, 1.2, 1.3, 1.4, 1.5};
thr_coeff.insert(thr_coeff.end(), thr_coeff_.begin(), thr_coeff_.end());
}
hops_bound = 7;
} else if (d == 9) {
if (beam_search) {
vector<int> ef_coeff_{5, 8, 15, 25, 30, 35};
ef_coeff.insert(ef_coeff.end(), ef_coeff_.begin(), ef_coeff_.end());
} else {
vector<int> k_coeff_{60, 100, 150, 200, 250, 300};
k_coeff.insert(k_coeff.end(), k_coeff_.begin(), k_coeff_.end());
vector<float> thr_coeff_{1.25, 1.3, 1.35, 1.4, 1.45, 1.5};
thr_coeff.insert(thr_coeff.end(), thr_coeff_.begin(), thr_coeff_.end());
}
hops_bound = 5;
} else if (d == 17) {
if (beam_search) {
vector<int> ef_coeff_{10, 40, 70, 100, 130, 160};
ef_coeff.insert(ef_coeff.end(), ef_coeff_.begin(), ef_coeff_.end());
} else {
vector<int> k_coeff_{750, 1000, 1250, 1500, 1750, 2000};
k_coeff.insert(k_coeff.end(), k_coeff_.begin(), k_coeff_.end());
vector<float> thr_coeff_{1.1, 1.15, 1.17, 1.19, 1.21, 1.22};
thr_coeff.insert(thr_coeff.end(), thr_coeff_.begin(), thr_coeff_.end());
}
hops_bound = 4;
}
int exp_size = min(ef_coeff.size(), k_coeff.size());
for (int i=0; i < exp_size; ++i) {
vector< vector <uint32_t>> knn_cur;
if (beam_search) {
knn_cur = knn;
} else if (knn_by_threshold) {
float thr = asin(thr_coeff[i] * pow(2, 0.5) * pow(n, - 1. / d));
knn_cur = CutKNNbyThreshold(knn, db, thr, n, d, metric);
// cout << "threshold " << thr << ", thr_coeff[i] " << thr_coeff[i] << endl;
} else {
knn_cur = CutKNNbyK(knn, db, k_coeff[i], n, d, metric);
}
// cout << "knn_cur " << FindGraphAverageDegree(knn_cur) << endl;
get_one_test(knn_cur, kl, db, queries, db, queries, truth, n, d, d, n_q, n_tr, ef_coeff[i], 1,
graph_name, metric, output_txt, inter_points, use_second_graph, llf, hops_bound, 0, recheck_size, 1, omp_get_max_threads());
}
}
|
integral_sync.c | #include<stdio.h>
#include<omp.h>
#define NUM_THREADS 4
static long num_steps = 100000;
double step;
int main(){
int i, nthreads;
double pi = 0.0, init_time, finish_time;
step = 1.0 / (double)num_steps;
init_time = omp_get_wtime();
omp_set_num_threads(NUM_THREADS);
#pragma omp parallel
{
int i, id, nthrds;
double x, sum = 0.0;
id = omp_get_thread_num();
nthrds = omp_get_num_threads();
if (id == 0)
nthreads = nthrds;
for (i=id ; i<num_steps ; i=i+nthrds){
x = (i+0.5)*step;
sum += 4.0/(1.0+x*x);
}
#pragma omp critical
pi += sum*step;
}
finish_time = omp_get_wtime()-init_time;
printf("PI = %f\n", pi);
printf("Time = %f\n", finish_time);
}
|
GB_unaryop__ainv_int32_uint32.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__ainv_int32_uint32
// op(A') function: GB_tran__ainv_int32_uint32
// C type: int32_t
// A type: uint32_t
// cast: int32_t cij = (int32_t) aij
// unaryop: cij = -aij
#define GB_ATYPE \
uint32_t
#define GB_CTYPE \
int32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = -x ;
// casting
#define GB_CASTING(z, x) \
int32_t z = (int32_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_AINV || GxB_NO_INT32 || GxB_NO_UINT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__ainv_int32_uint32
(
int32_t *restrict Cx,
const uint32_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__ainv_int32_uint32
(
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
|
opt_sls_solver.h | /*++
Copyright (c) 2014 Microsoft Corporation
Module Name:
opt_sls_solver.h
Abstract:
Wraps a solver with SLS for improving a solution using an objective function.
Author:
Nikolaj Bjorner (nbjorner) 2014-4-18
Notes:
--*/
#ifndef OPT_SLS_SOLVER_H_
#define OPT_SLS_SOLVER_H_
#include "solver_na2as.h"
#include "card2bv_tactic.h"
#include "nnf_tactic.h"
#include "pb_sls.h"
#include "bvsls_opt_engine.h"
namespace opt {
class sls_solver : public solver_na2as {
ast_manager& m;
ref<solver> m_solver;
scoped_ptr<bvsls_opt_engine> m_bvsls;
scoped_ptr<smt::pb_sls> m_pbsls;
pb::card_pb_rewriter m_pb2bv;
vector<rational> m_weights;
expr_ref_vector m_soft;
model_ref m_model;
params_ref m_params;
symbol m_engine;
public:
sls_solver(ast_manager & m, solver* s,
expr_ref_vector const& soft,
vector<rational> const& weights,
params_ref & p):
solver_na2as(m),
m(m),
m_solver(s),
m_bvsls(0),
m_pbsls(0),
m_pb2bv(m),
m_weights(weights),
m_soft(soft)
{
updt_params(p);
}
virtual ~sls_solver() {}
virtual void updt_params(params_ref & p) {
m_solver->updt_params(p);
m_params.copy(p);
opt_params _p(p);
m_engine = _p.sls_engine();
}
virtual void collect_param_descrs(param_descrs & r) {
m_solver->collect_param_descrs(r);
}
virtual void collect_statistics(statistics & st) const {
m_solver->collect_statistics(st);
if (m_bvsls) m_bvsls->collect_statistics(st);
if (m_pbsls) m_pbsls->collect_statistics(st);
}
virtual void assert_expr(expr * t) {
m_solver->assert_expr(t);
}
virtual void get_unsat_core(ptr_vector<expr> & r) {
m_solver->get_unsat_core(r);
}
virtual void get_model(model_ref & m) {
m = m_model;
}
virtual proof * get_proof() {
return m_solver->get_proof();
}
virtual std::string reason_unknown() const {
return m_solver->reason_unknown();
}
virtual void get_labels(svector<symbol> & r) {
m_solver->get_labels(r);
}
virtual void set_cancel(bool f) {
m_solver->set_cancel(f);
m_pb2bv.set_cancel(f);
#pragma omp critical (sls_solver)
{
if (m_bvsls) {
m_bvsls->set_cancel(f);
}
if (m_pbsls) {
m_pbsls->set_cancel(f);
}
}
}
virtual void set_progress_callback(progress_callback * callback) {
m_solver->set_progress_callback(callback);
}
virtual unsigned get_num_assertions() const {
return m_solver->get_num_assertions();
}
virtual expr * get_assertion(unsigned idx) const {
return m_solver->get_assertion(idx);
}
virtual void display(std::ostream & out) const {
m_solver->display(out);
// if (m_bvsls) m_bvsls->display(out);
}
void opt(model_ref& mdl) {
if (m_engine == symbol("pb")) {
pbsls_opt(mdl);
}
else {
bvsls_opt(mdl);
}
}
static expr_ref soft2bv(expr_ref_vector const& soft, vector<rational> const& weights) {
ast_manager& m = soft.get_manager();
pb::card_pb_rewriter pb2bv(m);
rational upper(1);
expr_ref objective(m);
for (unsigned i = 0; i < weights.size(); ++i) {
upper += weights[i];
}
expr_ref zero(m), tmp(m);
bv_util bv(m);
expr_ref_vector es(m);
rational num = numerator(upper);
rational den = denominator(upper);
rational maxval = num*den;
unsigned bv_size = maxval.get_num_bits();
zero = bv.mk_numeral(rational(0), bv_size);
for (unsigned i = 0; i < soft.size(); ++i) {
pb2bv(soft[i], tmp);
es.push_back(m.mk_ite(tmp, bv.mk_numeral(den*weights[i], bv_size), zero));
}
if (es.empty()) {
objective = bv.mk_numeral(0, bv_size);
}
else {
objective = es[0].get();
for (unsigned i = 1; i < es.size(); ++i) {
objective = bv.mk_bv_add(objective, es[i].get());
}
}
return objective;
}
protected:
typedef bvsls_opt_engine::optimization_result opt_result;
virtual lbool check_sat_core(unsigned num_assumptions, expr * const * assumptions) {
lbool r = m_solver->check_sat(num_assumptions, assumptions);
if (r == l_true) {
m_solver->get_model(m_model);
opt(m_model);
}
return r;
}
virtual void push_core() {
m_solver->push();
}
virtual void pop_core(unsigned n) {
m_solver->pop(n);
}
private:
// convert soft constraints to bit-vector objective.
void assertions2sls() {
expr_ref tmp(m);
goal_ref g(alloc(goal, m, true, false));
for (unsigned i = 0; i < m_solver->get_num_assertions(); ++i) {
m_pb2bv(m_solver->get_assertion(i), tmp);
g->assert_expr(tmp);
}
TRACE("opt", g->display(tout););
tactic_ref simplify = mk_nnf_tactic(m);
proof_converter_ref pc;
expr_dependency_ref core(m);
goal_ref_buffer result;
model_converter_ref model_converter;
(*simplify)(g, result, model_converter, pc, core);
SASSERT(result.size() == 1);
goal* r = result[0];
for (unsigned i = 0; i < r->size(); ++i) {
m_bvsls->assert_expr(r->form(i));
}
TRACE("opt", m_bvsls->display(tout););
}
void pbsls_opt(model_ref& mdl) {
#pragma omp critical (sls_solver)
{
if (m_pbsls) {
m_pbsls->reset();
}
else {
m_pbsls = alloc(smt::pb_sls, m);
}
}
m_pbsls->set_model(mdl);
m_pbsls->updt_params(m_params);
for (unsigned i = 0; i < m_solver->get_num_assertions(); ++i) {
m_pbsls->add(m_solver->get_assertion(i));
}
for (unsigned i = 0; i < m_soft.size(); ++i) {
m_pbsls->add(m_soft[i].get(), m_weights[i]);
}
(*m_pbsls.get())();
m_pbsls->get_model(m_model);
mdl = m_model.get();
}
void bvsls_opt(model_ref& mdl) {
#pragma omp critical (sls_solver)
{
m_bvsls = alloc(bvsls_opt_engine, m, m_params);
}
assertions2sls();
expr_ref objective = soft2bv(m_soft, m_weights);
TRACE("opt", tout << objective << "\n";);
opt_result res(m);
res.is_sat = l_undef;
try {
res = m_bvsls->optimize(objective, mdl, true);
}
catch (...) {
}
SASSERT(res.is_sat == l_true || res.is_sat == l_undef);
if (res.is_sat == l_true) {
m_bvsls->get_model(m_model);
mdl = m_model.get();
}
}
};
}
#endif
|
helper.h | //
// Created by Lei Ma on 9/8/17.
//
#ifndef HALO_PARALLEL_HELPER_H
#define HALO_PARALLEL_HELPER_H
#include "initializer.h"
#include <ctime>
#include <omp.h> // for openmp
namespace Helper
{
double sgnf(double val) {
return val/std::abs(val);
}
// Reverse an array of state_type and store in a new array; Tested.
void state_array_reverse( const state_type state [], state_type state_reversed [], const int length){
for(int i=0; i< length; i++){
for(int j=0; j < 3; j++) {
state_reversed[i][j] = state[length -1 - i][j];
}
}
// return state_reversed;
}
void state_array_copy( const state_type state [], state_type state_copied [], const int length) {
for(int i=0; i< length; i++){
for(int j=0; j < 3; j++) {
state_copied[i][j] = state[i][j];
}
}
}
void sa_ptr_swap( StateArray* &stateptr, StateArray* &stateptr_swap) {
StateArray *saptr_temp = stateptr;
stateptr = stateptr_swap;
stateptr_swap = saptr_temp;
}
void state_avg( StateArray* statearrayavg, StateArray* statearray, const int length, double alpha = 0.5) {
double norm_avg = 1.0;
double ele = 0.0;
double sumrecp;
#pragma omp parallel for
for(int i=0; i< length; i++) {
sumrecp = 0.0; // Have to set it to 0 for each iteration in i
for(int j=0;j < 3;j++) {
ele = (alpha) * (*statearray)[i][j] + (1 - alpha) * (*statearrayavg)[i][j];
(*statearrayavg)[i][j] = ele;
sumrecp = sumrecp + ele*ele;
}
sumrecp = 1/( norm_avg*std::sqrt(sumrecp) );
for(int j=0;j < 3;j++) {
(*statearrayavg)[i][j] = (*statearrayavg)[i][j] *sumrecp;
}
}
}
double squared_difference( StateArray *current_state, StateArray *past_state, const int length, const int savestep = 1 ) {
double sum = 0;
for(int i = 0; i < length; i+=savestep) {
sum += pow( (*current_state)[i][0] - (*past_state)[i][0], 2.0 );
// sum += abs( (*current_state)[i][0] - (*past_state)[i][0] ); // Calculation of absolute value is much much slower than square.
}
return sum;
}
}
// End of Helper namespace
class Timing {
public:
Timing() :rawtime{time(0)} {} //Constructor
string timestamp()
{
// time (&rawtime);
tm *ctm = localtime(&rawtime);
int year = ctm->tm_year + 1900;
int month = ctm->tm_mon+1;
int day = ctm->tm_mday;
int hour = ctm->tm_hour;
int min = ctm->tm_min;
int sec = ctm->tm_sec;
return to_string(year) + "-" + to_string(month)+ "-"+to_string(day)+ "-" + to_string(hour) + "-"+ to_string(min) + "-" + to_string(sec);
}
string time_pretty()
{
return ctime (&rawtime);
}
clock_t stopwatch_reset()
{
const clock_t stopwatch_begin = clock();
return stopwatch_begin;
}
void stopwatch_info(const clock_t stopwatch_begin_time, const int NIterations, const double calc_iter=1000.0)
{
const clock_t stopwatch_end = clock();
cout << "Total clock time: " << float( stopwatch_end - stopwatch_begin_time ) / CLOCKS_PER_SEC << endl;
cout << "Clock time for 1000 iterations: " << calc_iter * float( stopwatch_end - stopwatch_begin_time ) / CLOCKS_PER_SEC / NIterations << endl;
}
clock_t wall_stopwatch_reset()
{
const clock_t stopwatch_begin = omp_get_wtime();
return stopwatch_begin;
}
void wall_stopwatch_info(const clock_t stopwatch_begin_time, const int NIterations, const double calc_iter=1000.0)
{
const clock_t stopwatch_end = omp_get_wtime();
cout << "Total clock time: " << float( stopwatch_end - stopwatch_begin_time ) << endl;
cout << "Clock time for 1000 iterations: " << calc_iter * float( stopwatch_end - stopwatch_begin_time ) / NIterations << endl;
}
private:
time_t rawtime;
};
#endif
|
XSHA_fmt_plug.c | /*
* This file is part of John the Ripper password cracker,
* Copyright (c) 2008,2011 by Solar Designer
*
* Intrinsics support added by magnum 2011.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_XSHA;
#elif FMT_REGISTERS_H
john_register_one(&fmt_XSHA);
#else
#include <string.h>
#include "arch.h"
#ifdef SIMD_COEF_32
#define NBKEYS (SIMD_COEF_32 * SIMD_PARA_SHA1)
#ifdef _OPENMP
static unsigned int omp_t = 1;
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 128
#endif
#endif
#endif
#include "simd-intrinsics.h"
#include "params.h"
#include "common.h"
#include "formats.h"
#include "sha.h"
#include "johnswap.h"
#include "memdbg.h"
#define FORMAT_LABEL "xsha"
#define FORMAT_NAME "Mac OS X 10.4 - 10.6"
#define ALGORITHM_NAME "SHA1 " SHA1_ALGORITHM_NAME
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH 0
#define PLAINTEXT_LENGTH 51
#define CIPHERTEXT_LENGTH 48
#define BINARY_SIZE 20
#define BINARY_ALIGN 4
#define SALT_SIZE 4
#define SALT_ALIGN 4
#ifdef SIMD_COEF_32
#define MIN_KEYS_PER_CRYPT NBKEYS
#define MAX_KEYS_PER_CRYPT NBKEYS
#define FMT_IS_BE
#include "common-simd-getpos.h"
#else
#define MIN_KEYS_PER_CRYPT 1
#ifdef _OPENMP
#define MAX_KEYS_PER_CRYPT (0x200 * 3)
#else
#define MAX_KEYS_PER_CRYPT 0x100
#endif
#endif
static struct fmt_tests tests[] = {
{"12345678F9083C7F66F46A0A102E4CC17EC08C8AF120571B", "abc"},
{"12345678EB8844BFAF2A8CBDD587A37EF8D4A290680D5818", "azertyuiop1"},
{"3234C32AAA335FD20E3F95870E5851BDBE942B79CE4FDD92", "azertyuiop2"},
{"01295B67659E95F32931CEDB3BA50289E2826AF3D5A1422F", "apple"},
{"0E6A48F765D0FFFFF6247FA80D748E615F91DD0C7431E4D9", "macintosh"},
{"A320163F1E6DB42C3949F7E232888ACC7DB7A0A17E493DBA", "test"},
{"743777471285CB3566886D4821D556E475E0DF9234308B22", "123"},
{"474379622BD7B9F84BD6E4BB52ABF9D01705EFB0A2426655", "passWOrd"},
{"597A523666A10C534495DB6333CF7EBA70C1A578CADE11A3", ""},
{NULL}
};
#ifdef SIMD_COEF_32
static uint32_t (*saved_key);
static uint32_t (*crypt_key);
static uint32_t cur_salt;
#else
static char saved_key[MAX_KEYS_PER_CRYPT][PLAINTEXT_LENGTH + 1];
static int saved_len[MAX_KEYS_PER_CRYPT];
static SHA_CTX ctx_salt;
static uint32_t crypt_out[MAX_KEYS_PER_CRYPT][5];
#endif
static void init(struct fmt_main *self)
{
#ifdef SIMD_COEF_32
#if defined (_OPENMP)
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt = omp_t * NBKEYS;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt = omp_t * NBKEYS;
#endif
saved_key = mem_calloc_align(self->params.max_keys_per_crypt,
SHA_BUF_SIZ * 4, MEM_ALIGN_SIMD);
crypt_key = mem_calloc_align(self->params.max_keys_per_crypt,
BINARY_SIZE, MEM_ALIGN_SIMD);
#endif
}
static void done(void)
{
#ifdef SIMD_COEF_32
MEM_FREE(crypt_key);
MEM_FREE(saved_key);
#endif
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *pos;
/* Require uppercase hex digits (assume ASCII) */
pos = ciphertext;
while (atoi16[ARCH_INDEX(*pos)] != 0x7F && *pos < 'a')
pos++;
return !*pos && pos - ciphertext == CIPHERTEXT_LENGTH;
}
static void *get_binary(char *ciphertext)
{
static unsigned char *out;
char *p;
int i;
if (!out)
out = mem_alloc_tiny(BINARY_SIZE, MEM_ALIGN_WORD);
p = ciphertext + 8;
for (i = 0; i < BINARY_SIZE; i++) {
out[i] =
(atoi16[ARCH_INDEX(*p)] << 4) |
atoi16[ARCH_INDEX(p[1])];
p += 2;
}
#if defined(SIMD_COEF_32) && ARCH_LITTLE_ENDIAN==1
alter_endianity(out, BINARY_SIZE);
#endif
return out;
}
static void *get_salt(char *ciphertext)
{
static unsigned int outbuf[SALT_SIZE / sizeof(int)];
unsigned char *out = (unsigned char*)outbuf;
char *p;
int i;
p = ciphertext;
for (i = 0; i < SALT_SIZE; i++) {
out[i] =
(atoi16[ARCH_INDEX(*p)] << 4) |
atoi16[ARCH_INDEX(p[1])];
p += 2;
}
#if defined(SIMD_COEF_32) && ARCH_LITTLE_ENDIAN==1
alter_endianity(out, SALT_SIZE);
#endif
return out;
}
#define COMMON_GET_HASH_SIMD32 5
#define COMMON_GET_HASH_VAR crypt_out
#define COMMON_GET_HASH_SIMD_VAR crypt_key
#include "common-get-hash.h"
static int salt_hash(void *salt)
{
return *(uint32_t *)salt & (SALT_HASH_SIZE - 1);
}
static void set_salt(void *salt)
{
#ifdef SIMD_COEF_32
cur_salt = *(uint32_t*)salt;
#else
SHA1_Init(&ctx_salt);
SHA1_Update(&ctx_salt, salt, SALT_SIZE);
#endif
}
#define SALT_PREPENDED SALT_SIZE
#define NON_SIMD_SET_SAVED_LEN
#include "common-simd-setkey32.h"
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
#ifdef SIMD_COEF_32
int i = 0;
#if defined(_OPENMP)
#pragma omp parallel for
for (i=0; i < omp_t; i++) {
#endif
unsigned int *in = &saved_key[i*NBKEYS*SHA_BUF_SIZ];
unsigned int *out = &crypt_key[i*NBKEYS*BINARY_SIZE/4];
unsigned int j;
for (j=0; j < NBKEYS; j++)
in[(j&(SIMD_COEF_32-1)) + j/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32] = cur_salt;
SIMDSHA1body(in, out, NULL, SSEi_MIXED_IN);
#if defined(_OPENMP)
}
#endif
#else
int i;
#ifdef _OPENMP
#pragma omp parallel for default(none) private(i) shared(ctx_salt, saved_key, saved_len, crypt_out)
#endif
for (i = 0; i < count; i++) {
SHA_CTX ctx;
memcpy(&ctx, &ctx_salt, sizeof(ctx));
SHA1_Update(&ctx, saved_key[i], saved_len[i]);
SHA1_Final((unsigned char *)(crypt_out[i]), &ctx);
}
#endif
return count;
}
static int cmp_all(void *binary, int count)
{
#ifdef SIMD_COEF_32
unsigned int x,y=0;
#ifdef _OPENMP
for (;y<SIMD_PARA_SHA1*omp_t;y++)
#else
for (;y<SIMD_PARA_SHA1;y++)
#endif
for (x=0;x<SIMD_COEF_32;x++)
{
if ( ((uint32_t *)binary)[0] == ((uint32_t *)crypt_key)[x+y*SIMD_COEF_32*5] )
return 1;
}
return 0;
#else
uint32_t b0 = *(uint32_t *)binary;
int i;
for (i = 0; i < count; i++) {
if (b0 != crypt_out[i][0])
continue;
if (!memcmp(binary, crypt_out[i], BINARY_SIZE))
return 1;
}
return 0;
#endif
}
static int cmp_one(void *binary, int index)
{
#ifdef SIMD_COEF_32
unsigned int x,y;
x = index&(SIMD_COEF_32-1);
y = (unsigned int)index/SIMD_COEF_32;
if ( ((uint32_t *)binary)[0] != ((uint32_t *)crypt_key)[x+y*SIMD_COEF_32*5] )
return 0;
if ( ((uint32_t *)binary)[1] != ((uint32_t *)crypt_key)[x+y*SIMD_COEF_32*5+SIMD_COEF_32] )
return 0;
if ( ((uint32_t *)binary)[2] != ((uint32_t *)crypt_key)[x+y*SIMD_COEF_32*5+2*SIMD_COEF_32] )
return 0;
if ( ((uint32_t *)binary)[3] != ((uint32_t *)crypt_key)[x+y*SIMD_COEF_32*5+3*SIMD_COEF_32] )
return 0;
if ( ((uint32_t *)binary)[4] != ((uint32_t *)crypt_key)[x+y*SIMD_COEF_32*5+4*SIMD_COEF_32] )
return 0;
return 1;
#else
return !memcmp(binary, crypt_out[index], BINARY_SIZE);
#endif
}
static int cmp_exact(char *source, int index)
{
return 1;
}
struct fmt_main fmt_XSHA = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_OMP | FMT_OMP_BAD | FMT_CASE | FMT_8_BIT,
{ NULL },
{ NULL },
tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
get_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
#define COMMON_GET_HASH_LINK
#include "common-get-hash.h"
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
LRUCache_Prefetch.h | #include <iostream>
#include<stdint.h>
#include <unordered_map>
#include <vector>
using namespace std;
vector<int64_t>List_offset;
struct AIOReadInfo
{
int64_t readlength;
int64_t readoffset;
int64_t listlength;
int64_t offsetForenums;
int64_t memoffset;
int64_t curSendpos;
uint8_t *list_data;
uint32_t termid;
};
vector<int64_t>curReadpos;
vector<int64_t>usedFreq;
const uint64_t DISK_BLOCK = 4096;
const int64_t READ_BLOCK = 64 * 1024;
struct Node{
AIOReadInfo aiodata;
Node*prev, *next;
};
int64_t CACHE_SIZE = 1024 * 1024;
class LRUCache{
public:
LRUCache();
~LRUCache();
Node* Put(unsigned key);
Node* Get(unsigned key, bool& flag);
Node* Put_Prefetch(unsigned key);
Node* Get_Prefetch(unsigned key, bool& flag);
void print();
uint64_t hit_size;
uint64_t miss_size;
uint64_t hit_count;
uint64_t miss_count;
void attach(Node *node);
void detach(Node *node);
AIOReadInfo calAioreadinfo(unsigned term);
unordered_map<unsigned, Node*>hashmap_;
Node*head_, *tail_;
int64_t sumBytes;
};
LRUCache::LRUCache()
{
miss_size = 0; hit_size = 0;
miss_count = 0; hit_count = 0;
head_ = new Node;
tail_ = new Node;
head_->prev = NULL;
head_->next = tail_;
tail_->prev = head_;
tail_->next = NULL;
sumBytes = 0;
}
LRUCache::~LRUCache()
{
delete head_;
delete tail_;
}
AIOReadInfo LRUCache::calAioreadinfo(unsigned term)
{
AIOReadInfo tmpaio;
tmpaio.termid = term;
int64_t listlength = List_offset[term + 1] - List_offset[term];
tmpaio.listlength = listlength;
tmpaio.memoffset = 0;
int64_t offset = List_offset[term];
tmpaio.readoffset = ((int64_t)(offset / DISK_BLOCK))*DISK_BLOCK;
tmpaio.offsetForenums = offset - tmpaio.readoffset;
int64_t readlength = ((int64_t)(ceil((double)(listlength + tmpaio.offsetForenums) / READ_BLOCK)))*READ_BLOCK;
tmpaio.readlength = readlength;
tmpaio.curSendpos = -tmpaio.offsetForenums;
curReadpos[term] = -tmpaio.offsetForenums;
#pragma omp flush(curReadpos)
miss_size += tmpaio.listlength;
return tmpaio;
}
Node* LRUCache::Put(unsigned key)
{
AIOReadInfo tmpaio = calAioreadinfo(key);
Node *node;
if (tmpaio.readlength> CACHE_SIZE)
{
cout << "That block overflow!!" << endl;
return NULL;
}
node = tail_->prev;
while (sumBytes + tmpaio.readlength>CACHE_SIZE)
{
if (node == head_){ node = tail_->prev; }
#pragma omp flush(usedFreq)
if (usedFreq[node->aiodata.termid] > 0){ node = node->prev; continue; }
detach(node);
free(node->aiodata.list_data);
curReadpos[node->aiodata.termid] = node->aiodata.offsetForenums;
sumBytes -= node->aiodata.readlength;
hashmap_.erase(node->aiodata.termid);
Node *tmp = node->prev;
delete node;
node = tmp;
}
node = new Node();
posix_memalign((void**)&tmpaio.list_data, DISK_BLOCK, tmpaio.readlength);
node->aiodata = tmpaio;
sumBytes += tmpaio.readlength;
attach(node);
hashmap_[key] = node;
return node;
}
Node* LRUCache::Put_Prefetch(unsigned key)
{
AIOReadInfo tmpaio = calAioreadinfo(key);
Node *node;
if (tmpaio.readlength> CACHE_SIZE)
{
cout << "That block overflow!!" << endl;
return NULL;
}
node = tail_->prev;
while (sumBytes + tmpaio.readlength>CACHE_SIZE&&node != head_)
{
#pragma omp flush(usedFreq)
if (usedFreq[node->aiodata.termid] > 0){ node = node->prev; continue; }
detach(node);
free(node->aiodata.list_data);
curReadpos[node->aiodata.termid] = node->aiodata.offsetForenums;
sumBytes -= node->aiodata.readlength;
hashmap_.erase(node->aiodata.termid);
Node *tmp = node->prev;
delete node;
node = tmp;
}
if (node == head_)
{
return NULL;
}
node = new Node();
posix_memalign((void**)&tmpaio.list_data, DISK_BLOCK, tmpaio.readlength);
node->aiodata = tmpaio;
sumBytes += tmpaio.readlength;
attach(node);
hashmap_[key] = node;
return node;
}
Node* LRUCache::Get(unsigned key, bool &flag)
{
Node *node;
unordered_map<unsigned, Node* >::iterator it = hashmap_.find(key);
if (it != hashmap_.end())
{
node = it->second;
flag = true;
hit_count++;
detach(node);
attach(node);
}
else
{
flag = false;
miss_count++;
node = Put(key);
}
return node;
}
Node* LRUCache::Get_Prefetch(unsigned key, bool &flag)
{
Node *node;
unordered_map<unsigned, Node* >::iterator it = hashmap_.find(key);
if (it != hashmap_.end())
{
node = it->second;
flag = true;
detach(node);
attach(node);
}
else
{
flag = false;
miss_count++;
node = Put_Prefetch(key);
}
return node;
}
void LRUCache::attach(Node *node)
{
node->next = head_->next;
head_->next = node;
node->next->prev = node;
node->prev = head_;
}
void LRUCache::detach(Node *node)
{
node->prev->next = node->next;
node->next->prev = node->prev;
}
void LRUCache::print()
{
unordered_map<unsigned, Node* >::iterator iter;
int64_t mysumsize = 0;
for (iter = hashmap_.begin(); iter != hashmap_.end(); iter++)
{
mysumsize += iter->second->aiodata.listlength;
}
cout << "sumsize=" << mysumsize << endl;
}
|
template_vector.h | /* Copyright 2015 The math21 Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#pragma once
#include "inner.h"
namespace math21 {
template<typename T>
NumB math21_template_vector_is_equal_cpu(NumN n, const T *x, const T *y, NumR epsilon, NumN logLevel) {
x -= 1;
y -= 1;
NumN id;
//#pragma omp parallel for
for (id = 1; id <= n; ++id) {
NumR tmp = (NumR) y[id] - (NumR) x[id];
if (xjabs(tmp) > epsilon) {
break;
}
}
if (id <= n) {
if (logLevel) {
printf("different from postion %d\n", id);
}
return 0;
}
return 1;
}
template<typename T>
NumR math21_template_vector_distance(NumN n, const T *A, const T *B, NumR norm) {
MATH21_ASSERT(norm > 0);
A -= 1;
B -= 1;
NumN i;
NumR sum = 0;
if (norm == 1) {
//#pragma omp parallel for
for (i = 1; i <= n; ++i) sum += xjabs(A[i] - B[i]);
} else if (norm == 2) {
//#pragma omp parallel for
for (i = 1; i <= n; ++i) sum += xjsquare(A[i] - B[i]);
sum = xjsqrt(sum);
} else {
for (i = 1; i <= n; ++i) sum += xjpow(xjabs(A[i] - B[i]), norm);
sum = xjpow(sum, 1 / norm);
}
MATH21_ASSERT_FINITE(math21_operator_isfinite(sum))
return sum;
}
template<typename T>
T math21_template_vector_max(NumN n, const T *x, NumN &index) {
x -= 1;
NumN i;
MATH21_ASSERT(n >= 1);
NumN k = 1;
for (i = 1; i <= n; ++i) {
if (x[i] > x[k]) {
k = i;
}
}
index = k;
return x[k];
}
template<typename T>
T math21_template_vector_min(NumN n, const T *x, NumN &index) {
x -= 1;
NumN i;
MATH21_ASSERT(n >= 1);
NumN k = 1;
for (i = 1; i <= n; ++i) {
if (x[i] < x[k]) {
k = i;
}
}
index = k;
return x[k];
}
// see math21_operator_matrix_reverse_y_axis
template<typename T>
void math21_template_tensor_reverse_axis_3_in_d3_cpu(T *x, NumN d1, NumN d2, NumN d3) {
x -= 1;
NumN n = d1 * d2 * (d3 / 2);
NumN id;
#pragma omp parallel for
for (id = 1; id <= n; ++id) {
NumN i1, i2, i3, ix, iy;
math21_device_index_1d_to_3d_fast(&i1, &i2, &i3, id, d2, d3 / 2);
math21_device_index_3d_to_1d_fast(i1, i2, i3, &ix, d2, d3);
math21_device_index_3d_to_1d_fast(i1, i2, d3 + 1 - i3, &iy, d2, d3);
m21_swap(x[ix], x[iy]);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.