source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
deconvolution_packnto1_fp16s.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_packnto1_fp16s_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_fp16, 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)
{
const int packn = csrr_vlenb() / 2;
const word_type vl = vsetvl_e16m1(packn);
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++)
{
__fp16* 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];
}
vfloat32m2_t _sum = vfmv_v_f_f32m2(0.f, vl);
const __fp16* kptr = (const __fp16*)weight_data_fp16 + maxk * channels * p * packn;
// 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 __fp16* sptr = m.row<const __fp16>(sy) + sx * packn;
int k = y * kernel_w + x;
vfloat16m1_t _val = vle16_v_f16m1(sptr, vl);
vfloat16m1_t _w = vle16_v_f16m1(kptr + k * packn, vl);
_sum = vfwmacc_vv_f32m2(_sum, _val, _w, vl);
}
}
kptr += maxk * packn;
}
#if C906
// TODO
std::vector<float> ss(packn);
vse32_v_f32m2((float*)ss.data(), _sum, vl);
for (int i = 0; i < packn; i++)
{
sum += ss[i];
}
#else
sum = vfmv_f_s_f32m1_f32(vfredsum_vs_f32m2_f32m1(vfloat32m1_t(), _sum, vfmv_s_f_f32m1(vfloat32m1_t(), sum, vl), vl));
#endif
sum = activation_ss(sum, activation_type, activation_params);
outptr[j] = sum;
}
outptr += outw;
}
}
}
static void deconvolution_packnto1_fp16sa_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_fp16, const Mat& bias_data_fp16, 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)
{
const int packn = csrr_vlenb() / 2;
const word_type vl = vsetvl_e16m1(packn);
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 __fp16* bias_data_ptr = bias_data_fp16;
// num_output
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
__fp16* outptr = top_blob.channel(p);
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
__fp16 sum = 0.f;
if (bias_data_ptr)
{
sum = bias_data_ptr[p];
}
vfloat16m1_t _sum = vfmv_v_f_f16m1(0.f, vl);
const __fp16* kptr = (const __fp16*)weight_data_fp16 + maxk * channels * p * packn;
// 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 __fp16* sptr = m.row<const __fp16>(sy) + sx * packn;
int k = y * kernel_w + x;
vfloat16m1_t _val = vle16_v_f16m1(sptr, vl);
vfloat16m1_t _w = vle16_v_f16m1(kptr + k * packn, vl);
_sum = vfmacc_vv_f16m1(_sum, _val, _w, vl);
}
}
kptr += maxk * packn;
}
sum = vfmv_f_s_f16m1_f16(vfredsum_vs_f16m1_f16m1(vfloat16m1_t(), _sum, vfmv_s_f_f16m1(vfloat16m1_t(), sum, vl), vl));
sum = activation_ss(sum, activation_type, activation_params);
outptr[j] = sum;
}
outptr += outw;
}
}
}
|
ast-dump-openmp-target-parallel-for.c | // RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s
void test_one(int x) {
#pragma omp target parallel for
for (int i = 0; i < x; i++)
;
}
void test_two(int x, int y) {
#pragma omp target parallel for
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
;
}
void test_three(int x, int y) {
#pragma omp target parallel for collapse(1)
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
;
}
void test_four(int x, int y) {
#pragma omp target parallel for collapse(2)
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
;
}
void test_five(int x, int y, int z) {
#pragma omp target parallel for collapse(2)
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
for (int i = 0; i < z; i++)
;
}
// CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc>
// CHECK: |-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-target-parallel-for.c:3:1, line:7:1> line:3:6 test_one 'void (int)'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int'
// CHECK-NEXT: | `-CompoundStmt {{.*}} <col:22, line:7:1>
// CHECK-NEXT: | `-OMPTargetParallelForDirective {{.*}} <line:4:1, col:32>
// CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:5:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | `-CapturedStmt {{.*}} <col:3, line:6:5>
// CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:5:3, line:6:5>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-CapturedStmt {{.*}} <line:5:3, line:6:5>
// CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:5:3, line:6:5>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:5:8, col:17>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:6:5>
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:5:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <col:3, line:6:5>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:5:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:6:5>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:5:3> col:3 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <col:3, line:6:5>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:5:3, line:6:5>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:5:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:6:5>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:5:3> col:3 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-ForStmt {{.*}} <col:3, line:6:5>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:5:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt {{.*}} <line:6:5>
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:4:1) *const restrict'
// CHECK-NEXT: | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <col:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: |-FunctionDecl {{.*}} <line:9:1, line:14:1> line:9:6 test_two 'void (int, int)'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:22, col:26> col:26 used y 'int'
// CHECK-NEXT: | `-CompoundStmt {{.*}} <col:29, line:14:1>
// CHECK-NEXT: | `-OMPTargetParallelForDirective {{.*}} <line:10:1, col:32>
// CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:11:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | `-CapturedStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-CapturedStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:11:8, col:17>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:12:5, line:13:7>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:12:10, col:19>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:13:7>
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:11:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:11:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:12:25> col:25 implicit 'int'
// CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:11:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:12:5, line:13:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:12:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:13:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:11:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:11:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:12:25> col:25 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:11:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:12:5, line:13:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:12:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:13:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:11:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:11:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:12:25> col:25 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-ForStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:11:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ForStmt {{.*}} <line:12:5, line:13:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:12:10, col:19>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt {{.*}} <line:13:7>
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:10:1) *const restrict'
// CHECK-NEXT: | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:11:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: |-FunctionDecl {{.*}} <line:16:1, line:21:1> line:16:6 test_three 'void (int, int)'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:17, col:21> col:21 used x 'int'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:24, col:28> col:28 used y 'int'
// CHECK-NEXT: | `-CompoundStmt {{.*}} <col:31, line:21:1>
// CHECK-NEXT: | `-OMPTargetParallelForDirective {{.*}} <line:17:1, col:44>
// CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:33, col:43>
// CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:42> 'int'
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:42> 'int' 1
// CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:18:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | `-CapturedStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-CapturedStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:18:8, col:17>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:19:5, line:20:7>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:19:10, col:19>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:20:7>
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:18:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:18:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:19:25> col:25 implicit 'int'
// CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:18:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:19:5, line:20:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:19:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:20:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:18:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:18:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:19:25> col:25 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:18:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:19:5, line:20:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:19:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:20:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:18:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:18:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:19:25> col:25 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-ForStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:18:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ForStmt {{.*}} <line:19:5, line:20:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:19:10, col:19>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt {{.*}} <line:20:7>
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:17:1) *const restrict'
// CHECK-NEXT: | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:18:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: |-FunctionDecl {{.*}} <line:23:1, line:28:1> line:23:6 test_four 'void (int, int)'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int'
// CHECK-NEXT: | `-CompoundStmt {{.*}} <col:30, line:28:1>
// CHECK-NEXT: | `-OMPTargetParallelForDirective {{.*}} <line:24:1, col:44>
// CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:33, col:43>
// CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:42> 'int'
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:42> 'int' 2
// CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:25:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:26:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | `-CapturedStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-CapturedStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | | | |-ForStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:25:8, col:17>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-ForStmt {{.*}} <line:26:5, line:27:7>
// CHECK-NEXT: | | | | | | | |-DeclStmt {{.*}} <line:26:10, col:19>
// CHECK-NEXT: | | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-NullStmt {{.*}} <line:27:7>
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | | | | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-DeclRefExpr {{.*}} <line:25:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <line:26:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | | | |-FieldDecl {{.*}} <line:25:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | | | `-FieldDecl {{.*}} <line:26:5> col:5 implicit 'int'
// CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:25:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:26:5, line:27:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:26:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:27:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:25:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:26:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:25:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:26:5> col:5 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:25:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:26:5, line:27:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:26:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:27:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:25:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:26:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:25:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:26:5> col:5 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-ForStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:25:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ForStmt {{.*}} <line:26:5, line:27:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:26:10, col:19>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt {{.*}} <line:27:7>
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:24:1) *const restrict'
// CHECK-NEXT: | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:25:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:26:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: `-FunctionDecl {{.*}} <line:30:1, line:36:1> line:30:6 test_five 'void (int, int, int)'
// CHECK-NEXT: |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int'
// CHECK-NEXT: |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int'
// CHECK-NEXT: |-ParmVarDecl {{.*}} <col:30, col:34> col:34 used z 'int'
// CHECK-NEXT: `-CompoundStmt {{.*}} <col:37, line:36:1>
// CHECK-NEXT: `-OMPTargetParallelForDirective {{.*}} <line:31:1, col:44>
// CHECK-NEXT: |-OMPCollapseClause {{.*}} <col:33, col:43>
// CHECK-NEXT: | `-ConstantExpr {{.*}} <col:42> 'int'
// CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:42> 'int' 2
// CHECK-NEXT: |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:32:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:33:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: `-CapturedStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | |-CapturedStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | |-CapturedStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | | |-ForStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:32:8, col:17>
// CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:33:5, line:35:9>
// CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:33:10, col:19>
// CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ForStmt {{.*}} <line:34:7, line:35:9>
// CHECK-NEXT: | | | | | | |-DeclStmt {{.*}} <line:34:12, col:21>
// CHECK-NEXT: | | | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<'
// CHECK-NEXT: | | | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | | | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++'
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-NullStmt {{.*}} <line:35:9>
// CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | | | |-DeclRefExpr {{.*}} <line:32:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | |-DeclRefExpr {{.*}} <line:33:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | | |-FieldDecl {{.*}} <line:32:3> col:3 implicit 'int'
// CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | | |-FieldDecl {{.*}} <line:33:5> col:5 implicit 'int'
// CHECK-NEXT: | | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | | `-FieldDecl {{.*}} <line:34:27> col:27 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | |-ForStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:32:8, col:17>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:33:5, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:33:10, col:19>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:34:7, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:34:12, col:21>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:35:9>
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | | | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:32:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:33:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | |-FieldDecl {{.*}} <line:32:3> col:3 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | |-FieldDecl {{.*}} <line:33:5> col:5 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-FieldDecl {{.*}} <line:34:27> col:27 implicit 'int'
// CHECK-NEXT: | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | |-CapturedStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | |-ForStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:32:8, col:17>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:33:5, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:33:10, col:19>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:34:7, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:34:12, col:21>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:35:9>
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | | | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:32:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:33:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | |-FieldDecl {{.*}} <line:32:3> col:3 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | |-FieldDecl {{.*}} <line:33:5> col:5 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-FieldDecl {{.*}} <line:34:27> col:27 implicit 'int'
// CHECK-NEXT: | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | |-ForStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | |-DeclStmt {{.*}} <line:32:8, col:17>
// CHECK-NEXT: | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | |-<<<NULL>>>
// CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | `-ForStmt {{.*}} <line:33:5, line:35:9>
// CHECK-NEXT: | | |-DeclStmt {{.*}} <line:33:10, col:19>
// CHECK-NEXT: | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | |-<<<NULL>>>
// CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | `-ForStmt {{.*}} <line:34:7, line:35:9>
// CHECK-NEXT: | | |-DeclStmt {{.*}} <line:34:12, col:21>
// CHECK-NEXT: | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | |-<<<NULL>>>
// CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<'
// CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue>
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | `-NullStmt {{.*}} <line:35:9>
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit .global_tid. 'const int *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-target-parallel-for.c:31:1) *const restrict'
// CHECK-NEXT: | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: |-DeclRefExpr {{.*}} <line:32:3> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: |-DeclRefExpr {{.*}} <line:33:5> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
|
check_impl.c | /*
Copyright 2021 Tim Jammer
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "correctness-checking-partitioned-impl.h"
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#define SIZE 16
#define PARTITIONS 16
#define TAG 42
void correct_usage() {
MPIX_Request r;
int *buffer = (int*) malloc(sizeof(int) * PARTITIONS * SIZE);
MPIX_Psend_init(buffer, PARTITIONS, SIZE, MPI_INT, 1, TAG, MPI_COMM_WORLD,
MPI_INFO_NULL, &r);
MPIX_Start(&r);
#pragma omp parallel for
for (int i = 0; i < PARTITIONS; ++i) {
for (int j = i * SIZE; j < i * SIZE + SIZE; ++j) {
buffer[j] = i;
}
MPIX_Pready(i, &r);
}
MPIX_Wait(&r, MPI_STATUS_IGNORE);
MPIX_Request_free(&r);
}
void correct_usage_with_false_positives() {
MPIX_Request r;
int *buffer = (int*) malloc(sizeof(int) * PARTITIONS * SIZE);
int sum = 0;
MPIX_Psend_init(buffer, PARTITIONS, SIZE, MPI_INT, 1, TAG, MPI_COMM_WORLD,
MPI_INFO_NULL, &r);
MPIX_Start(&r);
#pragma omp parallel for reduction(+ : sum)
for (int i = 0; i < PARTITIONS; ++i) {
for (int j = i * SIZE; j < i * SIZE + SIZE; ++j) {
buffer[j] = i;
}
MPIX_Pready(i, &r);
for (int j = i * SIZE; j < i * SIZE + SIZE; ++j) {
// reading is allowed
sum += buffer[j];
}
}
printf("%d\n", sum);
MPIX_Wait(&r, MPI_STATUS_IGNORE);
MPIX_Request_free(&r);
}
void error_usage() {
MPIX_Request r;
int *buffer = (int*) malloc(sizeof(int) * PARTITIONS * SIZE);
MPIX_Psend_init(buffer, PARTITIONS, SIZE, MPI_INT, 1, TAG, MPI_COMM_WORLD,
MPI_INFO_NULL, &r);
MPIX_Start(&r);
// likely to fail
#pragma omp parallel for
for (int i = 0; i < PARTITIONS * 2; ++i) {
if (i < PARTITIONS) {
for (int j = i * SIZE; j < i * SIZE + SIZE / 2; ++j) {
buffer[j] = i;
}
MPIX_Pready(i, &r);
} else {
for (int j = (i - PARTITIONS) * SIZE + SIZE / 2;
j < (i - PARTITIONS) * SIZE + SIZE; ++j) {
buffer[j] = i;
}
}
}
MPIX_Wait(&r, MPI_STATUS_IGNORE);
MPIX_Request_free(&r);
}
int main(int argc, char **argv) {
MPI_Init(&argc, &argv);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
// correct_usage();
correct_usage_with_false_positives();
error_usage();
} else if (rank == 1) {
MPIX_Request r;
int *buffer = (int*) malloc(sizeof(int) * PARTITIONS * SIZE);
MPIX_Precv_init(buffer, 1, (PARTITIONS * SIZE), MPI_INT, 0, TAG,
MPI_COMM_WORLD, MPI_INFO_NULL, &r);
MPIX_Start(&r);
MPIX_Pready(0, &r);
MPIX_Wait(&r, MPI_STATUS_IGNORE);
MPIX_Start(&r);
MPIX_Pready(0, &r);
MPIX_Wait(&r, MPI_STATUS_IGNORE);
MPIX_Request_free(&r);
}
MPI_Finalize();
}
|
647ee_so12_itt.c | #define _POSIX_C_SOURCE 200809L
#include "stdlib.h"
#include "math.h"
#include "sys/time.h"
#include "ittnotify.h"
#include "xmmintrin.h"
#include "pmmintrin.h"
#include <stdio.h>
#include "omp.h"
#define min(a, b) (((a) < (b)) ? (a) : (b))
#define max(a, b) (((a) > (b)) ? (a) : (b))
struct dataobj
{
void *restrict data;
int *size;
int *npsize;
int *dsize;
int *hsize;
int *hofs;
int *oofs;
};
int Kernel(struct dataobj *restrict block_sizes_vec, struct dataobj *restrict damp_vec, const float dt, const float h_x, const float h_y, const float h_z, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict save_src_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict usol_vec, struct dataobj *restrict vp_vec, const int sp_zi_m, const int time_M, const int time_m, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads)
{
int (*restrict block_sizes) __attribute__ ((aligned (64))) = (int (*)) block_sizes_vec->data;
float(*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[damp_vec->size[1]][damp_vec->size[2]])damp_vec->data;
int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data;
float(*restrict save_src)[save_src_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_vec->size[1]])save_src_vec->data;
int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data;
float(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (float(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data;
int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data;
float(*restrict usol)[usol_vec->size[1]][usol_vec->size[2]][usol_vec->size[3]] __attribute__((aligned(64))) = (float(*)[usol_vec->size[1]][usol_vec->size[2]][usol_vec->size[3]])usol_vec->data;
float(*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[vp_vec->size[1]][vp_vec->size[2]])vp_vec->data;
/* Flush denormal numbers to zero in hardware */
_MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
__itt_resume();
int xb_size = block_sizes[0];
int y0_blk0_size = block_sizes[3];
int x0_blk0_size = block_sizes[2];
int yb_size = block_sizes[1];
printf(" Tiles: %d, %d ::: Blocks %d, %d \n", x0_blk0_size, y0_blk0_size, xb_size, yb_size);
int sf = 6;
int t_blk_size = 2 * sf * (time_M - time_m);
for (int t_blk = time_m; t_blk < sf * (time_M - time_m); t_blk += sf * t_blk_size) // for each t block
{
for (int xb = x_m; xb <= (x_M + sf * (time_M - time_m)); xb += xb_size + 1)
{
for (int yb = y_m; yb <= (y_M + sf * (time_M - time_m)); yb += yb_size + 1)
{
for (int time = t_blk, t0 = (time + 1) % (3), t1 = (time) % (3), t2 = (time + 2) % (3); time <= 1 + min(t_blk + t_blk_size - 1, sf * (time_M - time_m)); time += sf, t0 = (((time / sf) % (time_M - time_m + 1)) + 1) % (3), t1 = (((time / sf) % (time_M - time_m + 1))) % (3), t2 = (((time / sf) % (time_M - time_m + 1)) + 2) % (3))
{
int tw = ((time / sf) % (time_M - time_m + 1));
/* Begin section0 */
#pragma omp parallel num_threads(nthreads)
{
#pragma omp for collapse(2) schedule(dynamic, 1)
for (int x0_blk0 = max((x_m + time), xb); x0_blk0 <= min((x_M + time), (xb + xb_size)); x0_blk0 += x0_blk0_size)
{
for (int y0_blk0 = max((y_m + time), yb); y0_blk0 <= min((y_M + time), (yb + yb_size)); y0_blk0 += y0_blk0_size)
{
for (int x = x0_blk0; x <= min(min((x_M + time), (xb + xb_size)), (x0_blk0 + x0_blk0_size - 1)); x++)
{
for (int y = y0_blk0; y <= min(min((y_M + time), (yb + yb_size)), (y0_blk0 + y0_blk0_size - 1)); y++)
{
#pragma omp simd aligned(damp, usol, vp : 32)
for (int z = z_m; z <= z_M; z += 1)
{
float r7 = -2.98277778F * usol[t1][x - time + 12][y - time + 12][z + 12];
float r6 = 1.0 / dt;
float r5 = 1.0 / (dt * dt);
float r4 = 1.0 / (vp[x - time + 12][y - time + 12][z + 12] * vp[x - time + 12][y - time + 12][z + 12]);
usol[t0][x - time + 12][y - time + 12][z + 12] = (r4 * (-r5 * (-2.0F * usol[t1][x - time + 12][y - time + 12][z + 12] + usol[t2][x - time + 12][y - time + 12][z + 12])) + r6 * (damp[x - time + 1][y - time + 1][z + 1] * usol[t1][x - time + 12][y - time + 12][z + 12]) + (r7 - 6.01250601e-5F * (usol[t1][x - time + 12][y - time + 12][z + 6] + usol[t1][x - time + 12][y - time + 12][z + 18]) + 1.03896104e-3F * (usol[t1][x - time + 12][y - time + 12][z + 7] + usol[t1][x - time + 12][y - time + 12][z + 17]) - 8.92857143e-3F * (usol[t1][x - time + 12][y - time + 12][z + 8] + usol[t1][x - time + 12][y - time + 12][z + 16]) + 5.29100529e-2F * (usol[t1][x - time + 12][y - time + 12][z + 9] + usol[t1][x - time + 12][y - time + 12][z + 15]) - 2.67857143e-1F * (usol[t1][x - time + 12][y - time + 12][z + 10] + usol[t1][x - time + 12][y - time + 12][z + 14]) + 1.71428571F * (usol[t1][x - time + 12][y - time + 12][z + 11] + usol[t1][x - time + 12][y - time + 12][z + 13])) / ((h_z * h_z)) + (r7 - 6.01250601e-5F * (usol[t1][x - time + 12][y - time + 6][z + 12] + usol[t1][x - time + 12][y - time + 18][z + 12]) + 1.03896104e-3F * (usol[t1][x - time + 12][y - time + 7][z + 12] + usol[t1][x - time + 12][y - time + 17][z + 12]) - 8.92857143e-3F * (usol[t1][x - time + 12][y - time + 8][z + 12] + usol[t1][x - time + 12][y - time + 16][z + 12]) + 5.29100529e-2F * (usol[t1][x - time + 12][y - time + 9][z + 12] + usol[t1][x - time + 12][y - time + 15][z + 12]) - 2.67857143e-1F * (usol[t1][x - time + 12][y - time + 10][z + 12] + usol[t1][x - time + 12][y - time + 14][z + 12]) + 1.71428571F * (usol[t1][x - time + 12][y - time + 11][z + 12] + usol[t1][x - time + 12][y - time + 13][z + 12])) / ((h_y * h_y)) + (r7 - 6.01250601e-5F * (usol[t1][x - time + 6][y - time + 12][z + 12] + usol[t1][x - time + 18][y - time + 12][z + 12]) + 1.03896104e-3F * (usol[t1][x - time + 7][y - time + 12][z + 12] + usol[t1][x - time + 17][y - time + 12][z + 12]) - 8.92857143e-3F * (usol[t1][x - time + 8][y - time + 12][z + 12] + usol[t1][x - time + 16][y - time + 12][z + 12]) + 5.29100529e-2F * (usol[t1][x - time + 9][y - time + 12][z + 12] + usol[t1][x - time + 15][y - time + 12][z + 12]) - 2.67857143e-1F * (usol[t1][x - time + 10][y - time + 12][z + 12] + usol[t1][x - time + 14][y - time + 12][z + 12]) + 1.71428571F * (usol[t1][x - time + 11][y - time + 12][z + 12] + usol[t1][x - time + 13][y - time + 12][z + 12])) / ((h_x * h_x))) / (r4 * r5 + r6 * damp[x - time + 1][y - time + 1][z + 1]);
}
#pragma omp simd aligned(damp, usol, vp : 32)
for (int sp_zi = sp_zi_m; sp_zi <= nnz_sp_source_mask[x - time][y - time] - 1; sp_zi += 1)
{
int zind = sp_source_mask[x - time][y - time][sp_zi];
float r0 = save_src[((time / sf) % (time_M - time_m + 1))][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind];
usol[t0][x - time + 12][y - time + 12][zind + 12] += r0;}
}
}
}
}
}
}
}
}
}
/* End section0 */
__itt_pause();
return 0;
}
|
GB_binop__lt_uint32.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_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_uint32
// A.*B function (eWiseMult): GB_AemultB__lt_uint32
// A*D function (colscale): GB_AxD__lt_uint32
// D*A function (rowscale): GB_DxB__lt_uint32
// C+=B function (dense accum): GB_Cdense_accumB__lt_uint32
// C+=b function (dense accum): GB_Cdense_accumb__lt_uint32
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__lt_uint32
// C=scalar+B GB_bind1st__lt_uint32
// C=scalar+B' GB_bind1st_tran__lt_uint32
// C=A+scalar GB_bind2nd__lt_uint32
// C=A'+scalar GB_bind2nd_tran__lt_uint32
// C type: bool
// A type: uint32_t
// B,b type: uint32_t
// BinaryOp: cij = (aij < bij)
#define GB_ATYPE \
uint32_t
#define GB_BTYPE \
uint32_t
#define GB_CTYPE \
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) \
uint32_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint32_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
bool 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_LT || GxB_NO_UINT32 || GxB_NO_LT_UINT32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void (none)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__lt_uint32
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumB__lt_uint32
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#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_uint32
(
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 uint32_t
uint32_t bwork = (*((uint32_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_uint32
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *GB_RESTRICT Cx = (bool *) 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__lt_uint32
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *GB_RESTRICT Cx = (bool *) 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__lt_uint32
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *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__lt_uint32
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const 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__lt_uint32
(
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
bool *Cx = (bool *) Cx_output ;
uint32_t x = (*((uint32_t *) x_input)) ;
uint32_t *Bx = (uint32_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint32_t bij = Bx [p] ;
Cx [p] = (x < bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__lt_uint32
(
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 ;
bool *Cx = (bool *) Cx_output ;
uint32_t *Ax = (uint32_t *) Ax_input ;
uint32_t y = (*((uint32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint32_t aij = Ax [p] ;
Cx [p] = (aij < y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = Ax [pA] ; \
Cx [pC] = (x < aij) ; \
}
GrB_Info GB_bind1st_tran__lt_uint32
(
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 \
uint32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t x = (*((const uint32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = Ax [pA] ; \
Cx [pC] = (aij < y) ; \
}
GrB_Info GB_bind2nd_tran__lt_uint32
(
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
uint32_t y = (*((const uint32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
dgelqs.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/zgelqs.c, normal z -> d, Fri Sep 28 17:38:05 2018
*
**/
#include "plasma.h"
#include "plasma_async.h"
#include "plasma_context.h"
#include "plasma_descriptor.h"
#include "plasma_internal.h"
#include "plasma_tuning.h"
#include "plasma_types.h"
#include "plasma_workspace.h"
/***************************************************************************//**
*
* @ingroup plasma_gelqs
*
* Computes a minimum-norm solution min | A*X - B | using the
* LQ factorization A = L*Q computed by plasma_dgelqf.
*
*******************************************************************************
*
* @param[in] m
* The number of rows of the matrix A. m >= 0.
*
* @param[in] n
* The number of columns of the matrix A. n >= m >= 0.
*
* @param[in] nrhs
* The number of columns of B. nrhs >= 0.
*
* @param[in] pA
* Details of the LQ factorization of the original matrix A as returned
* by plasma_dgelqf.
*
* @param[in] lda
* The leading dimension of the array A. lda >= m.
*
* @param[in] T
* Auxiliary factorization data, computed by plasma_dgelqf.
*
* @param[in,out] pB
* On entry, pointer to the m-by-nrhs right hand side matrix B.
* On exit, the n-by-nrhs solution matrix X.
*
* @param[in] ldb
* The leading dimension of the array B. ldb >= n.
*
*******************************************************************************
*
* @retval PlasmaSuccess successful exit
* @retval < 0 if -i, the i-th argument had an illegal value
*
*******************************************************************************
*
* @sa plasma_omp_dgelqs
* @sa plasma_cgelqs
* @sa plasma_dgelqs
* @sa plasma_sgelqs
* @sa plasma_dgelqf
*
******************************************************************************/
int plasma_dgelqs(int m, int n, int nrhs,
double *pA, int lda,
plasma_desc_t T,
double *pB, int ldb)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_fatal_error("PLASMA not initialized");
return PlasmaErrorNotInitialized;
}
// Check input arguments.
if (m < 0) {
plasma_error("illegal value of m");
return -1;
}
if (n < 0 || m > n) {
plasma_error("illegal value of n");
return -2;
}
if (nrhs < 0) {
plasma_error("illegal value of nrhs");
return -3;
}
if (lda < imax(1, m)) {
plasma_error("illegal value of lda");
return -5;
}
if (ldb < imax(1, imax(1, n))) {
plasma_error("illegal value of ldb");
return -8;
}
// quick return
if (m == 0 || n == 0 || nrhs == 0)
return PlasmaSuccess;
// Tune parameters.
if (plasma->tuning)
plasma_tune_gelqf(plasma, PlasmaRealDouble, m, n);
// Set tiling parameters.
int ib = plasma->ib;
int nb = plasma->nb;
// Create tile matrices.
plasma_desc_t A;
plasma_desc_t B;
int retval;
retval = plasma_desc_general_create(PlasmaRealDouble, nb, nb,
m, n, 0, 0, m, n, &A);
if (retval != PlasmaSuccess) {
plasma_error("plasma_desc_general_create() failed");
return retval;
}
retval = plasma_desc_general_create(PlasmaRealDouble, nb, nb,
n, nrhs, 0, 0, n, nrhs, &B);
if (retval != PlasmaSuccess) {
plasma_error("plasma_desc_general_create() failed");
plasma_desc_destroy(&A);
return retval;
}
// Allocate workspace.
plasma_workspace_t work;
size_t lwork = ib*nb; // unmlq: work
retval = plasma_workspace_create(&work, lwork, PlasmaRealDouble);
if (retval != PlasmaSuccess) {
plasma_error("plasma_workspace_create() failed");
return retval;
}
// Initialize sequence.
plasma_sequence_t sequence;
retval = plasma_sequence_init(&sequence);
// Initialize request.
plasma_request_t request;
retval = plasma_request_init(&request);
// asynchronous block
#pragma omp parallel
#pragma omp master
{
// Translate to tile layout.
plasma_omp_dge2desc(pA, lda, A, &sequence, &request);
plasma_omp_dge2desc(pB, ldb, B, &sequence, &request);
// Call the tile async function.
plasma_omp_dgelqs(A, T, B, work, &sequence, &request);
// Translate back to LAPACK layout.
plasma_omp_ddesc2ge(B, pB, ldb, &sequence, &request);
}
// implicit synchronization
plasma_workspace_destroy(&work);
// Free matrices in tile layout.
plasma_desc_destroy(&A);
plasma_desc_destroy(&B);
// Return status.
int status = sequence.status;
return status;
}
/***************************************************************************//**
*
* @ingroup plasma_gelqs
*
* Computes a minimum-norm solution using previously computed LQ factorization.
* Non-blocking tile version of plasma_dgelqs().
* May return before the computation is finished.
* Allows for pipelining of operations at runtime.
*
*******************************************************************************
*
* @param[in] A
* Descriptor of matrix A.
* A is stored in the tile layout.
*
* @param[in] T
* Descriptor of matrix T.
* Auxiliary factorization data, computed by plasma_dgelqf.
*
* @param[in,out] B
* Descriptor of matrix B.
* On entry, right-hand side matrix B in the tile layout.
* On exit, solution matrix X in the tile layout.
*
* @param[in] work
* Workspace for the auxiliary arrays needed by some coreblas kernels.
* For multiplication by Q contains preallocated space for work
* arrays. Allocated by the plasma_workspace_create function.
*
* @param[in] sequence
* Identifies the sequence of function calls that this call belongs to
* (for completion checks and exception handling purposes).
*
* @param[out] request
* Identifies this function call (for exception handling purposes).
*
* @retval void
* Errors are returned by setting sequence->status and
* request->status to error values. The sequence->status and
* request->status should never be set to PlasmaSuccess (the
* initial values) since another async call may be setting a
* failure value at the same time.
*
*******************************************************************************
*
* @sa plasma_dgelqs
* @sa plasma_omp_cgelqs
* @sa plasma_omp_dgelqs
* @sa plasma_omp_sgelqs
* @sa plasma_omp_dgelqf
*
******************************************************************************/
void plasma_omp_dgelqs(plasma_desc_t A, plasma_desc_t T,
plasma_desc_t B, plasma_workspace_t work,
plasma_sequence_t *sequence, plasma_request_t *request)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA not initialized");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
// Check input arguments.
if (plasma_desc_check(A) != PlasmaSuccess) {
plasma_error("invalid descriptor A");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (plasma_desc_check(T) != PlasmaSuccess) {
plasma_error("invalid descriptor T");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (plasma_desc_check(B) != PlasmaSuccess) {
plasma_error("invalid descriptor B");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (sequence == NULL) {
plasma_error("NULL sequence");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (request == NULL) {
plasma_error("NULL request");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
// quick return
if (A.m == 0 || A.n == 0 || B.n == 0)
return;
// Zero the trailing block of the right-hand-side matrix.
// B has less rows than X.
plasma_pdlaset(PlasmaGeneral, 0.0, 0.0,
plasma_desc_view(B, A.m, 0, A.n - A.m, B.n),
sequence, request);
// Solve L * Y = B.
plasma_pdtrsm(PlasmaLeft, PlasmaLower, PlasmaNoTrans, PlasmaNonUnit,
1.0, plasma_desc_view(A, 0, 0, A.m, A.m),
plasma_desc_view(B, 0, 0, A.m, B.n),
sequence, request);
// Find X = Q^T * Y.
if (plasma->householder_mode == PlasmaTreeHouseholder) {
plasma_pdormlq_tree(PlasmaLeft, PlasmaTrans,
A, T, B, work,
sequence, request);
}
else {
plasma_pdormlq(PlasmaLeft, PlasmaTrans,
A, T, B, work,
sequence, request);
}
}
|
par_interp.c | /******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
#include "_hypre_parcsr_ls.h"
/*---------------------------------------------------------------------------
* hypre_BoomerAMGBuildInterp
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildInterp( hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts,
HYPRE_Int *col_offd_S_to_A,
hypre_ParCSRMatrix **P_ptr)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd);
HYPRE_BigInt *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd);
hypre_ParCSRMatrix *P;
HYPRE_BigInt *col_map_offd_P;
HYPRE_Int *tmp_map_offd = NULL;
HYPRE_Int *CF_marker_offd = NULL;
HYPRE_Int *dof_func_offd = NULL;
hypre_CSRMatrix *A_ext;
HYPRE_Real *A_ext_data = NULL;
HYPRE_Int *A_ext_i = NULL;
HYPRE_BigInt *A_ext_j = NULL;
hypre_CSRMatrix *P_diag;
hypre_CSRMatrix *P_offd;
HYPRE_Real *P_diag_data;
HYPRE_Int *P_diag_i;
HYPRE_Int *P_diag_j;
HYPRE_Real *P_offd_data;
HYPRE_Int *P_offd_i;
HYPRE_Int *P_offd_j;
HYPRE_Int P_diag_size, P_offd_size;
HYPRE_Int *P_marker, *P_marker_offd;
HYPRE_Int jj_counter,jj_counter_offd;
HYPRE_Int *jj_count, *jj_count_offd;
HYPRE_Int jj_begin_row,jj_begin_row_offd;
HYPRE_Int jj_end_row,jj_end_row_offd;
HYPRE_Int start_indexing = 0; /* start indexing for P_data at 0 */
HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int strong_f_marker;
HYPRE_Int *fine_to_coarse;
//HYPRE_Int *fine_to_coarse_offd;
HYPRE_Int *coarse_counter;
HYPRE_Int coarse_shift;
HYPRE_BigInt total_global_cpts;
//HYPRE_BigInt my_first_cpt;
HYPRE_Int num_cols_P_offd;
HYPRE_Int i,i1,i2;
HYPRE_Int j,jl,jj,jj1;
HYPRE_Int kc;
HYPRE_BigInt big_k;
HYPRE_Int start;
HYPRE_Int sgn;
HYPRE_Int c_num;
HYPRE_Real diagonal;
HYPRE_Real sum;
HYPRE_Real distribute;
HYPRE_Real zero = 0.0;
HYPRE_Real one = 1.0;
HYPRE_Int my_id;
HYPRE_Int num_procs;
HYPRE_Int num_threads;
HYPRE_Int num_sends;
HYPRE_Int index;
HYPRE_Int ns, ne, size, rest;
HYPRE_Int print_level = 0;
HYPRE_Int *int_buf_data;
HYPRE_BigInt col_1 = hypre_ParCSRMatrixFirstRowIndex(A);
HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag);
HYPRE_BigInt col_n = col_1 + (HYPRE_BigInt)local_numrows;
HYPRE_Real wall_time; /* for debugging instrumentation */
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm,&my_id);
num_threads = hypre_NumThreads();
//my_first_cpt = num_cpts_global[0];
if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1];
hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm);
/*-------------------------------------------------------------------
* Get the CF_marker data for the off-processor columns
*-------------------------------------------------------------------*/
if (debug_flag < 0)
{
debug_flag = -debug_flag;
print_level = 1;
}
if (debug_flag==4) wall_time = time_getWallclockSeconds();
if (num_cols_A_offd) CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
if (num_functions > 1 && num_cols_A_offd)
{
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
}
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(A);
comm_pkg = hypre_ParCSRMatrixCommPkg(A);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends),
HYPRE_MEMORY_HOST);
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
{
int_buf_data[index++] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, CF_marker_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
if (num_functions > 1)
{
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
}
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 1 CF_marker = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*----------------------------------------------------------------------
* Get the ghost rows of A
*---------------------------------------------------------------------*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
if (num_procs > 1)
{
A_ext = hypre_ParCSRMatrixExtractBExt(A,A,1);
A_ext_i = hypre_CSRMatrixI(A_ext);
A_ext_j = hypre_CSRMatrixBigJ(A_ext);
A_ext_data = hypre_CSRMatrixData(A_ext);
}
index = 0;
for (i=0; i < num_cols_A_offd; i++)
{
for (j=A_ext_i[i]; j < A_ext_i[i+1]; j++)
{
big_k = A_ext_j[j];
if (big_k >= col_1 && big_k < col_n)
{
A_ext_j[index] = big_k - col_1;
A_ext_data[index++] = A_ext_data[j];
}
else
{
kc = hypre_BigBinarySearch(col_map_offd,big_k,num_cols_A_offd);
if (kc > -1)
{
A_ext_j[index] = (HYPRE_BigInt)(-kc-1);
A_ext_data[index++] = A_ext_data[j];
}
}
}
A_ext_i[i] = index;
}
for (i = num_cols_A_offd; i > 0; i--)
A_ext_i[i] = A_ext_i[i-1];
if (num_procs > 1) A_ext_i[0] = 0;
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 2 Get A_ext = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*-----------------------------------------------------------------------
* First Pass: Determine size of P and fill in fine_to_coarse mapping.
*-----------------------------------------------------------------------*/
/*-----------------------------------------------------------------------
* Intialize counters and allocate mapping vector.
*-----------------------------------------------------------------------*/
coarse_counter = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_count = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_count_offd = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n_fine; i++) fine_to_coarse[i] = -1;
jj_counter = start_indexing;
jj_counter_offd = start_indexing;
/*-----------------------------------------------------------------------
* Loop over fine grid.
*-----------------------------------------------------------------------*/
/* RDF: this looks a little tricky, but doable */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,i1,jj,ns,ne,size,rest) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
size = n_fine/num_threads;
rest = n_fine - size*num_threads;
if (j < rest)
{
ns = j*size+j;
ne = (j+1)*size+j+1;
}
else
{
ns = j*size+rest;
ne = (j+1)*size+rest;
}
for (i = ns; i < ne; i++)
{
/*--------------------------------------------------------------------
* If i is a C-point, interpolation is the identity. Also set up
* mapping vector.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
jj_count[j]++;
fine_to_coarse[i] = coarse_counter[j];
coarse_counter[j]++;
}
/*--------------------------------------------------------------------
* If i is an F-point, interpolation is from the C-points that
* strongly influence i.
*--------------------------------------------------------------------*/
else
{
for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++)
{
i1 = S_diag_j[jj];
if (CF_marker[i1] >= 0)
{
jj_count[j]++;
}
}
if (num_procs > 1)
{
if (col_offd_S_to_A)
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = col_offd_S_to_A[S_offd_j[jj]];
if (CF_marker_offd[i1] >= 0)
{
jj_count_offd[j]++;
}
}
}
else
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = S_offd_j[jj];
if (CF_marker_offd[i1] >= 0)
{
jj_count_offd[j]++;
}
}
}
}
}
}
}
/*-----------------------------------------------------------------------
* Allocate arrays.
*-----------------------------------------------------------------------*/
for (i=0; i < num_threads-1; i++)
{
coarse_counter[i+1] += coarse_counter[i];
jj_count[i+1] += jj_count[i];
jj_count_offd[i+1] += jj_count_offd[i];
}
i = num_threads-1;
jj_counter = jj_count[i];
jj_counter_offd = jj_count_offd[i];
P_diag_size = jj_counter;
P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, HYPRE_MEMORY_DEVICE);
P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_DEVICE);
P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_DEVICE);
P_diag_i[n_fine] = jj_counter;
P_offd_size = jj_counter_offd;
P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, HYPRE_MEMORY_DEVICE);
P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_DEVICE);
P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_DEVICE);
/*-----------------------------------------------------------------------
* Intialize some stuff.
*-----------------------------------------------------------------------*/
jj_counter = start_indexing;
jj_counter_offd = start_indexing;
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Internal work 1 = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*-----------------------------------------------------------------------
* Send and receive fine_to_coarse info.
*-----------------------------------------------------------------------*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
//fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,ns,ne,size,rest,coarse_shift) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
coarse_shift = 0;
if (j > 0) coarse_shift = coarse_counter[j-1];
size = n_fine/num_threads;
rest = n_fine - size*num_threads;
if (j < rest)
{
ns = j*size+j;
ne = (j+1)*size+j+1;
}
else
{
ns = j*size+rest;
ne = (j+1)*size+rest;
}
for (i = ns; i < ne; i++)
{
fine_to_coarse[i] += coarse_shift;
}
//fine_to_coarse[i] += my_first_cpt+coarse_shift;
}
/*index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= fine_to_coarse[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, fine_to_coarse_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 4 FineToCoarse = %f\n",
my_id, wall_time);
fflush(NULL);
}*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
/*#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt; */
/*-----------------------------------------------------------------------
* Loop over fine grid points.
*-----------------------------------------------------------------------*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,jl,i1,i2,jj,jj1,ns,ne,size,rest,sum,diagonal,distribute,P_marker,P_marker_offd,strong_f_marker,jj_counter,jj_counter_offd,sgn,c_num,jj_begin_row,jj_end_row,jj_begin_row_offd,jj_end_row_offd) HYPRE_SMP_SCHEDULE
#endif
for (jl = 0; jl < num_threads; jl++)
{
size = n_fine/num_threads;
rest = n_fine - size*num_threads;
if (jl < rest)
{
ns = jl*size+jl;
ne = (jl+1)*size+jl+1;
}
else
{
ns = jl*size+rest;
ne = (jl+1)*size+rest;
}
jj_counter = 0;
if (jl > 0) jj_counter = jj_count[jl-1];
jj_counter_offd = 0;
if (jl > 0) jj_counter_offd = jj_count_offd[jl-1];
P_marker = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST);
if (num_cols_A_offd)
P_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
else
P_marker_offd = NULL;
for (i = 0; i < n_fine; i++)
{
P_marker[i] = -1;
}
for (i = 0; i < num_cols_A_offd; i++)
{
P_marker_offd[i] = -1;
}
strong_f_marker = -2;
for (i = ns; i < ne; i++)
{
/*--------------------------------------------------------------------
* If i is a c-point, interpolation is the identity.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
P_diag_i[i] = jj_counter;
P_diag_j[jj_counter] = fine_to_coarse[i];
P_diag_data[jj_counter] = one;
jj_counter++;
}
/*--------------------------------------------------------------------
* If i is an F-point, build interpolation.
*--------------------------------------------------------------------*/
else
{
/* Diagonal part of P */
P_diag_i[i] = jj_counter;
jj_begin_row = jj_counter;
for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++)
{
i1 = S_diag_j[jj];
/*--------------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_diag_j
* and initialize interpolation weight to zero.
*--------------------------------------------------------------*/
if (CF_marker[i1] >= 0)
{
P_marker[i1] = jj_counter;
P_diag_j[jj_counter] = fine_to_coarse[i1];
P_diag_data[jj_counter] = zero;
jj_counter++;
}
/*--------------------------------------------------------------
* If neighbor i1 is an F-point, mark it as a strong F-point
* whose connection needs to be distributed.
*--------------------------------------------------------------*/
else if (CF_marker[i1] != -3)
{
P_marker[i1] = strong_f_marker;
}
}
jj_end_row = jj_counter;
/* Off-Diagonal part of P */
P_offd_i[i] = jj_counter_offd;
jj_begin_row_offd = jj_counter_offd;
if (num_procs > 1)
{
if (col_offd_S_to_A)
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = col_offd_S_to_A[S_offd_j[jj]];
/*-----------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_offd_j
* and initialize interpolation weight to zero.
*-----------------------------------------------------------*/
if (CF_marker_offd[i1] >= 0)
{
P_marker_offd[i1] = jj_counter_offd;
/*P_offd_j[jj_counter_offd] = fine_to_coarse_offd[i1];*/
P_offd_j[jj_counter_offd] = i1;
P_offd_data[jj_counter_offd] = zero;
jj_counter_offd++;
}
/*-----------------------------------------------------------
* If neighbor i1 is an F-point, mark it as a strong F-point
* whose connection needs to be distributed.
*-----------------------------------------------------------*/
else if (CF_marker_offd[i1] != -3)
{
P_marker_offd[i1] = strong_f_marker;
}
}
}
else
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = S_offd_j[jj];
/*-----------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_offd_j
* and initialize interpolation weight to zero.
*-----------------------------------------------------------*/
if (CF_marker_offd[i1] >= 0)
{
P_marker_offd[i1] = jj_counter_offd;
/*P_offd_j[jj_counter_offd] = fine_to_coarse_offd[i1];*/
P_offd_j[jj_counter_offd] = i1;
P_offd_data[jj_counter_offd] = zero;
jj_counter_offd++;
}
/*-----------------------------------------------------------
* If neighbor i1 is an F-point, mark it as a strong F-point
* whose connection needs to be distributed.
*-----------------------------------------------------------*/
else if (CF_marker_offd[i1] != -3)
{
P_marker_offd[i1] = strong_f_marker;
}
}
}
}
jj_end_row_offd = jj_counter_offd;
diagonal = A_diag_data[A_diag_i[i]];
/* Loop over ith row of A. First, the diagonal part of A */
for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++)
{
i1 = A_diag_j[jj];
/*--------------------------------------------------------------
* Case 1: neighbor i1 is a C-point and strongly influences i,
* accumulate a_{i,i1} into the interpolation weight.
*--------------------------------------------------------------*/
if (P_marker[i1] >= jj_begin_row)
{
P_diag_data[P_marker[i1]] += A_diag_data[jj];
}
/*--------------------------------------------------------------
* Case 2: neighbor i1 is an F-point and strongly influences i,
* distribute a_{i,i1} to C-points that strongly infuence i.
* Note: currently no distribution to the diagonal in this case.
*--------------------------------------------------------------*/
else if (P_marker[i1] == strong_f_marker)
{
sum = zero;
/*-----------------------------------------------------------
* Loop over row of A for point i1 and calculate the sum
* of the connections to c-points that strongly influence i.
*-----------------------------------------------------------*/
sgn = 1;
if (A_diag_data[A_diag_i[i1]] < 0) sgn = -1;
/* Diagonal block part of row i1 */
for (jj1 = A_diag_i[i1]; jj1 < A_diag_i[i1+1]; jj1++)
{
i2 = A_diag_j[jj1];
if (P_marker[i2] >= jj_begin_row &&
(sgn*A_diag_data[jj1]) < 0)
{
sum += A_diag_data[jj1];
}
}
/* Off-Diagonal block part of row i1 */
if (num_procs > 1)
{
for (jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++)
{
i2 = A_offd_j[jj1];
if (P_marker_offd[i2] >= jj_begin_row_offd
&& (sgn*A_offd_data[jj1]) < 0)
{
sum += A_offd_data[jj1];
}
}
}
if (sum != 0)
{
distribute = A_diag_data[jj] / sum;
/*-----------------------------------------------------------
* Loop over row of A for point i1 and do the distribution.
*-----------------------------------------------------------*/
/* Diagonal block part of row i1 */
for (jj1 = A_diag_i[i1]; jj1 < A_diag_i[i1+1]; jj1++)
{
i2 = A_diag_j[jj1];
if (P_marker[i2] >= jj_begin_row
&& (sgn*A_diag_data[jj1]) < 0)
{
P_diag_data[P_marker[i2]]
+= distribute * A_diag_data[jj1];
}
}
/* Off-Diagonal block part of row i1 */
if (num_procs > 1)
{
for (jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++)
{
i2 = A_offd_j[jj1];
if (P_marker_offd[i2] >= jj_begin_row_offd
&& (sgn*A_offd_data[jj1]) < 0)
{
P_offd_data[P_marker_offd[i2]]
+= distribute * A_offd_data[jj1];
}
}
}
}
else
{
if (num_functions == 1 || dof_func[i] == dof_func[i1])
{
diagonal += A_diag_data[jj];
}
}
}
/*--------------------------------------------------------------
* Case 3: neighbor i1 weakly influences i, accumulate a_{i,i1}
* into the diagonal.
*--------------------------------------------------------------*/
else if (CF_marker[i1] != -3)
{
if (num_functions == 1 || dof_func[i] == dof_func[i1])
{
diagonal += A_diag_data[jj];
}
}
}
/*----------------------------------------------------------------
* Still looping over ith row of A. Next, loop over the
* off-diagonal part of A
*---------------------------------------------------------------*/
if (num_procs > 1)
{
for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++)
{
i1 = A_offd_j[jj];
/*--------------------------------------------------------------
* Case 1: neighbor i1 is a C-point and strongly influences i,
* accumulate a_{i,i1} into the interpolation weight.
*--------------------------------------------------------------*/
if (P_marker_offd[i1] >= jj_begin_row_offd)
{
P_offd_data[P_marker_offd[i1]] += A_offd_data[jj];
}
/*------------------------------------------------------------
* Case 2: neighbor i1 is an F-point and strongly influences i,
* distribute a_{i,i1} to C-points that strongly infuence i.
* Note: currently no distribution to the diagonal in this case.
*-----------------------------------------------------------*/
else if (P_marker_offd[i1] == strong_f_marker)
{
sum = zero;
/*---------------------------------------------------------
* Loop over row of A_ext for point i1 and calculate the sum
* of the connections to c-points that strongly influence i.
*---------------------------------------------------------*/
/* find row number */
c_num = A_offd_j[jj];
sgn = 1;
if (A_ext_data[A_ext_i[c_num]] < 0) sgn = -1;
for (jj1 = A_ext_i[c_num]; jj1 < A_ext_i[c_num+1]; jj1++)
{
i2 = (HYPRE_Int)A_ext_j[jj1];
if (i2 > -1)
{
/* in the diagonal block */
if (P_marker[i2] >= jj_begin_row
&& (sgn*A_ext_data[jj1]) < 0)
{
sum += A_ext_data[jj1];
}
}
else
{
/* in the off_diagonal block */
if (P_marker_offd[-i2-1] >= jj_begin_row_offd
&& (sgn*A_ext_data[jj1]) < 0)
{
sum += A_ext_data[jj1];
}
}
}
if (sum != 0)
{
distribute = A_offd_data[jj] / sum;
/*---------------------------------------------------------
* Loop over row of A_ext for point i1 and do
* the distribution.
*--------------------------------------------------------*/
/* Diagonal block part of row i1 */
for (jj1 = A_ext_i[c_num]; jj1 < A_ext_i[c_num+1]; jj1++)
{
i2 = (HYPRE_Int)A_ext_j[jj1];
if (i2 > -1) /* in the diagonal block */
{
if (P_marker[i2] >= jj_begin_row
&& (sgn*A_ext_data[jj1]) < 0)
{
P_diag_data[P_marker[i2]]
+= distribute * A_ext_data[jj1];
}
}
else
{
/* in the off_diagonal block */
if (P_marker_offd[-i2-1] >= jj_begin_row_offd
&& (sgn*A_ext_data[jj1]) < 0)
P_offd_data[P_marker_offd[-i2-1]]
+= distribute * A_ext_data[jj1];
}
}
}
else
{
if (num_functions == 1 || dof_func[i] == dof_func_offd[i1])
{
diagonal += A_offd_data[jj];
}
}
}
/*-----------------------------------------------------------
* Case 3: neighbor i1 weakly influences i, accumulate a_{i,i1}
* into the diagonal.
*-----------------------------------------------------------*/
else if (CF_marker_offd[i1] != -3)
{
if (num_functions == 1 || dof_func[i] == dof_func_offd[i1])
{
diagonal += A_offd_data[jj];
}
}
}
}
/*-----------------------------------------------------------------
* Set interpolation weight by dividing by the diagonal.
*-----------------------------------------------------------------*/
if (diagonal == 0.0)
{
if (print_level)
{
hypre_printf(" Warning! zero diagonal! Proc id %d row %d\n", my_id,i);
}
for (jj = jj_begin_row; jj < jj_end_row; jj++)
{
P_diag_data[jj] = 0.0;
}
for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++)
{
P_offd_data[jj] = 0.0;
}
}
else
{
for (jj = jj_begin_row; jj < jj_end_row; jj++)
{
P_diag_data[jj] /= -diagonal;
}
for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++)
{
P_offd_data[jj] /= -diagonal;
}
}
}
strong_f_marker--;
P_offd_i[i+1] = jj_counter_offd;
}
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
hypre_TFree(P_marker_offd, HYPRE_MEMORY_HOST);
}
P = hypre_ParCSRMatrixCreate(comm,
hypre_ParCSRMatrixGlobalNumRows(A),
total_global_cpts,
hypre_ParCSRMatrixColStarts(A),
num_cpts_global,
0,
P_diag_i[n_fine],
P_offd_i[n_fine]);
P_diag = hypre_ParCSRMatrixDiag(P);
hypre_CSRMatrixData(P_diag) = P_diag_data;
hypre_CSRMatrixI(P_diag) = P_diag_i;
hypre_CSRMatrixJ(P_diag) = P_diag_j;
P_offd = hypre_ParCSRMatrixOffd(P);
hypre_CSRMatrixData(P_offd) = P_offd_data;
hypre_CSRMatrixI(P_offd) = P_offd_i;
hypre_CSRMatrixJ(P_offd) = P_offd_j;
hypre_ParCSRMatrixOwnsRowStarts(P) = 0;
/* Compress P, removing coefficients smaller than trunc_factor * Max */
if (trunc_factor != 0.0 || max_elmts > 0)
{
hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts);
P_diag_data = hypre_CSRMatrixData(P_diag);
P_diag_i = hypre_CSRMatrixI(P_diag);
P_diag_j = hypre_CSRMatrixJ(P_diag);
P_offd_data = hypre_CSRMatrixData(P_offd);
P_offd_i = hypre_CSRMatrixI(P_offd);
P_offd_j = hypre_CSRMatrixJ(P_offd);
P_diag_size = P_diag_i[n_fine];
P_offd_size = P_offd_i[n_fine];
}
num_cols_P_offd = 0;
if (P_offd_size)
{
P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i=0; i < num_cols_A_offd; i++)
{
P_marker[i] = 0;
}
num_cols_P_offd = 0;
for (i=0; i < P_offd_size; i++)
{
index = P_offd_j[i];
if (!P_marker[index])
{
num_cols_P_offd++;
P_marker[index] = 1;
}
}
col_map_offd_P = hypre_CTAlloc(HYPRE_BigInt, num_cols_P_offd, HYPRE_MEMORY_HOST);
tmp_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST);
index = 0;
for (i=0; i < num_cols_P_offd; i++)
{
while (P_marker[index]==0) index++;
tmp_map_offd[i] = index++;
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i=0; i < P_offd_size; i++)
P_offd_j[i] = hypre_BinarySearch(tmp_map_offd,
P_offd_j[i],
num_cols_P_offd);
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
}
for (i=0; i < n_fine; i++)
{
if (CF_marker[i] == -3) CF_marker[i] = -1;
}
if (num_cols_P_offd)
{
hypre_ParCSRMatrixColMapOffd(P) = col_map_offd_P;
hypre_CSRMatrixNumCols(P_offd) = num_cols_P_offd;
}
hypre_GetCommPkgRTFromCommPkgA(P,A, fine_to_coarse, tmp_map_offd);
*P_ptr = P;
hypre_TFree(tmp_map_offd, HYPRE_MEMORY_HOST);
hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST);
hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST);
hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST);
hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST);
//hypre_TFree(fine_to_coarse_offd, HYPRE_MEMORY_HOST);
hypre_TFree(coarse_counter, HYPRE_MEMORY_HOST);
hypre_TFree(jj_count, HYPRE_MEMORY_HOST);
hypre_TFree(jj_count_offd, HYPRE_MEMORY_HOST);
if (num_procs > 1) hypre_CSRMatrixDestroy(A_ext);
return hypre_error_flag;
}
/*---------------------------------------------------------------------------
* hypre_BoomerAMGBuildInterpHE
* interpolation routine for hyperbolic PDEs
* treats weak fine connections like strong fine connections
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildInterpHE( hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts,
HYPRE_Int *col_offd_S_to_A,
hypre_ParCSRMatrix **P_ptr)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd);
HYPRE_BigInt *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd);
hypre_ParCSRMatrix *P;
HYPRE_BigInt *col_map_offd_P;
HYPRE_Int *tmp_map_offd = NULL;
HYPRE_Int *CF_marker_offd = NULL;
HYPRE_Int *dof_func_offd = NULL;
hypre_CSRMatrix *A_ext;
HYPRE_Real *A_ext_data = NULL;
HYPRE_Int *A_ext_i = NULL;
HYPRE_BigInt *A_ext_j = NULL;
hypre_CSRMatrix *P_diag;
hypre_CSRMatrix *P_offd;
HYPRE_Real *P_diag_data;
HYPRE_Int *P_diag_i;
HYPRE_Int *P_diag_j;
HYPRE_Real *P_offd_data;
HYPRE_Int *P_offd_i;
HYPRE_Int *P_offd_j;
HYPRE_Int P_diag_size, P_offd_size;
HYPRE_Int *P_marker, *P_marker_offd;
HYPRE_Int jj_counter,jj_counter_offd;
HYPRE_Int *jj_count, *jj_count_offd;
HYPRE_Int jj_begin_row,jj_begin_row_offd;
HYPRE_Int jj_end_row,jj_end_row_offd;
HYPRE_Int start_indexing = 0; /* start indexing for P_data at 0 */
HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int *fine_to_coarse;
//HYPRE_Int *fine_to_coarse_offd;
HYPRE_Int *coarse_counter;
HYPRE_Int coarse_shift;
HYPRE_BigInt total_global_cpts;
//HYPRE_BigInt my_first_cpt;
HYPRE_Int num_cols_P_offd;
HYPRE_Int i,i1,i2;
HYPRE_Int j,jl,jj,jj1;
HYPRE_Int kc;
HYPRE_BigInt big_k;
HYPRE_Int start;
HYPRE_Int sgn;
HYPRE_Int c_num;
HYPRE_Real diagonal;
HYPRE_Real sum;
HYPRE_Real distribute;
HYPRE_Real zero = 0.0;
HYPRE_Real one = 1.0;
HYPRE_Int my_id;
HYPRE_Int num_procs;
HYPRE_Int num_threads;
HYPRE_Int num_sends;
HYPRE_Int index;
HYPRE_Int ns, ne, size, rest;
HYPRE_Int *int_buf_data;
HYPRE_BigInt col_1 = hypre_ParCSRMatrixFirstRowIndex(A);
HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag);
HYPRE_BigInt col_n = col_1 + local_numrows;
HYPRE_Real wall_time; /* for debugging instrumentation */
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm,&my_id);
num_threads = hypre_NumThreads();
//my_first_cpt = num_cpts_global[0];
if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1];
hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm);
/*-------------------------------------------------------------------
* Get the CF_marker data for the off-processor columns
*-------------------------------------------------------------------*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
if (num_cols_A_offd) CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
if (num_functions > 1 && num_cols_A_offd)
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(A);
comm_pkg = hypre_ParCSRMatrixCommPkg(A);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends),
HYPRE_MEMORY_HOST);
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, CF_marker_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
if (num_functions > 1)
{
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
}
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 1 CF_marker = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*----------------------------------------------------------------------
* Get the ghost rows of A
*---------------------------------------------------------------------*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
if (num_procs > 1)
{
A_ext = hypre_ParCSRMatrixExtractBExt(A,A,1);
A_ext_i = hypre_CSRMatrixI(A_ext);
A_ext_j = hypre_CSRMatrixBigJ(A_ext);
A_ext_data = hypre_CSRMatrixData(A_ext);
}
index = 0;
for (i=0; i < num_cols_A_offd; i++)
{
for (j=A_ext_i[i]; j < A_ext_i[i+1]; j++)
{
big_k = A_ext_j[j];
if (big_k >= col_1 && big_k < col_n)
{
A_ext_j[index] = big_k - col_1;
A_ext_data[index++] = A_ext_data[j];
}
else
{
kc = hypre_BigBinarySearch(col_map_offd,big_k,num_cols_A_offd);
if (kc > -1)
{
A_ext_j[index] = (HYPRE_BigInt)(-kc-1);
A_ext_data[index++] = A_ext_data[j];
}
}
}
A_ext_i[i] = index;
}
for (i = num_cols_A_offd; i > 0; i--)
A_ext_i[i] = A_ext_i[i-1];
if (num_procs > 1) A_ext_i[0] = 0;
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 2 Get A_ext = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*-----------------------------------------------------------------------
* First Pass: Determine size of P and fill in fine_to_coarse mapping.
*-----------------------------------------------------------------------*/
/*-----------------------------------------------------------------------
* Intialize counters and allocate mapping vector.
*-----------------------------------------------------------------------*/
coarse_counter = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_count = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_count_offd = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n_fine; i++) fine_to_coarse[i] = -1;
jj_counter = start_indexing;
jj_counter_offd = start_indexing;
/*-----------------------------------------------------------------------
* Loop over fine grid.
*-----------------------------------------------------------------------*/
/* RDF: this looks a little tricky, but doable */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,i1,jj,ns,ne,size,rest) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
size = n_fine/num_threads;
rest = n_fine - size*num_threads;
if (j < rest)
{
ns = j*size+j;
ne = (j+1)*size+j+1;
}
else
{
ns = j*size+rest;
ne = (j+1)*size+rest;
}
for (i = ns; i < ne; i++)
{
/*--------------------------------------------------------------------
* If i is a C-point, interpolation is the identity. Also set up
* mapping vector.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
jj_count[j]++;
fine_to_coarse[i] = coarse_counter[j];
coarse_counter[j]++;
}
/*--------------------------------------------------------------------
* If i is an F-point, interpolation is from the C-points that
* strongly influence i.
*--------------------------------------------------------------------*/
else
{
for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++)
{
i1 = S_diag_j[jj];
if (CF_marker[i1] >= 0)
{
jj_count[j]++;
}
}
if (num_procs > 1)
{
if (col_offd_S_to_A)
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = col_offd_S_to_A[S_offd_j[jj]];
if (CF_marker_offd[i1] >= 0)
{
jj_count_offd[j]++;
}
}
}
else
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = S_offd_j[jj];
if (CF_marker_offd[i1] >= 0)
{
jj_count_offd[j]++;
}
}
}
}
}
}
}
/*-----------------------------------------------------------------------
* Allocate arrays.
*-----------------------------------------------------------------------*/
for (i=0; i < num_threads-1; i++)
{
coarse_counter[i+1] += coarse_counter[i];
jj_count[i+1] += jj_count[i];
jj_count_offd[i+1] += jj_count_offd[i];
}
i = num_threads-1;
jj_counter = jj_count[i];
jj_counter_offd = jj_count_offd[i];
P_diag_size = jj_counter;
P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, HYPRE_MEMORY_HOST);
P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_HOST);
P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_HOST);
P_diag_i[n_fine] = jj_counter;
P_offd_size = jj_counter_offd;
P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, HYPRE_MEMORY_HOST);
P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST);
P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_HOST);
/*-----------------------------------------------------------------------
* Intialize some stuff.
*-----------------------------------------------------------------------*/
jj_counter = start_indexing;
jj_counter_offd = start_indexing;
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Internal work 1 = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*-----------------------------------------------------------------------
* Send and receive fine_to_coarse info.
*-----------------------------------------------------------------------*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
//fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,ns,ne,size,rest,coarse_shift) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
coarse_shift = 0;
if (j > 0) coarse_shift = coarse_counter[j-1];
size = n_fine/num_threads;
rest = n_fine - size*num_threads;
if (j < rest)
{
ns = j*size+j;
ne = (j+1)*size+j+1;
}
else
{
ns = j*size+rest;
ne = (j+1)*size+rest;
}
for (i = ns; i < ne; i++)
fine_to_coarse[i] += coarse_shift;
}
/*index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= fine_to_coarse[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
fine_to_coarse_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 4 FineToCoarse = %f\n",
my_id, wall_time);
fflush(NULL);
}*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
/*#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt;*/
/*-----------------------------------------------------------------------
* Loop over fine grid points.
*-----------------------------------------------------------------------*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,jl,i1,i2,jj,jj1,ns,ne,size,rest,sum,diagonal,distribute,P_marker,P_marker_offd,jj_counter,jj_counter_offd,sgn,c_num,jj_begin_row,jj_end_row,jj_begin_row_offd,jj_end_row_offd) HYPRE_SMP_SCHEDULE
#endif
for (jl = 0; jl < num_threads; jl++)
{
size = n_fine/num_threads;
rest = n_fine - size*num_threads;
if (jl < rest)
{
ns = jl*size+jl;
ne = (jl+1)*size+jl+1;
}
else
{
ns = jl*size+rest;
ne = (jl+1)*size+rest;
}
jj_counter = 0;
if (jl > 0) jj_counter = jj_count[jl-1];
jj_counter_offd = 0;
if (jl > 0) jj_counter_offd = jj_count_offd[jl-1];
P_marker = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST);
if (num_cols_A_offd)
P_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
else
P_marker_offd = NULL;
for (i = 0; i < n_fine; i++)
{
P_marker[i] = -1;
}
for (i = 0; i < num_cols_A_offd; i++)
{
P_marker_offd[i] = -1;
}
for (i = ns; i < ne; i++)
{
/*--------------------------------------------------------------------
* If i is a c-point, interpolation is the identity.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
P_diag_i[i] = jj_counter;
P_diag_j[jj_counter] = fine_to_coarse[i];
P_diag_data[jj_counter] = one;
jj_counter++;
}
/*--------------------------------------------------------------------
* If i is an F-point, build interpolation.
*--------------------------------------------------------------------*/
else
{
/* Diagonal part of P */
P_diag_i[i] = jj_counter;
jj_begin_row = jj_counter;
for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++)
{
i1 = S_diag_j[jj];
/*--------------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_diag_j
* and initialize interpolation weight to zero.
*--------------------------------------------------------------*/
if (CF_marker[i1] >= 0)
{
P_marker[i1] = jj_counter;
P_diag_j[jj_counter] = fine_to_coarse[i1];
P_diag_data[jj_counter] = zero;
jj_counter++;
}
}
jj_end_row = jj_counter;
/* Off-Diagonal part of P */
P_offd_i[i] = jj_counter_offd;
jj_begin_row_offd = jj_counter_offd;
if (num_procs > 1)
{
if (col_offd_S_to_A)
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = col_offd_S_to_A[S_offd_j[jj]];
/*-----------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_offd_j
* and initialize interpolation weight to zero.
*-----------------------------------------------------------*/
if (CF_marker_offd[i1] >= 0)
{
P_marker_offd[i1] = jj_counter_offd;
P_offd_j[jj_counter_offd] = i1;
P_offd_data[jj_counter_offd] = zero;
jj_counter_offd++;
}
}
}
else
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = S_offd_j[jj];
/*-----------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_offd_j
* and initialize interpolation weight to zero.
*-----------------------------------------------------------*/
if (CF_marker_offd[i1] >= 0)
{
P_marker_offd[i1] = jj_counter_offd;
P_offd_j[jj_counter_offd] = i1;
P_offd_data[jj_counter_offd] = zero;
jj_counter_offd++;
}
}
}
}
jj_end_row_offd = jj_counter_offd;
diagonal = A_diag_data[A_diag_i[i]];
/* Loop over ith row of A. First, the diagonal part of A */
for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++)
{
i1 = A_diag_j[jj];
/*--------------------------------------------------------------
* Case 1: neighbor i1 is a C-point and strongly influences i,
* accumulate a_{i,i1} into the interpolation weight.
*--------------------------------------------------------------*/
if (P_marker[i1] >= jj_begin_row)
{
P_diag_data[P_marker[i1]] += A_diag_data[jj];
}
/*--------------------------------------------------------------
* Case 2: neighbor i1 is an F-point and influences i,
* distribute a_{i,i1} to C-points that strongly influence i.
* Note: currently no distribution to the diagonal in this case.
*--------------------------------------------------------------*/
else
{
sum = zero;
/*-----------------------------------------------------------
* Loop over row of A for point i1 and calculate the sum
* of the connections to c-points that strongly influence i.
*-----------------------------------------------------------*/
sgn = 1;
if (A_diag_data[A_diag_i[i1]] < 0) sgn = -1;
/* Diagonal block part of row i1 */
for (jj1 = A_diag_i[i1]; jj1 < A_diag_i[i1+1]; jj1++)
{
i2 = A_diag_j[jj1];
if (P_marker[i2] >= jj_begin_row &&
(sgn*A_diag_data[jj1]) < 0)
{
sum += A_diag_data[jj1];
}
}
/* Off-Diagonal block part of row i1 */
if (num_procs > 1)
{
for (jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++)
{
i2 = A_offd_j[jj1];
if (P_marker_offd[i2] >= jj_begin_row_offd
&& (sgn*A_offd_data[jj1]) < 0)
{
sum += A_offd_data[jj1];
}
}
}
if (sum != 0)
{
distribute = A_diag_data[jj] / sum;
/*-----------------------------------------------------------
* Loop over row of A for point i1 and do the distribution.
*-----------------------------------------------------------*/
/* Diagonal block part of row i1 */
for (jj1 = A_diag_i[i1]; jj1 < A_diag_i[i1+1]; jj1++)
{
i2 = A_diag_j[jj1];
if (P_marker[i2] >= jj_begin_row
&& (sgn*A_diag_data[jj1]) < 0)
{
P_diag_data[P_marker[i2]]
+= distribute * A_diag_data[jj1];
}
}
/* Off-Diagonal block part of row i1 */
if (num_procs > 1)
{
for (jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++)
{
i2 = A_offd_j[jj1];
if (P_marker_offd[i2] >= jj_begin_row_offd
&& (sgn*A_offd_data[jj1]) < 0)
{
P_offd_data[P_marker_offd[i2]]
+= distribute * A_offd_data[jj1];
}
}
}
}
else
{
if (num_functions == 1 || dof_func[i] == dof_func[i1])
diagonal += A_diag_data[jj];
}
}
}
/*----------------------------------------------------------------
* Still looping over ith row of A. Next, loop over the
* off-diagonal part of A
*---------------------------------------------------------------*/
if (num_procs > 1)
{
for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++)
{
i1 = A_offd_j[jj];
/*--------------------------------------------------------------
* Case 1: neighbor i1 is a C-point and strongly influences i,
* accumulate a_{i,i1} into the interpolation weight.
*--------------------------------------------------------------*/
if (P_marker_offd[i1] >= jj_begin_row_offd)
{
P_offd_data[P_marker_offd[i1]] += A_offd_data[jj];
}
/*------------------------------------------------------------
* Case 2: neighbor i1 is an F-point and influences i,
* distribute a_{i,i1} to C-points that strongly infuence i.
* Note: currently no distribution to the diagonal in this case.
*-----------------------------------------------------------*/
else
{
sum = zero;
/*---------------------------------------------------------
* Loop over row of A_ext for point i1 and calculate the sum
* of the connections to c-points that strongly influence i.
*---------------------------------------------------------*/
/* find row number */
c_num = A_offd_j[jj];
sgn = 1;
if (A_ext_data[A_ext_i[c_num]] < 0) sgn = -1;
for (jj1 = A_ext_i[c_num]; jj1 < A_ext_i[c_num+1]; jj1++)
{
i2 = (HYPRE_Int)A_ext_j[jj1];
if (i2 > -1)
{
/* in the diagonal block */
if (P_marker[i2] >= jj_begin_row
&& (sgn*A_ext_data[jj1]) < 0)
{
sum += A_ext_data[jj1];
}
}
else
{
/* in the off_diagonal block */
if (P_marker_offd[-i2-1] >= jj_begin_row_offd
&& (sgn*A_ext_data[jj1]) < 0)
{
sum += A_ext_data[jj1];
}
}
}
if (sum != 0)
{
distribute = A_offd_data[jj] / sum;
/*---------------------------------------------------------
* Loop over row of A_ext for point i1 and do
* the distribution.
*--------------------------------------------------------*/
/* Diagonal block part of row i1 */
for (jj1 = A_ext_i[c_num]; jj1 < A_ext_i[c_num+1]; jj1++)
{
i2 = (HYPRE_Int)A_ext_j[jj1];
if (i2 > -1) /* in the diagonal block */
{
if (P_marker[i2] >= jj_begin_row
&& (sgn*A_ext_data[jj1]) < 0)
{
P_diag_data[P_marker[i2]]
+= distribute * A_ext_data[jj1];
}
}
else
{
/* in the off_diagonal block */
if (P_marker_offd[-i2-1] >= jj_begin_row_offd
&& (sgn*A_ext_data[jj1]) < 0)
P_offd_data[P_marker_offd[-i2-1]]
+= distribute * A_ext_data[jj1];
}
}
}
else
{
if (num_functions == 1 || dof_func[i] == dof_func_offd[i1])
diagonal += A_offd_data[jj];
}
}
}
}
/*-----------------------------------------------------------------
* Set interpolation weight by dividing by the diagonal.
*-----------------------------------------------------------------*/
for (jj = jj_begin_row; jj < jj_end_row; jj++)
{
P_diag_data[jj] /= -diagonal;
}
for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++)
{
P_offd_data[jj] /= -diagonal;
}
}
P_offd_i[i+1] = jj_counter_offd;
}
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
hypre_TFree(P_marker_offd, HYPRE_MEMORY_HOST);
}
P = hypre_ParCSRMatrixCreate(comm,
hypre_ParCSRMatrixGlobalNumRows(A),
total_global_cpts,
hypre_ParCSRMatrixColStarts(A),
num_cpts_global,
0,
P_diag_i[n_fine],
P_offd_i[n_fine]);
P_diag = hypre_ParCSRMatrixDiag(P);
hypre_CSRMatrixData(P_diag) = P_diag_data;
hypre_CSRMatrixI(P_diag) = P_diag_i;
hypre_CSRMatrixJ(P_diag) = P_diag_j;
P_offd = hypre_ParCSRMatrixOffd(P);
hypre_CSRMatrixData(P_offd) = P_offd_data;
hypre_CSRMatrixI(P_offd) = P_offd_i;
hypre_CSRMatrixJ(P_offd) = P_offd_j;
hypre_ParCSRMatrixOwnsRowStarts(P) = 0;
/* Compress P, removing coefficients smaller than trunc_factor * Max */
if (trunc_factor != 0.0 || max_elmts > 0)
{
hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts);
P_diag_data = hypre_CSRMatrixData(P_diag);
P_diag_i = hypre_CSRMatrixI(P_diag);
P_diag_j = hypre_CSRMatrixJ(P_diag);
P_offd_data = hypre_CSRMatrixData(P_offd);
P_offd_i = hypre_CSRMatrixI(P_offd);
P_offd_j = hypre_CSRMatrixJ(P_offd);
P_diag_size = P_diag_i[n_fine];
P_offd_size = P_offd_i[n_fine];
}
num_cols_P_offd = 0;
if (P_offd_size)
{
P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i=0; i < num_cols_A_offd; i++)
P_marker[i] = 0;
num_cols_P_offd = 0;
for (i=0; i < P_offd_size; i++)
{
index = P_offd_j[i];
if (!P_marker[index])
{
num_cols_P_offd++;
P_marker[index] = 1;
}
}
col_map_offd_P = hypre_CTAlloc(HYPRE_BigInt, num_cols_P_offd, HYPRE_MEMORY_HOST);
tmp_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST);
index = 0;
for (i=0; i < num_cols_P_offd; i++)
{
while (P_marker[index]==0) index++;
tmp_map_offd[i] = index++;
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i=0; i < P_offd_size; i++)
P_offd_j[i] = hypre_BinarySearch(tmp_map_offd,
P_offd_j[i],
num_cols_P_offd);
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
}
for (i=0; i < n_fine; i++)
if (CF_marker[i] == -3) CF_marker[i] = -1;
if (num_cols_P_offd)
{
hypre_ParCSRMatrixColMapOffd(P) = col_map_offd_P;
hypre_CSRMatrixNumCols(P_offd) = num_cols_P_offd;
}
hypre_GetCommPkgRTFromCommPkgA(P,A,fine_to_coarse, tmp_map_offd);
*P_ptr = P;
hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST);
hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST);
hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST);
hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST);
hypre_TFree(tmp_map_offd, HYPRE_MEMORY_HOST);
hypre_TFree(coarse_counter, HYPRE_MEMORY_HOST);
hypre_TFree(jj_count, HYPRE_MEMORY_HOST);
hypre_TFree(jj_count_offd, HYPRE_MEMORY_HOST);
if (num_procs > 1)
{
hypre_CSRMatrixDestroy(A_ext);
}
return hypre_error_flag;
}
/*---------------------------------------------------------------------------
* hypre_BoomerAMGBuildDirInterp
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildDirInterpHost( hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts,
HYPRE_Int *col_offd_S_to_A,
hypre_ParCSRMatrix **P_ptr)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd);
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd);
hypre_ParCSRMatrix *P;
HYPRE_BigInt *col_map_offd_P;
HYPRE_Int *tmp_map_offd = NULL;
HYPRE_Int *CF_marker_offd = NULL;
HYPRE_Int *dof_func_offd = NULL;
hypre_CSRMatrix *P_diag;
hypre_CSRMatrix *P_offd;
HYPRE_Real *P_diag_data;
HYPRE_Int *P_diag_i;
HYPRE_Int *P_diag_j;
HYPRE_Real *P_offd_data;
HYPRE_Int *P_offd_i;
HYPRE_Int *P_offd_j;
HYPRE_Int P_diag_size, P_offd_size;
HYPRE_Int jj_counter,jj_counter_offd;
HYPRE_Int *jj_count, *jj_count_offd;
HYPRE_Int jj_begin_row,jj_begin_row_offd;
HYPRE_Int jj_end_row,jj_end_row_offd;
HYPRE_Int start_indexing = 0; /* start indexing for P_data at 0 */
HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int *fine_to_coarse;
HYPRE_Int *coarse_counter;
HYPRE_Int coarse_shift;
HYPRE_BigInt total_global_cpts;
HYPRE_Int num_cols_P_offd;
//HYPRE_BigInt my_first_cpt;
HYPRE_Int i,i1;
HYPRE_Int j,jl,jj;
HYPRE_Int start;
HYPRE_Real diagonal;
HYPRE_Real sum_N_pos, sum_P_pos;
HYPRE_Real sum_N_neg, sum_P_neg;
HYPRE_Real alfa = 1.0;
HYPRE_Real beta = 1.0;
HYPRE_Real zero = 0.0;
HYPRE_Real one = 1.0;
HYPRE_Int my_id;
HYPRE_Int num_procs;
HYPRE_Int num_threads;
HYPRE_Int num_sends;
HYPRE_Int index;
HYPRE_Int ns, ne, size, rest;
HYPRE_Int *int_buf_data;
HYPRE_Real wall_time; /* for debugging instrumentation */
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm,&my_id);
num_threads = hypre_NumThreads();
//my_first_cpt = num_cpts_global[0];
if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1];
hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm);
/*-------------------------------------------------------------------
* Get the CF_marker data for the off-processor columns
*-------------------------------------------------------------------*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
if (num_cols_A_offd) CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
if (num_functions > 1 && num_cols_A_offd)
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(A);
comm_pkg = hypre_ParCSRMatrixCommPkg(A);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg,
num_sends), HYPRE_MEMORY_HOST);
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
CF_marker_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
if (num_functions > 1)
{
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
}
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 1 CF_marker = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*-----------------------------------------------------------------------
* First Pass: Determine size of P and fill in fine_to_coarse mapping.
*-----------------------------------------------------------------------*/
/*-----------------------------------------------------------------------
* Intialize counters and allocate mapping vector.
*-----------------------------------------------------------------------*/
coarse_counter = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_count = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_count_offd = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n_fine; i++) fine_to_coarse[i] = -1;
jj_counter = start_indexing;
jj_counter_offd = start_indexing;
/*-----------------------------------------------------------------------
* Loop over fine grid.
*-----------------------------------------------------------------------*/
/* RDF: this looks a little tricky, but doable */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,i1,jj,ns,ne,size,rest) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
size = n_fine/num_threads;
rest = n_fine - size*num_threads;
if (j < rest)
{
ns = j*size+j;
ne = (j+1)*size+j+1;
}
else
{
ns = j*size+rest;
ne = (j+1)*size+rest;
}
for (i = ns; i < ne; i++)
{
/*--------------------------------------------------------------------
* If i is a C-point, interpolation is the identity. Also set up
* mapping vector.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
jj_count[j]++;
fine_to_coarse[i] = coarse_counter[j];
coarse_counter[j]++;
}
/*--------------------------------------------------------------------
* If i is an F-point, interpolation is from the C-points that
* strongly influence i.
*--------------------------------------------------------------------*/
else
{
for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++)
{
i1 = S_diag_j[jj];
if (CF_marker[i1] > 0)
{
jj_count[j]++;
}
}
if (num_procs > 1)
{
if (col_offd_S_to_A)
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = col_offd_S_to_A[S_offd_j[jj]];
if (CF_marker_offd[i1] > 0)
{
jj_count_offd[j]++;
}
}
}
else
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = S_offd_j[jj];
if (CF_marker_offd[i1] > 0)
{
jj_count_offd[j]++;
}
}
}
}
}
}
}
/*-----------------------------------------------------------------------
* Allocate arrays.
*-----------------------------------------------------------------------*/
for (i=0; i < num_threads-1; i++)
{
coarse_counter[i+1] += coarse_counter[i];
jj_count[i+1] += jj_count[i];
jj_count_offd[i+1] += jj_count_offd[i];
}
i = num_threads-1;
jj_counter = jj_count[i];
jj_counter_offd = jj_count_offd[i];
P_diag_size = jj_counter;
P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, HYPRE_MEMORY_DEVICE);
P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_DEVICE);
P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_DEVICE);
P_diag_i[n_fine] = jj_counter;
P_offd_size = jj_counter_offd;
P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, HYPRE_MEMORY_DEVICE);
P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_DEVICE);
P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_DEVICE);
/*-----------------------------------------------------------------------
* Intialize some stuff.
*-----------------------------------------------------------------------*/
jj_counter = start_indexing;
jj_counter_offd = start_indexing;
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Internal work 1 = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*-----------------------------------------------------------------------
* Send and receive fine_to_coarse info.
*-----------------------------------------------------------------------*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
//fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,ns,ne,size,rest,coarse_shift) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
coarse_shift = 0;
if (j > 0) coarse_shift = coarse_counter[j-1];
size = n_fine/num_threads;
rest = n_fine - size*num_threads;
if (j < rest)
{
ns = j*size+j;
ne = (j+1)*size+j+1;
}
else
{
ns = j*size+rest;
ne = (j+1)*size+rest;
}
for (i = ns; i < ne; i++)
{
fine_to_coarse[i] += coarse_shift;
}
}
/*index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= fine_to_coarse[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
fine_to_coarse_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 4 FineToCoarse = %f\n",
my_id, wall_time);
fflush(NULL);
}*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
/*#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt;*/
/*-----------------------------------------------------------------------
* Loop over fine grid points.
*-----------------------------------------------------------------------*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,jl,i1,jj,ns,ne,size,rest,diagonal,jj_counter,jj_counter_offd,jj_begin_row,jj_end_row,jj_begin_row_offd,jj_end_row_offd,sum_P_pos,sum_P_neg,sum_N_pos,sum_N_neg,alfa,beta) HYPRE_SMP_SCHEDULE
#endif
for (jl = 0; jl < num_threads; jl++)
{
HYPRE_Int *P_marker, *P_marker_offd;
size = n_fine/num_threads;
rest = n_fine - size*num_threads;
if (jl < rest)
{
ns = jl*size+jl;
ne = (jl+1)*size+jl+1;
}
else
{
ns = jl*size+rest;
ne = (jl+1)*size+rest;
}
jj_counter = 0;
if (jl > 0) jj_counter = jj_count[jl-1];
jj_counter_offd = 0;
if (jl > 0) jj_counter_offd = jj_count_offd[jl-1];
P_marker = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST);
if (num_cols_A_offd)
P_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
else
P_marker_offd = NULL;
for (i = 0; i < n_fine; i++)
{
P_marker[i] = -1;
}
for (i = 0; i < num_cols_A_offd; i++)
{
P_marker_offd[i] = -1;
}
for (i = ns; i < ne; i++)
{
/*--------------------------------------------------------------------
* If i is a c-point, interpolation is the identity.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
P_diag_i[i] = jj_counter;
P_diag_j[jj_counter] = fine_to_coarse[i];
P_diag_data[jj_counter] = one;
jj_counter++;
}
/*--------------------------------------------------------------------
* If i is an F-point, build interpolation.
*--------------------------------------------------------------------*/
else
{
/* Diagonal part of P */
P_diag_i[i] = jj_counter;
jj_begin_row = jj_counter;
for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++)
{
i1 = S_diag_j[jj];
/*--------------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_diag_j
* and initialize interpolation weight to zero.
*--------------------------------------------------------------*/
if (CF_marker[i1] >= 0)
{
P_marker[i1] = jj_counter;
P_diag_j[jj_counter] = fine_to_coarse[i1];
P_diag_data[jj_counter] = zero;
jj_counter++;
}
}
jj_end_row = jj_counter;
/* Off-Diagonal part of P */
P_offd_i[i] = jj_counter_offd;
jj_begin_row_offd = jj_counter_offd;
if (num_procs > 1)
{
if (col_offd_S_to_A)
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = col_offd_S_to_A[S_offd_j[jj]];
/*-----------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_offd_j
* and initialize interpolation weight to zero.
*-----------------------------------------------------------*/
if (CF_marker_offd[i1] >= 0)
{
P_marker_offd[i1] = jj_counter_offd;
P_offd_j[jj_counter_offd] = i1;
P_offd_data[jj_counter_offd] = zero;
jj_counter_offd++;
}
}
}
else
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = S_offd_j[jj];
/*-----------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_offd_j
* and initialize interpolation weight to zero.
*-----------------------------------------------------------*/
if (CF_marker_offd[i1] >= 0)
{
P_marker_offd[i1] = jj_counter_offd;
P_offd_j[jj_counter_offd] = i1;
P_offd_data[jj_counter_offd] = zero;
jj_counter_offd++;
}
}
}
}
jj_end_row_offd = jj_counter_offd;
diagonal = A_diag_data[A_diag_i[i]];
/* Loop over ith row of A. First, the diagonal part of A */
sum_N_pos = 0;
sum_N_neg = 0;
sum_P_pos = 0;
sum_P_neg = 0;
for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++)
{
i1 = A_diag_j[jj];
if (num_functions == 1 || dof_func[i1] == dof_func[i])
{
if (A_diag_data[jj] > 0)
sum_N_pos += A_diag_data[jj];
else
sum_N_neg += A_diag_data[jj];
}
/*--------------------------------------------------------------
* Case 1: neighbor i1 is a C-point and strongly influences i,
* accumulate a_{i,i1} into the interpolation weight.
*--------------------------------------------------------------*/
if (P_marker[i1] >= jj_begin_row)
{
P_diag_data[P_marker[i1]] += A_diag_data[jj];
if (A_diag_data[jj] > 0)
sum_P_pos += A_diag_data[jj];
else
sum_P_neg += A_diag_data[jj];
}
}
/*----------------------------------------------------------------
* Still looping over ith row of A. Next, loop over the
* off-diagonal part of A
*---------------------------------------------------------------*/
if (num_procs > 1)
{
for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++)
{
i1 = A_offd_j[jj];
if (num_functions == 1 || dof_func_offd[i1] == dof_func[i])
{
if (A_offd_data[jj] > 0)
sum_N_pos += A_offd_data[jj];
else
sum_N_neg += A_offd_data[jj];
}
/*--------------------------------------------------------------
* Case 1: neighbor i1 is a C-point and strongly influences i,
* accumulate a_{i,i1} into the interpolation weight.
*--------------------------------------------------------------*/
if (P_marker_offd[i1] >= jj_begin_row_offd)
{
P_offd_data[P_marker_offd[i1]] += A_offd_data[jj];
if (A_offd_data[jj] > 0)
sum_P_pos += A_offd_data[jj];
else
sum_P_neg += A_offd_data[jj];
}
}
}
if (sum_P_neg) alfa = sum_N_neg/sum_P_neg/diagonal;
if (sum_P_pos) beta = sum_N_pos/sum_P_pos/diagonal;
/*-----------------------------------------------------------------
* Set interpolation weight by dividing by the diagonal.
*-----------------------------------------------------------------*/
for (jj = jj_begin_row; jj < jj_end_row; jj++)
{
if (P_diag_data[jj]> 0)
P_diag_data[jj] *= -beta;
else
P_diag_data[jj] *= -alfa;
}
for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++)
{
if (P_offd_data[jj]> 0)
P_offd_data[jj] *= -beta;
else
P_offd_data[jj] *= -alfa;
}
}
P_offd_i[i+1] = jj_counter_offd;
}
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
hypre_TFree(P_marker_offd, HYPRE_MEMORY_HOST);
}
P = hypre_ParCSRMatrixCreate(comm,
hypre_ParCSRMatrixGlobalNumRows(A),
total_global_cpts,
hypre_ParCSRMatrixColStarts(A),
num_cpts_global,
0,
P_diag_i[n_fine],
P_offd_i[n_fine]);
P_diag = hypre_ParCSRMatrixDiag(P);
hypre_CSRMatrixData(P_diag) = P_diag_data;
hypre_CSRMatrixI(P_diag) = P_diag_i;
hypre_CSRMatrixJ(P_diag) = P_diag_j;
P_offd = hypre_ParCSRMatrixOffd(P);
hypre_CSRMatrixData(P_offd) = P_offd_data;
hypre_CSRMatrixI(P_offd) = P_offd_i;
hypre_CSRMatrixJ(P_offd) = P_offd_j;
hypre_ParCSRMatrixOwnsRowStarts(P) = 0;
/* Compress P, removing coefficients smaller than trunc_factor * Max */
if (trunc_factor != 0.0 || max_elmts > 0)
{
hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts);
P_diag_data = hypre_CSRMatrixData(P_diag);
P_diag_i = hypre_CSRMatrixI(P_diag);
P_diag_j = hypre_CSRMatrixJ(P_diag);
P_offd_data = hypre_CSRMatrixData(P_offd);
P_offd_i = hypre_CSRMatrixI(P_offd);
P_offd_j = hypre_CSRMatrixJ(P_offd);
P_diag_size = P_diag_i[n_fine];
P_offd_size = P_offd_i[n_fine];
}
num_cols_P_offd = 0;
if (P_offd_size)
{
HYPRE_Int *P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i=0; i < num_cols_A_offd; i++)
P_marker[i] = 0;
num_cols_P_offd = 0;
for (i=0; i < P_offd_size; i++)
{
index = P_offd_j[i];
if (!P_marker[index])
{
num_cols_P_offd++;
P_marker[index] = 1;
}
}
col_map_offd_P = hypre_CTAlloc(HYPRE_BigInt, num_cols_P_offd, HYPRE_MEMORY_HOST);
tmp_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST);
index = 0;
for (i=0; i < num_cols_P_offd; i++)
{
while (P_marker[index]==0) index++;
tmp_map_offd[i] = index++;
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i=0; i < P_offd_size; i++)
{
P_offd_j[i] = hypre_BinarySearch(tmp_map_offd,
P_offd_j[i],
num_cols_P_offd);
}
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
}
for (i=0; i < n_fine; i++)
if (CF_marker[i] == -3) CF_marker[i] = -1;
if (num_cols_P_offd)
{
hypre_ParCSRMatrixColMapOffd(P) = col_map_offd_P;
hypre_CSRMatrixNumCols(P_offd) = num_cols_P_offd;
}
hypre_GetCommPkgRTFromCommPkgA(P, A, fine_to_coarse, tmp_map_offd);
*P_ptr = P;
hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST);
hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST);
hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST);
hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST);
hypre_TFree(tmp_map_offd, HYPRE_MEMORY_HOST);
hypre_TFree(coarse_counter, HYPRE_MEMORY_HOST);
hypre_TFree(jj_count, HYPRE_MEMORY_HOST);
hypre_TFree(jj_count_offd, HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
HYPRE_Int
hypre_BoomerAMGBuildDirInterp( hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts,
HYPRE_Int *col_offd_S_to_A,
HYPRE_Int interp_type,
hypre_ParCSRMatrix **P_ptr)
{
#if defined(HYPRE_USING_CUDA)
hypre_NvtxPushRange("DirInterp");
#endif
HYPRE_Int ierr = 0;
#if defined(HYPRE_USING_CUDA)
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(A) );
if (exec == HYPRE_EXEC_DEVICE)
{
ierr = hypre_BoomerAMGBuildDirInterpDevice(A,CF_marker,S,num_cpts_global,num_functions,dof_func,
debug_flag,trunc_factor,max_elmts,col_offd_S_to_A,
interp_type, P_ptr);
}
else
#endif
{
ierr = hypre_BoomerAMGBuildDirInterpHost(A,CF_marker,S,num_cpts_global,num_functions,dof_func,
debug_flag,trunc_factor,max_elmts,col_offd_S_to_A, P_ptr);
}
#if defined(HYPRE_USING_CUDA)
hypre_NvtxPopRange();
#endif
return ierr;
}
/*------------------------------------------------
* Drop entries in interpolation matrix P
* max_elmts == 0 means no limit on rownnz
*------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGInterpTruncation( hypre_ParCSRMatrix *P,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts)
{
if (trunc_factor <= 0.0 && max_elmts == 0)
{
return 0;
}
#if defined(HYPRE_USING_CUDA)
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(P) );
if (exec == HYPRE_EXEC_DEVICE)
{
return hypre_BoomerAMGInterpTruncationDevice(P, trunc_factor, max_elmts);
}
else
#endif
{
HYPRE_Int rescale = 1; // rescale P
HYPRE_Int nrm_type = 0; // Use infty-norm of row to perform treshold dropping
return hypre_ParCSRMatrixTruncate(P, trunc_factor, max_elmts, rescale, nrm_type);
}
}
/*---------------------------------------------------------------------------
* hypre_BoomerAMGBuildInterpModUnk - this is a modified interpolation for the unknown approach.
* here we need to pass in a strength matrix built on the entire matrix.
*
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildInterpModUnk( hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts,
HYPRE_Int *col_offd_S_to_A,
hypre_ParCSRMatrix **P_ptr)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd);
HYPRE_BigInt *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd);
hypre_ParCSRMatrix *P;
HYPRE_BigInt *col_map_offd_P;
HYPRE_Int *tmp_map_offd;
HYPRE_Int *CF_marker_offd = NULL;
HYPRE_Int *dof_func_offd = NULL;
hypre_CSRMatrix *A_ext;
HYPRE_Real *A_ext_data = NULL;
HYPRE_Int *A_ext_i = NULL;
HYPRE_BigInt *A_ext_j = NULL;
hypre_CSRMatrix *P_diag;
hypre_CSRMatrix *P_offd;
HYPRE_Real *P_diag_data;
HYPRE_Int *P_diag_i;
HYPRE_Int *P_diag_j;
HYPRE_Real *P_offd_data;
HYPRE_Int *P_offd_i;
HYPRE_Int *P_offd_j;
HYPRE_Int P_diag_size, P_offd_size;
HYPRE_Int *P_marker, *P_marker_offd;
HYPRE_Int jj_counter,jj_counter_offd;
HYPRE_Int *jj_count, *jj_count_offd;
HYPRE_Int jj_begin_row,jj_begin_row_offd;
HYPRE_Int jj_end_row,jj_end_row_offd;
HYPRE_Int start_indexing = 0; /* start indexing for P_data at 0 */
HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int strong_f_marker;
HYPRE_Int *fine_to_coarse;
//HYPRE_Int *fine_to_coarse_offd;
HYPRE_Int *coarse_counter;
HYPRE_Int coarse_shift;
HYPRE_BigInt total_global_cpts;
HYPRE_Int num_cols_P_offd;
//HYPRE_BigInt my_first_cpt;
HYPRE_Int i,i1,i2;
HYPRE_Int j,jl,jj,jj1;
HYPRE_Int kc;
HYPRE_BigInt big_k;
HYPRE_Int start;
HYPRE_Int sgn;
HYPRE_Int c_num;
HYPRE_Real diagonal;
HYPRE_Real sum;
HYPRE_Real distribute;
HYPRE_Real zero = 0.0;
HYPRE_Real one = 1.0;
HYPRE_Int my_id;
HYPRE_Int num_procs;
HYPRE_Int num_threads;
HYPRE_Int num_sends;
HYPRE_Int index;
HYPRE_Int ns, ne, size, rest;
HYPRE_Int print_level = 0;
HYPRE_Int *int_buf_data;
HYPRE_BigInt col_1 = hypre_ParCSRMatrixFirstRowIndex(A);
HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag);
HYPRE_BigInt col_n = col_1 + local_numrows;
HYPRE_Real wall_time; /* for debugging instrumentation */
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm,&my_id);
num_threads = hypre_NumThreads();
//my_first_cpt = num_cpts_global[0];
if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1];
hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm);
/*-------------------------------------------------------------------
* Get the CF_marker data for the off-processor columns
*-------------------------------------------------------------------*/
if (debug_flag < 0)
{
debug_flag = -debug_flag;
print_level = 1;
}
if (debug_flag==4) wall_time = time_getWallclockSeconds();
if (num_cols_A_offd) CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
if (num_functions > 1 && num_cols_A_offd)
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(A);
comm_pkg = hypre_ParCSRMatrixCommPkg(A);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg,
num_sends), HYPRE_MEMORY_HOST);
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
CF_marker_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
if (num_functions > 1)
{
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
}
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 1 CF_marker = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*----------------------------------------------------------------------
* Get the ghost rows of A
*---------------------------------------------------------------------*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
if (num_procs > 1)
{
A_ext = hypre_ParCSRMatrixExtractBExt(A,A,1);
A_ext_i = hypre_CSRMatrixI(A_ext);
A_ext_j = hypre_CSRMatrixBigJ(A_ext);
A_ext_data = hypre_CSRMatrixData(A_ext);
}
index = 0;
for (i=0; i < num_cols_A_offd; i++)
{
for (j=A_ext_i[i]; j < A_ext_i[i+1]; j++)
{
big_k = A_ext_j[j];
if (big_k >= col_1 && big_k < col_n)
{
A_ext_j[index] = big_k - col_1;
A_ext_data[index++] = A_ext_data[j];
}
else
{
kc = hypre_BigBinarySearch(col_map_offd,big_k,num_cols_A_offd);
if (kc > -1)
{
A_ext_j[index] = (HYPRE_BigInt)(-kc-1);
A_ext_data[index++] = A_ext_data[j];
}
}
}
A_ext_i[i] = index;
}
for (i = num_cols_A_offd; i > 0; i--)
A_ext_i[i] = A_ext_i[i-1];
if (num_procs > 1) A_ext_i[0] = 0;
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 2 Get A_ext = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*-----------------------------------------------------------------------
* First Pass: Determine size of P and fill in fine_to_coarse mapping.
*-----------------------------------------------------------------------*/
/*-----------------------------------------------------------------------
* Intialize counters and allocate mapping vector.
*-----------------------------------------------------------------------*/
coarse_counter = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_count = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_count_offd = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n_fine; i++) fine_to_coarse[i] = -1;
jj_counter = start_indexing;
jj_counter_offd = start_indexing;
/*-----------------------------------------------------------------------
* Loop over fine grid.
*-----------------------------------------------------------------------*/
/* RDF: this looks a little tricky, but doable */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,i1,jj,ns,ne,size,rest) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
size = n_fine/num_threads;
rest = n_fine - size*num_threads;
if (j < rest)
{
ns = j*size+j;
ne = (j+1)*size+j+1;
}
else
{
ns = j*size+rest;
ne = (j+1)*size+rest;
}
for (i = ns; i < ne; i++)
{
/*--------------------------------------------------------------------
* If i is a C-point, interpolation is the identity. Also set up
* mapping vector.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
jj_count[j]++;
fine_to_coarse[i] = coarse_counter[j];
coarse_counter[j]++;
}
/*--------------------------------------------------------------------
* If i is an F-point, interpolation is from the C-points that
* strongly influence i.
*--------------------------------------------------------------------*/
else
{
for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++)
{
i1 = S_diag_j[jj];
if (CF_marker[i1] >= 0)
{
jj_count[j]++;
}
}
if (num_procs > 1)
{
if (col_offd_S_to_A)
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = col_offd_S_to_A[S_offd_j[jj]];
if (CF_marker_offd[i1] >= 0)
{
jj_count_offd[j]++;
}
}
}
else
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = S_offd_j[jj];
if (CF_marker_offd[i1] >= 0)
{
jj_count_offd[j]++;
}
}
}
}
}
}
}
/*-----------------------------------------------------------------------
* Allocate arrays.
*-----------------------------------------------------------------------*/
for (i=0; i < num_threads-1; i++)
{
coarse_counter[i+1] += coarse_counter[i];
jj_count[i+1] += jj_count[i];
jj_count_offd[i+1] += jj_count_offd[i];
}
i = num_threads-1;
jj_counter = jj_count[i];
jj_counter_offd = jj_count_offd[i];
P_diag_size = jj_counter;
P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, HYPRE_MEMORY_HOST);
P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_HOST);
P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_HOST);
P_diag_i[n_fine] = jj_counter;
P_offd_size = jj_counter_offd;
P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, HYPRE_MEMORY_HOST);
P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST);
P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_HOST);
/*-----------------------------------------------------------------------
* Intialize some stuff.
*-----------------------------------------------------------------------*/
jj_counter = start_indexing;
jj_counter_offd = start_indexing;
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Internal work 1 = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*-----------------------------------------------------------------------
* Send and receive fine_to_coarse info.
*-----------------------------------------------------------------------*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
//fine_to_coarse_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,ns,ne,size,rest,coarse_shift) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
coarse_shift = 0;
if (j > 0) coarse_shift = coarse_counter[j-1];
size = n_fine/num_threads;
rest = n_fine - size*num_threads;
if (j < rest)
{
ns = j*size+j;
ne = (j+1)*size+j+1;
}
else
{
ns = j*size+rest;
ne = (j+1)*size+rest;
}
for (i = ns; i < ne; i++)
fine_to_coarse[i] += coarse_shift;
}
/*index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= fine_to_coarse[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
fine_to_coarse_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 4 FineToCoarse = %f\n",
my_id, wall_time);
fflush(NULL);
}*/
if (debug_flag==4) wall_time = time_getWallclockSeconds();
/*#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n_fine; i++) fine_to_coarse[i] -= my_first_cpt;*/
/*-----------------------------------------------------------------------
* Loop over fine grid points.
*-----------------------------------------------------------------------*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,jl,i1,i2,jj,jj1,ns,ne,size,rest,sum,diagonal,distribute,P_marker,P_marker_offd,strong_f_marker,jj_counter,jj_counter_offd,sgn,c_num,jj_begin_row,jj_end_row,jj_begin_row_offd,jj_end_row_offd) HYPRE_SMP_SCHEDULE
#endif
for (jl = 0; jl < num_threads; jl++)
{
size = n_fine/num_threads;
rest = n_fine - size*num_threads;
if (jl < rest)
{
ns = jl*size+jl;
ne = (jl+1)*size+jl+1;
}
else
{
ns = jl*size+rest;
ne = (jl+1)*size+rest;
}
jj_counter = 0;
if (jl > 0) jj_counter = jj_count[jl-1];
jj_counter_offd = 0;
if (jl > 0) jj_counter_offd = jj_count_offd[jl-1];
P_marker = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST);
if (num_cols_A_offd)
P_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
else
P_marker_offd = NULL;
for (i = 0; i < n_fine; i++)
{
P_marker[i] = -1;
}
for (i = 0; i < num_cols_A_offd; i++)
{
P_marker_offd[i] = -1;
}
strong_f_marker = -2;
for (i = ns; i < ne; i++)
{
/*--------------------------------------------------------------------
* If i is a c-point, interpolation is the identity.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
P_diag_i[i] = jj_counter;
P_diag_j[jj_counter] = fine_to_coarse[i];
P_diag_data[jj_counter] = one;
jj_counter++;
}
/*--------------------------------------------------------------------
* If i is an F-point, build interpolation.
*--------------------------------------------------------------------*/
else
{
/* Diagonal part of P */
P_diag_i[i] = jj_counter;
jj_begin_row = jj_counter;
for (jj = S_diag_i[i]; jj < S_diag_i[i+1]; jj++)
{
i1 = S_diag_j[jj];
/*--------------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_diag_j
* and initialize interpolation weight to zero.
*--------------------------------------------------------------*/
if (CF_marker[i1] >= 0)
{
P_marker[i1] = jj_counter;
P_diag_j[jj_counter] = fine_to_coarse[i1];
P_diag_data[jj_counter] = zero;
jj_counter++;
}
/*--------------------------------------------------------------
* If neighbor i1 is an F-point, mark it as a strong F-point
* whose connection needs to be distributed.
*--------------------------------------------------------------*/
else if (CF_marker[i1] != -3)
{
P_marker[i1] = strong_f_marker;
}
}
jj_end_row = jj_counter;
/* Off-Diagonal part of P */
P_offd_i[i] = jj_counter_offd;
jj_begin_row_offd = jj_counter_offd;
if (num_procs > 1)
{
if (col_offd_S_to_A)
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = col_offd_S_to_A[S_offd_j[jj]];
/*-----------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_offd_j
* and initialize interpolation weight to zero.
*-----------------------------------------------------------*/
if (CF_marker_offd[i1] >= 0)
{
P_marker_offd[i1] = jj_counter_offd;
/*P_offd_j[jj_counter_offd] = fine_to_coarse_offd[i1];*/
P_offd_j[jj_counter_offd] = i1;
P_offd_data[jj_counter_offd] = zero;
jj_counter_offd++;
}
/*-----------------------------------------------------------
* If neighbor i1 is an F-point, mark it as a strong F-point
* whose connection needs to be distributed.
*-----------------------------------------------------------*/
else if (CF_marker_offd[i1] != -3)
{
P_marker_offd[i1] = strong_f_marker;
}
}
}
else
{
for (jj = S_offd_i[i]; jj < S_offd_i[i+1]; jj++)
{
i1 = S_offd_j[jj];
/*-----------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_offd_j
* and initialize interpolation weight to zero.
*-----------------------------------------------------------*/
if (CF_marker_offd[i1] >= 0)
{
P_marker_offd[i1] = jj_counter_offd;
/*P_offd_j[jj_counter_offd] = fine_to_coarse_offd[i1];*/
P_offd_j[jj_counter_offd] = i1;
P_offd_data[jj_counter_offd] = zero;
jj_counter_offd++;
}
/*-----------------------------------------------------------
* If neighbor i1 is an F-point, mark it as a strong F-point
* whose connection needs to be distributed.
*-----------------------------------------------------------*/
else if (CF_marker_offd[i1] != -3)
{
P_marker_offd[i1] = strong_f_marker;
}
}
}
}
jj_end_row_offd = jj_counter_offd;
diagonal = A_diag_data[A_diag_i[i]];
/* Loop over ith row of A. First, the diagonal part of A */
for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++)
{
i1 = A_diag_j[jj];
/*--------------------------------------------------------------
* Case 1: neighbor i1 is a C-point and strongly influences i,
* accumulate a_{i,i1} into the interpolation weight.
*--------------------------------------------------------------*/
if (P_marker[i1] >= jj_begin_row)
{
P_diag_data[P_marker[i1]] += A_diag_data[jj];
}
/*--------------------------------------------------------------
* Case 2: neighbor i1 is an F-point and strongly influences i,
* distribute a_{i,i1} to C-points that strongly infuence i.
* Note: currently no distribution to the diagonal in this case.
HERE, we only want to distribut to points of the SAME function type
*--------------------------------------------------------------*/
else if (P_marker[i1] == strong_f_marker)
{
sum = zero;
/*-----------------------------------------------------------
* Loop over row of A for point i1 and calculate the sum
* of the connections to c-points that strongly influence i.
*-----------------------------------------------------------*/
sgn = 1;
if (A_diag_data[A_diag_i[i1]] < 0) sgn = -1;
/* Diagonal block part of row i1 */
for (jj1 = A_diag_i[i1]; jj1 < A_diag_i[i1+1]; jj1++)
{
i2 = A_diag_j[jj1];
if (num_functions == 1 || dof_func[i1] == dof_func[i2])
{
if (P_marker[i2] >= jj_begin_row &&
(sgn*A_diag_data[jj1]) < 0 )
{
sum += A_diag_data[jj1];
}
}
}
/* Off-Diagonal block part of row i1 */
if (num_procs > 1)
{
for (jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++)
{
i2 = A_offd_j[jj1];
if (num_functions == 1 || dof_func[i1] == dof_func[i2])
{
if (P_marker_offd[i2] >= jj_begin_row_offd
&& (sgn*A_offd_data[jj1]) < 0)
{
sum += A_offd_data[jj1];
}
}
}
}
if (sum != 0)
{
distribute = A_diag_data[jj] / sum;
/*-----------------------------------------------------------
* Loop over row of A for point i1 and do the distribution.
*-----------------------------------------------------------*/
/* Diagonal block part of row i1 */
for (jj1 = A_diag_i[i1]; jj1 < A_diag_i[i1+1]; jj1++)
{
i2 = A_diag_j[jj1];
if (num_functions == 1 || dof_func[i1] == dof_func[i2])
{
if (P_marker[i2] >= jj_begin_row
&& (sgn*A_diag_data[jj1]) < 0)
{
P_diag_data[P_marker[i2]]
+= distribute * A_diag_data[jj1];
}
}
}
/* Off-Diagonal block part of row i1 */
if (num_procs > 1)
{
for (jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1+1]; jj1++)
{
i2 = A_offd_j[jj1];
if (num_functions == 1 || dof_func[i1] == dof_func[i2])
{
if (P_marker_offd[i2] >= jj_begin_row_offd
&& (sgn*A_offd_data[jj1]) < 0)
{
P_offd_data[P_marker_offd[i2]]
+= distribute * A_offd_data[jj1];
}
}
}
}
}
else /* sum = 0 - only add to diag if the same function type */
{
if (num_functions == 1 || dof_func[i] == dof_func[i1])
diagonal += A_diag_data[jj];
}
}
/*--------------------------------------------------------------
* Case 3: neighbor i1 weakly influences i, accumulate a_{i,i1}
* into the diagonal. (only if the same function type)
*--------------------------------------------------------------*/
else if (CF_marker[i1] != -3)
{
if (num_functions == 1 || dof_func[i] == dof_func[i1])
diagonal += A_diag_data[jj];
}
}
/*----------------------------------------------------------------
* Still looping over ith row of A. Next, loop over the
* off-diagonal part of A
*---------------------------------------------------------------*/
if (num_procs > 1)
{
for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++)
{
i1 = A_offd_j[jj];
/*--------------------------------------------------------------
* Case 1: neighbor i1 is a C-point and strongly influences i,
* accumulate a_{i,i1} into the interpolation weight.
*--------------------------------------------------------------*/
if (P_marker_offd[i1] >= jj_begin_row_offd)
{
P_offd_data[P_marker_offd[i1]] += A_offd_data[jj];
}
/*------------------------------------------------------------
* Case 2: neighbor i1 is an F-point and strongly influences i,
* distribute a_{i,i1} to C-points that strongly infuence i.
* Note: currently no distribution to the diagonal in this case.
AGAIN, we only want to distribut to points of the SAME function type
*-----------------------------------------------------------*/
else if (P_marker_offd[i1] == strong_f_marker)
{
sum = zero;
/*---------------------------------------------------------
* Loop over row of A_ext for point i1 and calculate the sum
* of the connections to c-points that strongly influence i.
*---------------------------------------------------------*/
/* find row number */
c_num = A_offd_j[jj];
sgn = 1;
if (A_ext_data[A_ext_i[c_num]] < 0) sgn = -1;
for (jj1 = A_ext_i[c_num]; jj1 < A_ext_i[c_num+1]; jj1++)
{
i2 = (HYPRE_Int)A_ext_j[jj1];
if (num_functions == 1 || dof_func[i1] == dof_func[i2])
{
if (i2 > -1)
{
/* in the diagonal block */
if (P_marker[i2] >= jj_begin_row
&& (sgn*A_ext_data[jj1]) < 0)
{
sum += A_ext_data[jj1];
}
}
else
{
/* in the off_diagonal block */
if (P_marker_offd[-i2-1] >= jj_begin_row_offd
&& (sgn*A_ext_data[jj1]) < 0)
{
sum += A_ext_data[jj1];
}
}
}
}
if (sum != 0)
{
distribute = A_offd_data[jj] / sum;
/*---------------------------------------------------------
* Loop over row of A_ext for point i1 and do
* the distribution.
*--------------------------------------------------------*/
/* Diagonal block part of row i1 */
for (jj1 = A_ext_i[c_num]; jj1 < A_ext_i[c_num+1]; jj1++)
{
i2 = (HYPRE_Int)A_ext_j[jj1];
if (num_functions == 1 || dof_func[i1] == dof_func[i2])
{
if (i2 > -1) /* in the diagonal block */
{
if (P_marker[i2] >= jj_begin_row
&& (sgn*A_ext_data[jj1]) < 0)
{
P_diag_data[P_marker[i2]]
+= distribute * A_ext_data[jj1];
}
}
else
{
/* in the off_diagonal block */
if (P_marker_offd[-i2-1] >= jj_begin_row_offd
&& (sgn*A_ext_data[jj1]) < 0)
P_offd_data[P_marker_offd[-i2-1]]
+= distribute * A_ext_data[jj1];
}
}
}
}
else /* sum = 0 */
{
if (num_functions == 1 || dof_func[i] == dof_func_offd[i1])
diagonal += A_offd_data[jj];
}
}
/*-----------------------------------------------------------
* Case 3: neighbor i1 weakly influences i, accumulate a_{i,i1}
* into the diagonal.
*-----------------------------------------------------------*/
else if (CF_marker_offd[i1] != -3)
{
if (num_functions == 1 || dof_func[i] == dof_func_offd[i1])
diagonal += A_offd_data[jj];
}
}
}
/*-----------------------------------------------------------------
* Set interpolation weight by dividing by the diagonal.
*-----------------------------------------------------------------*/
if (diagonal == 0.0)
{
if (print_level)
hypre_printf(" Warning! zero diagonal! Proc id %d row %d\n", my_id,i);
for (jj = jj_begin_row; jj < jj_end_row; jj++)
{
P_diag_data[jj] = 0.0;
}
for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++)
{
P_offd_data[jj] = 0.0;
}
}
else
{
for (jj = jj_begin_row; jj < jj_end_row; jj++)
{
P_diag_data[jj] /= -diagonal;
}
for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++)
{
P_offd_data[jj] /= -diagonal;
}
}
}
strong_f_marker--;
P_offd_i[i+1] = jj_counter_offd;
}
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
hypre_TFree(P_marker_offd, HYPRE_MEMORY_HOST);
}
P = hypre_ParCSRMatrixCreate(comm,
hypre_ParCSRMatrixGlobalNumRows(A),
total_global_cpts,
hypre_ParCSRMatrixColStarts(A),
num_cpts_global,
0,
P_diag_i[n_fine],
P_offd_i[n_fine]);
P_diag = hypre_ParCSRMatrixDiag(P);
hypre_CSRMatrixData(P_diag) = P_diag_data;
hypre_CSRMatrixI(P_diag) = P_diag_i;
hypre_CSRMatrixJ(P_diag) = P_diag_j;
P_offd = hypre_ParCSRMatrixOffd(P);
hypre_CSRMatrixData(P_offd) = P_offd_data;
hypre_CSRMatrixI(P_offd) = P_offd_i;
hypre_CSRMatrixJ(P_offd) = P_offd_j;
hypre_ParCSRMatrixOwnsRowStarts(P) = 0;
/* Compress P, removing coefficients smaller than trunc_factor * Max */
if (trunc_factor != 0.0 || max_elmts > 0)
{
hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts);
P_diag_data = hypre_CSRMatrixData(P_diag);
P_diag_i = hypre_CSRMatrixI(P_diag);
P_diag_j = hypre_CSRMatrixJ(P_diag);
P_offd_data = hypre_CSRMatrixData(P_offd);
P_offd_i = hypre_CSRMatrixI(P_offd);
P_offd_j = hypre_CSRMatrixJ(P_offd);
P_diag_size = P_diag_i[n_fine];
P_offd_size = P_offd_i[n_fine];
}
num_cols_P_offd = 0;
if (P_offd_size)
{
P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i=0; i < num_cols_A_offd; i++)
P_marker[i] = 0;
num_cols_P_offd = 0;
for (i=0; i < P_offd_size; i++)
{
index = P_offd_j[i];
if (!P_marker[index])
{
num_cols_P_offd++;
P_marker[index] = 1;
}
}
col_map_offd_P = hypre_CTAlloc(HYPRE_BigInt, num_cols_P_offd, HYPRE_MEMORY_HOST);
tmp_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST);
index = 0;
for (i=0; i < num_cols_P_offd; i++)
{
while (P_marker[index]==0) index++;
tmp_map_offd[i] = index++;
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i=0; i < P_offd_size; i++)
P_offd_j[i] = hypre_BinarySearch(tmp_map_offd,
P_offd_j[i],
num_cols_P_offd);
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
}
for (i=0; i < n_fine; i++)
if (CF_marker[i] == -3) CF_marker[i] = -1;
if (num_cols_P_offd)
{
hypre_ParCSRMatrixColMapOffd(P) = col_map_offd_P;
hypre_CSRMatrixNumCols(P_offd) = num_cols_P_offd;
}
hypre_GetCommPkgRTFromCommPkgA(P, A, fine_to_coarse, tmp_map_offd);
*P_ptr = P;
hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST);
hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST);
hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST);
hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST);
hypre_TFree(tmp_map_offd, HYPRE_MEMORY_HOST);
hypre_TFree(coarse_counter, HYPRE_MEMORY_HOST);
hypre_TFree(jj_count, HYPRE_MEMORY_HOST);
hypre_TFree(jj_count_offd, HYPRE_MEMORY_HOST);
if (num_procs > 1) hypre_CSRMatrixDestroy(A_ext);
return hypre_error_flag;
}
/*---------------------------------------------------------------------------
* hypre_BoomerAMGTruncandBuild
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGTruncandBuild( hypre_ParCSRMatrix *P,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts)
{
hypre_CSRMatrix *P_offd = hypre_ParCSRMatrixOffd(P);
hypre_ParCSRCommPkg *commpkg_P = hypre_ParCSRMatrixCommPkg(P);
HYPRE_BigInt *col_map_offd = hypre_ParCSRMatrixColMapOffd(P);
HYPRE_Int *P_offd_i = hypre_CSRMatrixI(P_offd);
HYPRE_Int *P_offd_j = hypre_CSRMatrixJ(P_offd);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(P_offd);
HYPRE_Int n_fine = hypre_CSRMatrixNumRows(P_offd);
HYPRE_BigInt *new_col_map_offd;
HYPRE_Int *tmp_map_offd = NULL;
HYPRE_Int P_offd_size=0, new_num_cols_offd;
HYPRE_Int *P_marker;
HYPRE_Int i;
HYPRE_Int index;
/* Compress P, removing coefficients smaller than trunc_factor * Max */
if (trunc_factor != 0.0 || max_elmts > 0)
{
hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts);
P_offd_j = hypre_CSRMatrixJ(P_offd);
P_offd_i = hypre_CSRMatrixI(P_offd);
P_offd_size = P_offd_i[n_fine];
}
new_num_cols_offd = 0;
if (P_offd_size)
{
P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST);
/*#define HYPRE_SMP_PRIVATE i
#include "../utilities/hypre_smp_forloop.h"*/
for (i=0; i < num_cols_offd; i++)
P_marker[i] = 0;
for (i=0; i < P_offd_size; i++)
{
index = P_offd_j[i];
if (!P_marker[index])
{
new_num_cols_offd++;
P_marker[index] = 1;
}
}
tmp_map_offd = hypre_CTAlloc(HYPRE_Int, new_num_cols_offd, HYPRE_MEMORY_HOST);
new_col_map_offd = hypre_CTAlloc(HYPRE_BigInt, new_num_cols_offd, HYPRE_MEMORY_HOST);
index = 0;
for (i=0; i < new_num_cols_offd; i++)
{
while (P_marker[index]==0) index++;
tmp_map_offd[i] = index++;
}
/*#define HYPRE_SMP_PRIVATE i
#include "../utilities/hypre_smp_forloop.h"*/
for (i=0; i < P_offd_size; i++)
P_offd_j[i] = hypre_BinarySearch(tmp_map_offd,
P_offd_j[i],
new_num_cols_offd);
}
index = 0;
for (i = 0; i < new_num_cols_offd; i++)
{
while (P_marker[index] == 0) index++;
new_col_map_offd[i] = col_map_offd[index];
index++;
}
if (P_offd_size) hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
if (new_num_cols_offd)
{
hypre_TFree(tmp_map_offd, HYPRE_MEMORY_HOST);
hypre_TFree(col_map_offd, HYPRE_MEMORY_HOST);
hypre_ParCSRMatrixColMapOffd(P) = new_col_map_offd;
hypre_CSRMatrixNumCols(P_offd) = new_num_cols_offd;
}
if (commpkg_P != NULL) hypre_MatvecCommPkgDestroy(commpkg_P);
hypre_MatvecCommPkgCreate(P);
return hypre_error_flag;
}
hypre_ParCSRMatrix *hypre_CreateC( hypre_ParCSRMatrix *A,
HYPRE_Real w)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(A);
HYPRE_BigInt *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A);
HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd);
HYPRE_BigInt global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A);
hypre_ParCSRMatrix *C;
hypre_CSRMatrix *C_diag;
hypre_CSRMatrix *C_offd;
HYPRE_Real *C_diag_data;
HYPRE_Int *C_diag_i;
HYPRE_Int *C_diag_j;
HYPRE_Real *C_offd_data;
HYPRE_Int *C_offd_i;
HYPRE_Int *C_offd_j;
HYPRE_BigInt *col_map_offd_C;
HYPRE_Int i, j, index;
HYPRE_Real invdiag;
HYPRE_Real w_local = w;
C = hypre_ParCSRMatrixCreate(comm, global_num_rows, global_num_rows, row_starts,
row_starts, num_cols_offd, A_diag_i[num_rows], A_offd_i[num_rows]);
hypre_ParCSRMatrixInitialize(C);
C_diag = hypre_ParCSRMatrixDiag(C);
C_offd = hypre_ParCSRMatrixOffd(C);
C_diag_i = hypre_CSRMatrixI(C_diag);
C_diag_j = hypre_CSRMatrixJ(C_diag);
C_diag_data = hypre_CSRMatrixData(C_diag);
C_offd_i = hypre_CSRMatrixI(C_offd);
C_offd_j = hypre_CSRMatrixJ(C_offd);
C_offd_data = hypre_CSRMatrixData(C_offd);
col_map_offd_C = hypre_ParCSRMatrixColMapOffd(C);
hypre_ParCSRMatrixOwnsRowStarts(C) = 0;
hypre_ParCSRMatrixOwnsColStarts(C) = 0;
for (i=0; i < num_cols_offd; i++)
col_map_offd_C[i] = col_map_offd_A[i];
for (i=0; i < num_rows; i++)
{
index = A_diag_i[i];
invdiag = -w/A_diag_data[index];
C_diag_data[index] = 1.0-w;
C_diag_j[index] = A_diag_j[index];
if (w == 0)
{
w_local = fabs(A_diag_data[index]);
for (j = index+1; j < A_diag_i[i+1]; j++)
w_local += fabs(A_diag_data[j]);
for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++)
w_local += fabs(A_offd_data[j]);
invdiag = -1/w_local;
C_diag_data[index] = 1.0-A_diag_data[index]/w_local;
}
C_diag_i[i] = index;
C_offd_i[i] = A_offd_i[i];
for (j = index+1; j < A_diag_i[i+1]; j++)
{
C_diag_data[j] = A_diag_data[j]*invdiag;
C_diag_j[j] = A_diag_j[j];
}
for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++)
{
C_offd_data[j] = A_offd_data[j]*invdiag;
C_offd_j[j] = A_offd_j[j];
}
}
C_diag_i[num_rows] = A_diag_i[num_rows];
C_offd_i[num_rows] = A_offd_i[num_rows];
return C;
}
/* RL */
HYPRE_Int
hypre_BoomerAMGBuildInterpOnePnt( hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Int *col_offd_S_to_A,
hypre_ParCSRMatrix **P_ptr)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd);
//HYPRE_Int *col_map_offd_A = hypre_ParCSRMatrixColMapOffd(A);
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd);
/* Interpolation matrix P */
hypre_ParCSRMatrix *P;
/* csr's */
hypre_CSRMatrix *P_diag;
hypre_CSRMatrix *P_offd;
/* arrays */
HYPRE_Real *P_diag_data;
HYPRE_Int *P_diag_i;
HYPRE_Int *P_diag_j;
HYPRE_Real *P_offd_data;
HYPRE_Int *P_offd_i;
HYPRE_Int *P_offd_j;
HYPRE_Int num_cols_offd_P;
HYPRE_Int *tmp_map_offd = NULL;
HYPRE_BigInt *col_map_offd_P = NULL;
/* CF marker off-diag part */
HYPRE_Int *CF_marker_offd = NULL;
/* func type off-diag part */
HYPRE_Int *dof_func_offd = NULL;
/* nnz */
HYPRE_Int nnz_diag, nnz_offd, cnt_diag, cnt_offd;
HYPRE_Int *marker_diag, *marker_offd = NULL;
/* local size */
HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag);
/* number of C-pts */
HYPRE_Int n_cpts = 0;
/* fine to coarse mapping: diag part and offd part */
HYPRE_Int *fine_to_coarse;
HYPRE_BigInt *fine_to_coarse_offd = NULL;
HYPRE_BigInt total_global_cpts, my_first_cpt;
HYPRE_Int my_id, num_procs;
HYPRE_Int num_sends;
HYPRE_Int *int_buf_data = NULL;
HYPRE_BigInt *big_int_buf_data = NULL;
//HYPRE_Int col_start = hypre_ParCSRMatrixFirstRowIndex(A);
//HYPRE_Int col_end = col_start + n_fine;
HYPRE_Int i, j, i1, j1, k1, index, start;
HYPRE_Int *max_abs_cij;
char *max_abs_diag_offd;
HYPRE_Real max_abs_aij, vv;
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm,&my_id);
my_first_cpt = num_cpts_global[0];
if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1];
hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm);
/*-------------------------------------------------------------------
* Get the CF_marker data for the off-processor columns
*-------------------------------------------------------------------*/
/* CF marker for the off-diag columns */
if (num_cols_A_offd)
{
CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd,HYPRE_MEMORY_HOST);
}
/* function type indicator for the off-diag columns */
if (num_functions > 1 && num_cols_A_offd)
{
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd,HYPRE_MEMORY_HOST);
}
/* if CommPkg of A is not present, create it */
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(A);
comm_pkg = hypre_ParCSRMatrixCommPkg(A);
}
/* number of sends to do (number of procs) */
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
/* send buffer, of size send_map_starts[num_sends]),
* i.e., number of entries to send */
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends),HYPRE_MEMORY_HOST);
/* copy CF markers of elements to send to buffer
* RL: why copy them with two for loops? Why not just loop through all in one */
index = 0;
for (i = 0; i < num_sends; i++)
{
/* start pos of elements sent to send_proc[i] */
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
/* loop through all elems to send_proc[i] */
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
{
/* CF marker of send_map_elemts[j] */
int_buf_data[index++] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
}
/* create a handle to start communication. 11: for integer */
comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data, CF_marker_offd);
/* destroy the handle to finish communication */
hypre_ParCSRCommHandleDestroy(comm_handle);
/* do a similar communication for dof_func */
if (num_functions > 1)
{
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
{
int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
}
comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data, dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
}
hypre_TFree(int_buf_data,HYPRE_MEMORY_HOST);
/*-----------------------------------------------------------------------
* First Pass: Determine size of P and fill in fine_to_coarse mapping,
* and find the most strongly influencing C-pt for each F-pt
*-----------------------------------------------------------------------*/
/* nnz in diag and offd parts */
cnt_diag = 0;
cnt_offd = 0;
max_abs_cij = hypre_CTAlloc(HYPRE_Int, n_fine,HYPRE_MEMORY_HOST);
max_abs_diag_offd = hypre_CTAlloc(char, n_fine,HYPRE_MEMORY_HOST);
fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine,HYPRE_MEMORY_HOST);
/* markers initialized as zeros */
marker_diag = hypre_CTAlloc(HYPRE_Int, n_fine,HYPRE_MEMORY_HOST);
marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd,HYPRE_MEMORY_HOST);
for (i = 0; i < n_fine; i++)
{
/*--------------------------------------------------------------------
* If i is a C-point, interpolation is the identity. Also set up
* mapping vector.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
//fine_to_coarse[i] = my_first_cpt + n_cpts;
fine_to_coarse[i] = n_cpts;
n_cpts++;
continue;
}
/* mark all the strong connections: in S */
HYPRE_Int MARK = i + 1;
/* loop through row i of S, diag part */
for (j = S_diag_i[i]; j < S_diag_i[i+1]; j++)
{
marker_diag[S_diag_j[j]] = MARK;
}
/* loop through row i of S, offd part */
if (num_procs > 1)
{
for (j = S_offd_i[i]; j < S_offd_i[i+1]; j++)
{
j1 = col_offd_S_to_A ? col_offd_S_to_A[S_offd_j[j]] : S_offd_j[j];
marker_offd[j1] = MARK;
}
}
fine_to_coarse[i] = -1;
/*---------------------------------------------------------------------------
* If i is an F-pt, interpolation is from the most strongly influencing C-pt
* Find this C-pt and save it
*--------------------------------------------------------------------------*/
/* if we failed to find any strong C-pt, mark this point as an 'n' */
char marker = 'n';
/* max abs val */
max_abs_aij = -1.0;
/* loop through row i of A, diag part */
for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++)
{
i1 = A_diag_j[j];
vv = fabs(A_diag_data[j]);
#if 0
/* !!! this is a hack just for code verification purpose !!!
it basically says:
1. if we see |a_ij| < 1e-14, force it to be 1e-14
2. if we see |a_ij| == the max(|a_ij|) so far exactly,
replace it if the j idx is smaller
Reasons:
1. numerical round-off for eps-level values
2. entries in CSR rows may be listed in different orders
*/
vv = vv < 1e-14 ? 1e-14 : vv;
if (CF_marker[i1] >= 0 && marker_diag[i1] == MARK &&
vv == max_abs_aij && i1 < max_abs_cij[i])
{
/* mark it as a 'd' */
marker = 'd';
max_abs_cij[i] = i1;
max_abs_aij = vv;
continue;
}
#endif
/* it is a strong C-pt and has abs val larger than what have seen */
if (CF_marker[i1] >= 0 && marker_diag[i1] == MARK && vv > max_abs_aij)
{
/* mark it as a 'd' */
marker = 'd';
max_abs_cij[i] = i1;
max_abs_aij = vv;
}
}
/* offd part */
if (num_procs > 1)
{
for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++)
{
i1 = A_offd_j[j];
vv = fabs(A_offd_data[j]);
if (CF_marker_offd[i1] >= 0 && marker_offd[i1] == MARK && vv > max_abs_aij)
{
/* mark it as an 'o' */
marker = 'o';
max_abs_cij[i] = i1;
max_abs_aij = vv;
}
}
}
max_abs_diag_offd[i] = marker;
if (marker == 'd')
{
cnt_diag ++;
}
else if (marker == 'o')
{
cnt_offd ++;
}
}
nnz_diag = cnt_diag + n_cpts;
nnz_offd = cnt_offd;
/*------------- allocate arrays */
P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1,HYPRE_MEMORY_HOST);
P_diag_j = hypre_CTAlloc(HYPRE_Int, nnz_diag,HYPRE_MEMORY_HOST);
P_diag_data = hypre_CTAlloc(HYPRE_Real, nnz_diag,HYPRE_MEMORY_HOST);
/* not in ``if num_procs > 1'',
* allocation needed even for empty CSR */
P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1,HYPRE_MEMORY_HOST);
P_offd_j = hypre_CTAlloc(HYPRE_Int, nnz_offd,HYPRE_MEMORY_HOST);
P_offd_data = hypre_CTAlloc(HYPRE_Real, nnz_offd,HYPRE_MEMORY_HOST);
/* redundant */
P_diag_i[0] = 0;
P_offd_i[0] = 0;
/* reset counters */
cnt_diag = 0;
cnt_offd = 0;
/*-----------------------------------------------------------------------
* Send and receive fine_to_coarse info.
*-----------------------------------------------------------------------*/
fine_to_coarse_offd = hypre_CTAlloc(HYPRE_BigInt, num_cols_A_offd,HYPRE_MEMORY_HOST);
big_int_buf_data = hypre_CTAlloc(HYPRE_BigInt, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends),HYPRE_MEMORY_HOST);
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
{
big_int_buf_data[index++] = my_first_cpt
+(HYPRE_BigInt)fine_to_coarse[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
}
comm_handle = hypre_ParCSRCommHandleCreate(21, comm_pkg, big_int_buf_data, fine_to_coarse_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
/*-----------------------------------------------------------------------
* Second Pass: Populate P
*-----------------------------------------------------------------------*/
for (i = 0; i < n_fine; i++)
{
if (CF_marker[i] >= 0)
{
/*--------------------------------------------------------------------
* If i is a C-point, interpolation is the identity.
*--------------------------------------------------------------------*/
//P_diag_j[cnt_diag] = fine_to_coarse[i] - my_first_cpt;
P_diag_j[cnt_diag] = fine_to_coarse[i];
P_diag_data[cnt_diag++] = 1.0;
}
else
{
/*---------------------------------------------------------------------------
* If i is an F-pt, interpolation is from the most strongly influencing C-pt
*--------------------------------------------------------------------------*/
if (max_abs_diag_offd[i] == 'd')
{
/* on diag part of P */
j = max_abs_cij[i];
//P_diag_j[cnt_diag] = fine_to_coarse[j] - my_first_cpt;
P_diag_j[cnt_diag] = fine_to_coarse[j];
P_diag_data[cnt_diag++] = 1.0;
}
else if (max_abs_diag_offd[i] == 'o')
{
/* on offd part of P */
j = max_abs_cij[i];
P_offd_j[cnt_offd] = j;
P_offd_data[cnt_offd++] = 1.0;
}
}
P_diag_i[i+1] = cnt_diag;
P_offd_i[i+1] = cnt_offd;
}
hypre_assert(cnt_diag == nnz_diag);
hypre_assert(cnt_offd == nnz_offd);
/* num of cols in the offd part of P */
num_cols_offd_P = 0;
/* marker_offd: all -1 */
for (i = 0; i < num_cols_A_offd; i++)
{
marker_offd[i] = -1;
}
for (i = 0; i < nnz_offd; i++)
{
i1 = P_offd_j[i];
if (marker_offd[i1] == -1)
{
num_cols_offd_P++;
marker_offd[i1] = 1;
}
}
/* col_map_offd_P: the col indices of the offd of P
* we first keep them be the offd-idx of A */
col_map_offd_P = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_P,HYPRE_MEMORY_HOST);
tmp_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd_P,HYPRE_MEMORY_HOST);
for (i = 0, i1 = 0; i < num_cols_A_offd; i++)
{
if (marker_offd[i] == 1)
{
tmp_map_offd[i1++] = i;
}
}
hypre_assert(i1 == num_cols_offd_P);
/* now, adjust P_offd_j to local idx w.r.t col_map_offd_R
* by searching */
for (i = 0; i < nnz_offd; i++)
{
i1 = P_offd_j[i];
k1 = hypre_BinarySearch(tmp_map_offd, i1, num_cols_offd_P);
/* search must succeed */
hypre_assert(k1 >= 0 && k1 < num_cols_offd_P);
P_offd_j[i] = k1;
}
/* change col_map_offd_P to global coarse ids */
for (i = 0; i < num_cols_offd_P; i++)
{
col_map_offd_P[i] = fine_to_coarse_offd[tmp_map_offd[i]];
}
/* Now, we should have everything of Parcsr matrix P */
P = hypre_ParCSRMatrixCreate(comm,
hypre_ParCSRMatrixGlobalNumCols(A), /* global num of rows */
total_global_cpts, /* global num of cols */
hypre_ParCSRMatrixColStarts(A), /* row_starts */
num_cpts_global, /* col_starts */
num_cols_offd_P, /* num cols offd */
nnz_diag,
nnz_offd);
P_diag = hypre_ParCSRMatrixDiag(P);
hypre_CSRMatrixData(P_diag) = P_diag_data;
hypre_CSRMatrixI(P_diag) = P_diag_i;
hypre_CSRMatrixJ(P_diag) = P_diag_j;
P_offd = hypre_ParCSRMatrixOffd(P);
hypre_CSRMatrixData(P_offd) = P_offd_data;
hypre_CSRMatrixI(P_offd) = P_offd_i;
hypre_CSRMatrixJ(P_offd) = P_offd_j;
/* P does not own ColStarts, since A does */
hypre_ParCSRMatrixOwnsRowStarts(P) = 0;
hypre_ParCSRMatrixColMapOffd(P) = col_map_offd_P;
/* create CommPkg of P */
hypre_MatvecCommPkgCreate(P);
*P_ptr = P;
/* free workspace */
hypre_TFree(CF_marker_offd,HYPRE_MEMORY_HOST);
hypre_TFree(dof_func_offd,HYPRE_MEMORY_HOST);
hypre_TFree(tmp_map_offd,HYPRE_MEMORY_HOST);
hypre_TFree(big_int_buf_data,HYPRE_MEMORY_HOST);
hypre_TFree(fine_to_coarse,HYPRE_MEMORY_HOST);
hypre_TFree(fine_to_coarse_offd,HYPRE_MEMORY_HOST);
hypre_TFree(marker_diag,HYPRE_MEMORY_HOST);
hypre_TFree(marker_offd,HYPRE_MEMORY_HOST);
hypre_TFree(max_abs_cij,HYPRE_MEMORY_HOST);
hypre_TFree(max_abs_diag_offd,HYPRE_MEMORY_HOST);
return hypre_error_flag;
}
|
omp_parallel_reduction.c | // RUN: %libomp-compile-and-run
#include <stdio.h>
#include <math.h>
#include "omp_testsuite.h"
#define DOUBLE_DIGITS 20 /* dt^DOUBLE_DIGITS */
#define MAX_FACTOR 10
#define KNOWN_PRODUCT 3628800 /* 10! */
int test_omp_parallel_reduction()
{
int sum;
int known_sum;
double dsum;
double dknown_sum;
double dt=0.5; /* base of geometric row for + and - test*/
double rounding_error= 1.E-9;
int diff;
double ddiff;
int product;
int known_product;
int logic_and;
int logic_or;
int bit_and;
int bit_or;
int exclusiv_bit_or;
int logics[LOOPCOUNT];
int i;
double dpt;
int result;
sum =0;
dsum=0;
product=1;
logic_and=1;
logic_or=0;
bit_and=1;
bit_or=0;
exclusiv_bit_or=0;
result=0;
dt = 1./3.;
known_sum = (LOOPCOUNT*(LOOPCOUNT+1))/2;
/* Tests for integers */
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(+:sum)
for (i=1;i<=LOOPCOUNT;i++) {
sum=sum+i;
}
if(known_sum!=sum) {
result++;
fprintf(stderr,"Error in sum with integers: Result was %d instead of %d\n",sum,known_sum);
}
diff = (LOOPCOUNT*(LOOPCOUNT+1))/2;
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(-:diff)
for (i=1;i<=LOOPCOUNT;++i) {
diff=diff-i;
}
if(diff != 0) {
result++;
fprintf(stderr,"Error in difference with integers: Result was %d instead of 0.\n",diff);
}
/* Tests for doubles */
dsum=0;
dpt=1;
for (i=0;i<DOUBLE_DIGITS;++i) {
dpt*=dt;
}
dknown_sum = (1-dpt)/(1-dt);
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(+:dsum)
for (i=0;i<DOUBLE_DIGITS;++i) {
dsum += pow(dt,i);
}
if( fabs(dsum-dknown_sum) > rounding_error ) {
result++;
fprintf(stderr,"Error in sum with doubles: Result was %f instead of %f (Difference: %E)\n",dsum,dknown_sum, dsum-dknown_sum);
}
dpt=1;
for (i=0;i<DOUBLE_DIGITS;++i) {
dpt*=dt;
}
fprintf(stderr,"\n");
ddiff = (1-dpt)/(1-dt);
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(-:ddiff)
for (i=0;i<DOUBLE_DIGITS;++i) {
ddiff -= pow(dt,i);
}
if( fabs(ddiff) > rounding_error) {
result++;
fprintf(stderr,"Error in Difference with doubles: Result was %E instead of 0.0\n",ddiff);
}
/* Tests for product of integers */
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(*:product)
for(i=1;i<=MAX_FACTOR;i++) {
product *= i;
}
known_product = KNOWN_PRODUCT;
if(known_product != product) {
result++;
fprintf(stderr,"Error in Product with integers: Result was %d instead of %d\n\n",product,known_product);
}
/* Tests for logical and */
for(i=0;i<LOOPCOUNT;i++) {
logics[i]=1;
}
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(&&:logic_and)
for(i=0;i<LOOPCOUNT;++i) {
logic_and = (logic_and && logics[i]);
}
if(!logic_and) {
result++;
fprintf(stderr,"Error in logic AND part 1.\n");
}
logic_and = 1;
logics[LOOPCOUNT/2]=0;
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(&&:logic_and)
for(i=0;i<LOOPCOUNT;++i) {
logic_and = logic_and && logics[i];
}
if(logic_and) {
result++;
fprintf(stderr,"Error in logic AND part 2.\n");
}
/* Tests for logical or */
for(i=0;i<LOOPCOUNT;i++) {
logics[i]=0;
}
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(||:logic_or)
for(i=0;i<LOOPCOUNT;++i) {
logic_or = logic_or || logics[i];
}
if(logic_or) {
result++;
fprintf(stderr,"Error in logic OR part 1.\n");
}
logic_or = 0;
logics[LOOPCOUNT/2]=1;
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(||:logic_or)
for(i=0;i<LOOPCOUNT;++i) {
logic_or = logic_or || logics[i];
}
if(!logic_or) {
result++;
fprintf(stderr,"Error in logic OR part 2.\n");
}
/* Tests for bitwise and */
for(i=0;i<LOOPCOUNT;++i) {
logics[i]=1;
}
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(&:bit_and)
for(i=0;i<LOOPCOUNT;++i) {
bit_and = (bit_and & logics[i]);
}
if(!bit_and) {
result++;
fprintf(stderr,"Error in BIT AND part 1.\n");
}
bit_and = 1;
logics[LOOPCOUNT/2]=0;
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(&:bit_and)
for(i=0;i<LOOPCOUNT;++i) {
bit_and = bit_and & logics[i];
}
if(bit_and) {
result++;
fprintf(stderr,"Error in BIT AND part 2.\n");
}
for(i=0;i<LOOPCOUNT;i++) {
logics[i]=0;
}
/* Tests for bitwise or */
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(|:bit_or)
for(i=0;i<LOOPCOUNT;++i) {
bit_or = bit_or | logics[i];
}
if(bit_or) {
result++;
fprintf(stderr,"Error in BIT OR part 1\n");
}
bit_or = 0;
logics[LOOPCOUNT/2]=1;
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(|:bit_or)
for(i=0;i<LOOPCOUNT;++i) {
bit_or = bit_or | logics[i];
}
if(!bit_or) {
result++;
fprintf(stderr,"Error in BIT OR part 2\n");
}
for(i=0;i<LOOPCOUNT;i++) {
logics[i]=0;
}
/* Tests for bitwise xor */
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(^:exclusiv_bit_or)
for(i=0;i<LOOPCOUNT;++i) {
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
if(exclusiv_bit_or) {
result++;
fprintf(stderr,"Error in EXCLUSIV BIT OR part 1\n");
}
exclusiv_bit_or = 0;
logics[LOOPCOUNT/2]=1;
#pragma omp parallel for schedule(dynamic,1) private(i) reduction(^:exclusiv_bit_or)
for(i=0;i<LOOPCOUNT;++i) {
exclusiv_bit_or = exclusiv_bit_or ^ logics[i];
}
if(!exclusiv_bit_or) {
result++;
fprintf(stderr,"Error in EXCLUSIV BIT OR part 2\n");
}
/*printf("\nResult:%d\n",result);*/
return (result==0);
}
int main()
{
int i;
int num_failed=0;
for(i = 0; i < REPETITIONS; i++) {
if(!test_omp_parallel_reduction()) {
num_failed++;
}
}
return num_failed;
}
|
GB_unaryop__minv_int32_fp64.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__minv_int32_fp64
// op(A') function: GB_tran__minv_int32_fp64
// C type: int32_t
// A type: double
// cast: int32_t cij ; GB_CAST_SIGNED(cij,aij,32)
// unaryop: cij = GB_IMINV_SIGNED (aij, 32)
#define GB_ATYPE \
double
#define GB_CTYPE \
int32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IMINV_SIGNED (x, 32) ;
// casting
#define GB_CASTING(z, x) \
int32_t z ; GB_CAST_SIGNED(z,x,32) ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_INT32 || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_int32_fp64
(
int32_t *restrict Cx,
const double *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__minv_int32_fp64
(
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
|
3d25pt_var.c | /*
* Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*13);
for(m=0; m<13;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 4;
tile_size[1] = 4;
tile_size[2] = 32;
tile_size[3] = 256;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<13; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt; t++) {
for (i = 4; i < Nz-4; i++) {
for (j = 4; j < Ny-4; j++) {
for (k = 4; k < Nx-4; k++) {
A[(t+1)%2][i][j][k] =
coef[0][i][j][k] * A[(t)%2][i ][j ][k ] +
coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) +
coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) +
coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) +
coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) +
coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) +
coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) +
coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) +
coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) +
coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) +
coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) +
coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) +
coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ;
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "variable axis-symmetric")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<13;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
GB_binop__minus_fc32.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__minus_fc32)
// A.*B function (eWiseMult): GB (_AemultB_08__minus_fc32)
// A.*B function (eWiseMult): GB (_AemultB_02__minus_fc32)
// A.*B function (eWiseMult): GB (_AemultB_04__minus_fc32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__minus_fc32)
// A*D function (colscale): GB (_AxD__minus_fc32)
// D*A function (rowscale): GB (_DxB__minus_fc32)
// C+=B function (dense accum): GB (_Cdense_accumB__minus_fc32)
// C+=b function (dense accum): GB (_Cdense_accumb__minus_fc32)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__minus_fc32)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__minus_fc32)
// C=scalar+B GB (_bind1st__minus_fc32)
// C=scalar+B' GB (_bind1st_tran__minus_fc32)
// C=A+scalar GB (_bind2nd__minus_fc32)
// C=A'+scalar GB (_bind2nd_tran__minus_fc32)
// C type: GxB_FC32_t
// A type: GxB_FC32_t
// A pattern? 0
// B type: GxB_FC32_t
// B pattern? 0
// BinaryOp: cij = GB_FC32_minus (aij, bij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_BTYPE \
GxB_FC32_t
#define GB_CTYPE \
GxB_FC32_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
GxB_FC32_t aij = GBX (Ax, pA, A_iso)
// 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) \
GxB_FC32_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) \
GxB_FC32_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = GB_FC32_minus (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_MINUS || GxB_NO_FC32 || GxB_NO_MINUS_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__minus_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
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__minus_fc32)
(
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__minus_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__minus_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__minus_fc32)
(
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
GxB_FC32_t *restrict Cx = (GxB_FC32_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__minus_fc32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t *restrict Cx = (GxB_FC32_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__minus_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 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) ;
GxB_FC32_t alpha_scalar ;
GxB_FC32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((GxB_FC32_t *) alpha_scalar_in)) ;
beta_scalar = (*((GxB_FC32_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__minus_fc32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__minus_fc32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__minus_fc32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__minus_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__minus_fc32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ;
GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ;
GxB_FC32_t *Bx = (GxB_FC32_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
GxB_FC32_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_FC32_minus (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_fc32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ;
GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ;
GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
GxB_FC32_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_FC32_minus (aij, y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
GxB_FC32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_FC32_minus (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__minus_fc32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
GxB_FC32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
GxB_FC32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
GxB_FC32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_FC32_minus (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__minus_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
|
compute_treatment_uncertainties.c | /*
This file is part of the MCsquare software
Copyright © 2016-2017 Université catholique de Louvain (UCL)
All rights reserved.
The MCsquare software has been developed by Kevin Souris from UCL in the context of a collaboration with IBA s.a.
Each use of this software must be attributed to Université catholique de Louvain (UCL, Louvain-la-Neuve). Any other additional authorizations may be asked to LTTO@uclouvain.be.
The MCsquare software is released under the terms of the open-source Apache 2.0 license. Anyone can use or modify the code provided that the Apache 2.0 license conditions are met. See the Apache 2.0 license for more details https://www.apache.org/licenses/LICENSE-2.0
The MCsquare software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "include/compute_treatment_uncertainties.h"
void Translation_uncertainty(Hadron_buffer *hadron, DATA_config *config, VSLStreamStatePtr RNG_Stream){
int i;
/*
if(config->Current_Random_setup[0] != 0.0) hadron->x = hadron->x - single_rand_normal(RNG_Stream, 0, config->Current_Random_setup[0]) - config->Current_Systematic_setup[0];
else hadron->x = hadron->x - config->Current_Systematic_setup[0];
if(config->Current_Random_setup[1] != 0.0) hadron->y = hadron->y - single_rand_normal(RNG_Stream, 0, config->Current_Random_setup[1]) - config->Current_Systematic_setup[1];
else hadron->y = hadron->y - config->Current_Systematic_setup[1];
if(config->Current_Random_setup[2] != 0.0) hadron->z = hadron->z - single_rand_normal(RNG_Stream, 0, config->Current_Random_setup[2]) - config->Current_Systematic_setup[2];
else hadron->z = hadron->z - config->Current_Systematic_setup[2];
*/
hadron->x = hadron->x - config->Current_Systematic_setup[0] - config->Current_Random_setup[0];
hadron->y = hadron->y - config->Current_Systematic_setup[1] - config->Current_Random_setup[1];
hadron->z = hadron->z - config->Current_Systematic_setup[2] - config->Current_Random_setup[2];
// Sampling of sigma before the Gaussian sampling (test for Ana)
//VAR_COMPUTE rnd = single_rand_uniform(RNG_Stream);
//hadron->x = hadron->x - single_rand_normal(RNG_Stream, 0, config->Current_Random_error[0]*rnd) - config->Current_Systematic_error[0];
//hadron->y = hadron->y - single_rand_normal(RNG_Stream, 0, config->Current_Random_error[1]*rnd) - config->Current_Systematic_error[1];
//hadron->z = hadron->z - single_rand_normal(RNG_Stream, 0, config->Current_Random_error[2]*rnd) - config->Current_Systematic_error[2];
}
void Density_scaling(VAR_DATA *Nominal_density, VAR_DATA *Scaled_density, int Num_voxels, VAR_DATA scaling_factor){
int i;
for(i=0; i<Num_voxels; i++){
Scaled_density[i] = scaling_factor * Nominal_density[i];
}
}
void Breathing_amplitude_variation(DATA_config *config, DATA_CT *ct, DATA_CT **CT_phases, DATA_4D_Fields *Fields){
int phaseID, i;
VAR_DATA *tmp = NULL;
double time_init = omp_get_wtime();
printf("Generating new 4DCT with %f %% motion amplitude ", 100*config->Current_Breathing_amplitude);
for(phaseID=0; phaseID < config->Num_4DCT_phases; phaseID++){
tmp = Field_multiplication(config->Current_Breathing_amplitude, Fields->Ref2Phase_log[phaseID], Fields->GridSize);
if(Fields->Phase2Ref[phaseID] != NULL) free(Fields->Phase2Ref[phaseID]);
Fields->Phase2Ref[phaseID] = Field_exponentiation(tmp, Fields->GridSize, Fields->Spacing, Fields->Origin, 1);
if(Fields->Ref2Phase[phaseID] != NULL) free(Fields->Ref2Phase[phaseID]);
Fields->Ref2Phase[phaseID] = Field_exponentiation(tmp, Fields->GridSize, Fields->Spacing, Fields->Origin, 0);
free(tmp);
if(CT_phases[phaseID]->density == CT_phases[phaseID]->Scaled_density){
if(CT_phases[phaseID]->density != NULL) free(CT_phases[phaseID]->density);
CT_phases[phaseID]->density = Image_deformation(ct->density, ct->GridSize, ct->VoxelLength, ct->Origin, Fields->Ref2Phase[phaseID], Fields->GridSize, Fields->Spacing, Fields->Origin);
CT_phases[phaseID]->Scaled_density = CT_phases[phaseID]->density;
}
else{
if(CT_phases[phaseID]->density != NULL) free(CT_phases[phaseID]->density);
CT_phases[phaseID]->density = Image_deformation(ct->density, ct->GridSize, ct->VoxelLength, ct->Origin, Fields->Ref2Phase[phaseID], Fields->GridSize, Fields->Spacing, Fields->Origin);
CT_phases[phaseID]->Nominal_density = CT_phases[phaseID]->density;
}
#pragma omp parallel for private(i)
for(i=0; i<CT_phases[phaseID]->Nbr_voxels; i++){
CT_phases[phaseID]->material[i] = (unsigned short int)Density_to_Material_convertion(CT_phases[phaseID]->density[i], CT_phases[phaseID]);
}
}
printf("(%f s) \n", omp_get_wtime() - time_init);
}
plan_parameters* Spot_Sorting(DATA_config *config, int phase, plan_parameters *Plan){
double time_init = omp_get_wtime();
printf("Generating partial plan for phase %d ", phase+1);
VAR_DATA SpotPhase, cumulative_weight=0;
VAR_DATA PhaseDuration = config->Current_Breathing_period * 1000 / config->Num_4DCT_phases;
VAR_DATA InitTime;
plan_parameters *partial_plan = (plan_parameters*)malloc(sizeof(plan_parameters));
strcpy(partial_plan->PlanName, "Partial plan");
partial_plan->NumberOfFractions = Plan->NumberOfFractions;
partial_plan->FractionID = Plan->FractionID;
partial_plan->NumberOfFields = Plan->NumberOfFields;
partial_plan->TotalMetersetWeightOfAllFields = 0.0;
partial_plan->fields = (field_parameters*)malloc(Plan->NumberOfFields * sizeof(field_parameters));
partial_plan->Fields_cumulative_PDF = (VAR_DATA*)malloc(Plan->NumberOfFields * sizeof(VAR_DATA));
partial_plan->FieldsID = (int*)malloc(Plan->NumberOfFields * sizeof(int));
int i,j,k;
for(i=0; i<Plan->NumberOfFields; i++){
if(config->Export_Beam_dose == 1) InitTime = config->Current_init_delivery_points[config->Current_Beam] * config->Current_Breathing_period * 1000;
else InitTime = config->Current_init_delivery_points[i] * config->Current_Breathing_period * 1000;
partial_plan->FieldsID[i] = Plan->FieldsID[i];
partial_plan->fields[i].FieldID = Plan->fields[i].FieldID;
partial_plan->fields[i].FinalCumulativeMeterSetWeight = 0.0;
partial_plan->fields[i].GantryAngle = Plan->fields[i].GantryAngle;
partial_plan->fields[i].PatientSupportAngle = Plan->fields[i].PatientSupportAngle;
partial_plan->fields[i].IsocenterPositionX = Plan->fields[i].IsocenterPositionX;
partial_plan->fields[i].IsocenterPositionY = Plan->fields[i].IsocenterPositionY;
partial_plan->fields[i].IsocenterPositionZ = Plan->fields[i].IsocenterPositionZ;
partial_plan->fields[i].NumberOfControlPoints = Plan->fields[i].NumberOfControlPoints;
partial_plan->fields[i].RS_Type = Plan->fields[i].RS_Type;
partial_plan->fields[i].ControlPoints = (ControlPoint_parameters*)malloc(Plan->fields[i].NumberOfControlPoints * sizeof(ControlPoint_parameters));
partial_plan->fields[i].ControlPoints_cumulative_PDF = (VAR_DATA*)malloc(Plan->fields[i].NumberOfControlPoints * sizeof(VAR_DATA));
for(j=0; j<Plan->fields[i].NumberOfControlPoints; j++){
partial_plan->fields[i].ControlPoints[j].ControlPointIndex = Plan->fields[i].ControlPoints[j].ControlPointIndex;
partial_plan->fields[i].ControlPoints[j].SpotTunnedID = Plan->fields[i].ControlPoints[j].SpotTunnedID;
partial_plan->fields[i].ControlPoints[j].CumulativeMetersetWeight = 0.0;
partial_plan->fields[i].ControlPoints[j].Energy = Plan->fields[i].ControlPoints[j].Energy;
partial_plan->fields[i].ControlPoints[j].NbOfScannedSpots = Plan->fields[i].ControlPoints[j].NbOfScannedSpots;
partial_plan->fields[i].ControlPoints[j].RS_setting = Plan->fields[i].ControlPoints[j].RS_setting;
partial_plan->fields[i].ControlPoints[j].RS_IsocenterDist = Plan->fields[i].ControlPoints[j].RS_IsocenterDist;
partial_plan->fields[i].ControlPoints[j].RS_WET = Plan->fields[i].ControlPoints[j].RS_WET;
partial_plan->fields[i].ControlPoints[j].RS_Thickness = Plan->fields[i].ControlPoints[j].RS_Thickness;
partial_plan->fields[i].ControlPoints[j].spots = (spot_parameters*)malloc(Plan->fields[i].ControlPoints[j].NbOfScannedSpots * sizeof(spot_parameters));
partial_plan->fields[i].ControlPoints[j].Spots_cumulative_PDF = (VAR_DATA*)malloc(Plan->fields[i].ControlPoints[j].NbOfScannedSpots * sizeof(VAR_DATA));
for(k=0; k<Plan->fields[i].ControlPoints[j].NbOfScannedSpots; k++){
partial_plan->fields[i].ControlPoints[j].spots[k].Spot_X = Plan->fields[i].ControlPoints[j].spots[k].Spot_X;
partial_plan->fields[i].ControlPoints[j].spots[k].Spot_Y = Plan->fields[i].ControlPoints[j].spots[k].Spot_Y;
partial_plan->fields[i].ControlPoints[j].spots[k].Spot_Time = Plan->fields[i].ControlPoints[j].spots[k].Spot_Time;
SpotPhase = fmod(floor((Plan->fields[i].ControlPoints[j].spots[k].Spot_Time + InitTime) / PhaseDuration), config->Num_4DCT_phases);
if(SpotPhase == phase) partial_plan->fields[i].ControlPoints[j].spots[k].Spot_Weight = Plan->fields[i].ControlPoints[j].spots[k].Spot_Weight;
else partial_plan->fields[i].ControlPoints[j].spots[k].Spot_Weight = 0.0;
cumulative_weight += partial_plan->fields[i].ControlPoints[j].spots[k].Spot_Weight;
partial_plan->fields[i].ControlPoints[j].Spots_cumulative_PDF[k] = cumulative_weight;
}
partial_plan->fields[i].ControlPoints_cumulative_PDF[j] = cumulative_weight;
partial_plan->fields[i].ControlPoints[j].CumulativeMetersetWeight = cumulative_weight;
}
partial_plan->Fields_cumulative_PDF[i] = cumulative_weight;
partial_plan->fields[i].FinalCumulativeMeterSetWeight = cumulative_weight;
}
partial_plan->TotalMetersetWeightOfAllFields = cumulative_weight;
partial_plan->cumulative_weight = cumulative_weight;
partial_plan->normalization_factor = Plan->normalization_factor * partial_plan->Fields_cumulative_PDF[Plan->NumberOfFields-1] / Plan->Fields_cumulative_PDF[Plan->NumberOfFields-1];
if(config->Dose_4D_Accumulation == 1) partial_plan->normalization_factor *= config->Num_4DCT_phases;
printf("(%f s) \n", omp_get_wtime() - time_init);
return partial_plan;
}
|
utils.h | #ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <assert.h>
#include "pixman-private.h" /* For 'inline' definition */
#include "utils-prng.h"
#if defined(_MSC_VER)
#define snprintf _snprintf
#define strcasecmp _stricmp
#endif
#define ARRAY_LENGTH(A) ((int) (sizeof (A) / sizeof ((A) [0])))
/* A primitive pseudorandom number generator,
* taken from POSIX.1-2001 example
*/
extern prng_t prng_state_data;
extern prng_t *prng_state;
#ifdef USE_OPENMP
#pragma omp threadprivate(prng_state_data)
#pragma omp threadprivate(prng_state)
#endif
static inline uint32_t
prng_rand (void)
{
return prng_rand_r (prng_state);
}
static inline void
prng_srand (uint32_t seed)
{
if (!prng_state)
{
/* Without setting a seed, PRNG does not work properly (is just
* returning zeros). So we only initialize the pointer here to
* make sure that 'prng_srand' is always called before any
* other 'prng_*' function. The wrongdoers violating this order
* will get a segfault. */
prng_state = &prng_state_data;
}
prng_srand_r (prng_state, seed);
}
static inline uint32_t
prng_rand_n (int max)
{
return prng_rand () % max;
}
static inline void
prng_randmemset (void *buffer, size_t size, prng_randmemset_flags_t flags)
{
prng_randmemset_r (prng_state, buffer, size, flags);
}
/* CRC 32 computation
*/
uint32_t
compute_crc32 (uint32_t in_crc32,
const void *buf,
size_t buf_len);
uint32_t
compute_crc32_for_image (uint32_t in_crc32,
pixman_image_t *image);
/* Print the image in hexadecimal */
void
print_image (pixman_image_t *image);
/* Returns TRUE if running on a little endian system
*/
static force_inline pixman_bool_t
is_little_endian (void)
{
unsigned long endian_check_var = 1;
return *(unsigned char *)&endian_check_var == 1;
}
/* perform endian conversion of pixel data
*/
void
image_endian_swap (pixman_image_t *img);
#if defined (HAVE_MPROTECT) && defined (HAVE_GETPAGESIZE) && \
defined (HAVE_SYS_MMAN_H) && defined (HAVE_MMAP)
/* fence_malloc and friends have working fence implementation.
* Without this, fence_malloc still allocs but does not catch
* out-of-bounds accesses.
*/
#define FENCE_MALLOC_ACTIVE 1
#else
#define FENCE_MALLOC_ACTIVE 0
#endif
/* Allocate memory that is bounded by protected pages,
* so that out-of-bounds access will cause segfaults
*/
void *
fence_malloc (int64_t len);
void
fence_free (void *data);
pixman_image_t *
fence_image_create_bits (pixman_format_code_t format,
int min_width,
int height,
pixman_bool_t stride_fence);
/* Return the page size if FENCE_MALLOC_ACTIVE, or zero otherwise */
unsigned long
fence_get_page_size ();
/* Generate n_bytes random bytes in fence_malloced memory */
uint8_t *
make_random_bytes (int n_bytes);
float *
make_random_floats (int n_bytes);
/* Return current time in seconds */
double
gettime (void);
uint32_t
get_random_seed (void);
/* main body of the fuzzer test */
int
fuzzer_test_main (const char *test_name,
int default_number_of_iterations,
uint32_t expected_checksum,
uint32_t (*test_function)(int testnum, int verbose),
int argc,
const char *argv[]);
void
fail_after (int seconds, const char *msg);
/* If possible, enable traps for floating point exceptions */
void enable_divbyzero_exceptions(void);
void enable_invalid_exceptions(void);
/* Converts a8r8g8b8 pixels to pixels that
* - are not premultiplied,
* - are stored in this order in memory: R, G, B, A, regardless of
* the endianness of the computer.
* It is allowed for @src and @dst to point to the same memory buffer.
*/
void
a8r8g8b8_to_rgba_np (uint32_t *dst, uint32_t *src, int n_pixels);
pixman_bool_t
write_png (pixman_image_t *image, const char *filename);
void
draw_checkerboard (pixman_image_t *image,
int check_size,
uint32_t color1, uint32_t color2);
/* A pair of macros which can help to detect corruption of
* floating point registers after a function call. This may
* happen if _mm_empty() call is forgotten in MMX/SSE2 fast
* path code, or ARM NEON assembly optimized function forgets
* to save/restore d8-d15 registers before use.
*/
#define FLOAT_REGS_CORRUPTION_DETECTOR_START() \
static volatile double frcd_volatile_constant1 = 123451; \
static volatile double frcd_volatile_constant2 = 123452; \
static volatile double frcd_volatile_constant3 = 123453; \
static volatile double frcd_volatile_constant4 = 123454; \
static volatile double frcd_volatile_constant5 = 123455; \
static volatile double frcd_volatile_constant6 = 123456; \
static volatile double frcd_volatile_constant7 = 123457; \
static volatile double frcd_volatile_constant8 = 123458; \
double frcd_canary_variable1 = frcd_volatile_constant1; \
double frcd_canary_variable2 = frcd_volatile_constant2; \
double frcd_canary_variable3 = frcd_volatile_constant3; \
double frcd_canary_variable4 = frcd_volatile_constant4; \
double frcd_canary_variable5 = frcd_volatile_constant5; \
double frcd_canary_variable6 = frcd_volatile_constant6; \
double frcd_canary_variable7 = frcd_volatile_constant7; \
double frcd_canary_variable8 = frcd_volatile_constant8;
#define FLOAT_REGS_CORRUPTION_DETECTOR_FINISH() \
assert (frcd_canary_variable1 == frcd_volatile_constant1); \
assert (frcd_canary_variable2 == frcd_volatile_constant2); \
assert (frcd_canary_variable3 == frcd_volatile_constant3); \
assert (frcd_canary_variable4 == frcd_volatile_constant4); \
assert (frcd_canary_variable5 == frcd_volatile_constant5); \
assert (frcd_canary_variable6 == frcd_volatile_constant6); \
assert (frcd_canary_variable7 == frcd_volatile_constant7); \
assert (frcd_canary_variable8 == frcd_volatile_constant8);
/* Try to get an aligned memory chunk */
void *
aligned_malloc (size_t align, size_t size);
double
convert_srgb_to_linear (double component);
double
convert_linear_to_srgb (double component);
void
initialize_palette (pixman_indexed_t *palette, uint32_t depth, int is_rgb);
pixman_format_code_t
format_from_string (const char *s);
void
list_formats (void);
void
list_operators (void);
pixman_op_t
operator_from_string (const char *s);
const char *
operator_name (pixman_op_t op);
const char *
format_name (pixman_format_code_t format);
typedef struct
{
double r, g, b, a;
} color_t;
void
do_composite (pixman_op_t op,
const color_t *src,
const color_t *mask,
const color_t *dst,
color_t *result,
pixman_bool_t component_alpha);
void
round_color (pixman_format_code_t format, color_t *color);
typedef struct
{
pixman_format_code_t format;
uint32_t am, rm, gm, bm;
uint32_t as, rs, gs, bs;
uint32_t aw, rw, gw, bw;
} pixel_checker_t;
void
pixel_checker_init (pixel_checker_t *checker, pixman_format_code_t format);
void
pixel_checker_split_pixel (const pixel_checker_t *checker, uint32_t pixel,
int *a, int *r, int *g, int *b);
void
pixel_checker_get_max (const pixel_checker_t *checker, color_t *color,
int *a, int *r, int *g, int *b);
void
pixel_checker_get_min (const pixel_checker_t *checker, color_t *color,
int *a, int *r, int *g, int *b);
pixman_bool_t
pixel_checker_check (const pixel_checker_t *checker,
uint32_t pixel, color_t *color);
void
pixel_checker_convert_pixel_to_color (const pixel_checker_t *checker,
uint32_t pixel, color_t *color);
void
pixel_checker_get_masks (const pixel_checker_t *checker,
uint32_t *am,
uint32_t *rm,
uint32_t *gm,
uint32_t *bm);
|
blockchain_fmt_plug.c | /* blockchain "My Wallet" cracker patch for JtR. Hacked together during June of
* 2013 by Dhiru Kholia <dhiru at openwall.com>.
*
* See https://blockchain.info/wallet/wallet-format
*
* This software is Copyright (c) 2013 Dhiru Kholia <dhiru at openwall.com>,
* and it is hereby released to the general public under the following terms:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* Improved detection, added iteration count and handle v2 hashes, Feb, 2015, JimF.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_blockchain;
#elif FMT_REGISTERS_H
john_register_one(&fmt_blockchain);
#else
#include <string.h>
#include <errno.h>
#include "arch.h"
#include "jumbo.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#include "johnswap.h"
#include "pbkdf2_hmac_sha1.h"
#include "blockchain_common.h"
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#define OMP_SCALE 4 // this is a slow format
#endif
#endif
#include "memdbg.h"
#define FORMAT_LABEL "Blockchain"
#define FORMAT_NAME "My Wallet"
#ifdef SIMD_COEF_32
#define ALGORITHM_NAME "PBKDF2-SHA1 AES " SHA1_ALGORITHM_NAME
#else
#define ALGORITHM_NAME "PBKDF2-SHA1 AES 32/" ARCH_BITS_STR
#endif
#define BENCHMARK_COMMENT " (x10)"
#define BENCHMARK_LENGTH -1
#define BINARY_SIZE 0
#define BINARY_ALIGN 1
#define PLAINTEXT_LENGTH 125
#define SALT_SIZE sizeof(struct custom_salt)
#define SALT_ALIGN 4
#ifdef SIMD_COEF_32
#define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1
#define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1
#else
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#endif
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static int *cracked;
static struct custom_salt *cur_salt;
static void init(struct fmt_main *self)
{
#if defined (_OPENMP)
int omp_t = 1;
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc_align(sizeof(*saved_key),
self->params.max_keys_per_crypt, MEM_ALIGN_WORD);
cracked = mem_calloc_align(sizeof(*cracked),
self->params.max_keys_per_crypt, MEM_ALIGN_WORD);
}
static void done(void)
{
MEM_FREE(cracked);
MEM_FREE(saved_key);
}
static void set_salt(void *salt)
{
cur_salt = (struct custom_salt *)salt;
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT)
#endif
{
#ifdef SIMD_COEF_32
unsigned char master[MAX_KEYS_PER_CRYPT][32];
int lens[MAX_KEYS_PER_CRYPT], i;
unsigned char *pin[MAX_KEYS_PER_CRYPT], *pout[MAX_KEYS_PER_CRYPT];
for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) {
lens[i] = strlen(saved_key[i+index]);
pin[i] = (unsigned char*)saved_key[i+index];
pout[i] = master[i];
}
pbkdf2_sha1_sse((const unsigned char **)pin, lens,
cur_salt->data, 16, cur_salt->iter, pout, 32, 0);
for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) {
if (blockchain_decrypt(master[i], cur_salt->data) == 0)
cracked[i+index] = 1;
else
cracked[i+index] = 0;
}
#else
unsigned char master[32];
pbkdf2_sha1((unsigned char *)saved_key[index],
strlen(saved_key[index]),
cur_salt->data, 16,
cur_salt->iter, master, 32, 0);
if (blockchain_decrypt(master, cur_salt->data) == 0)
cracked[index] = 1;
else
cracked[index] = 0;
#endif
}
return count;
}
static int cmp_all(void *binary, int count)
{
int index;
for (index = 0; index < count; index++)
if (cracked[index])
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return cracked[index];
}
static int cmp_exact(char *source, int index)
{
return 1;
}
static void blockchain_set_key(char *key, int index)
{
int saved_len = strlen(key);
if (saved_len > PLAINTEXT_LENGTH)
saved_len = PLAINTEXT_LENGTH;
memcpy(saved_key[index], key, saved_len);
saved_key[index][saved_len] = 0;
}
static char *get_key(int index)
{
return saved_key[index];
}
struct fmt_main fmt_blockchain = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_HUGE_INPUT,
{ NULL },
{ FORMAT_TAG },
blockchain_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
blockchain_common_valid,
fmt_default_split,
fmt_default_binary,
blockchain_common_get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash
},
fmt_default_salt_hash,
NULL,
set_salt,
blockchain_set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
com3.c | #include <mpi.h>
extern int local_cell_blocks;
extern int local_edge_blocks;
#include "grid.h"
#include "memory.h"
#include "component.h"
#include "io.h"
#include <stdint.h>
void com3_init(GRID * g);
void com3_compute(GRID * g);
void com3_io(GRID * g);
double com3_flops(GRID * g);
double com3_memory(GRID * g);
uint64_t com3_checksum(GRID *);
void com3_cleanup(GRID * g);
void O2VertIntegration(GRID * g);
void O3Indirect2D(GRID * g);
void O4Indirect3D(GRID * g);
void O5Indirect3D(GRID * g);
struct {
char *name;
int loc;
int dim;
union {
GVAL *restrict * restrict p2;
GVAL *restrict * restrict * restrict p3;
} data_pointer;
} *gv_vi;
struct {
char *name;
int loc;
int dim;
union {
GVAL *restrict * restrict p2;
GVAL *restrict * restrict * restrict p3;
} data_pointer;
} *gv_ind2Dparam;
struct {
char *name;
int loc;
int dim;
union {
GVAL *restrict * restrict p2;
GVAL *restrict * restrict * restrict p3;
} data_pointer;
} *gv_ind2Dvar;
struct {
char *name;
int loc;
int dim;
union {
GVAL *restrict * restrict p2;
GVAL *restrict * restrict * restrict p3;
} data_pointer;
} *gv_ind3Dvar;
struct {
char *name;
int loc;
int dim;
union {
int *restrict * restrict p2;
int *restrict * restrict * restrict p3;
} data_pointer;
} *t3DBlk;
struct {
char *name;
int loc;
int dim;
union {
int *restrict * restrict p2;
int *restrict * restrict * restrict p3;
} data_pointer;
} *t3DIdx;
struct {
char *name;
int loc;
int dim;
union {
int *restrict * restrict p2;
int *restrict * restrict * restrict p3;
} data_pointer;
} *t3DVer;
io_var_t io_gv_vi;
io_var_t io_gv_ind2Dvar;
io_var_t io_gv_ind3Dvar;
MODEL_COMPONENT com3 = { 0, com3_init, com3_compute, com3_io, com3_flops, com3_memory, com3_checksum, com3_cleanup };
extern struct {
char *name;
int loc;
int dim;
union {
GVAL *restrict * restrict p2;
GVAL *restrict * restrict * restrict p3;
} data_pointer;
} *gv_grad;
void init_opO4(GRID * g)
{
{
int num_blocks = local_edge_blocks ? local_edge_blocks : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
t3DBlk = malloc(24);
t3DBlk->name = "t3DBlk";
t3DBlk->loc = 1;
t3DBlk->dim = 3;
t3DBlk->data_pointer.p3 = malloc((num_blocks * g->height * g->blkSize) * sizeof(int) + (num_blocks * g->height) * sizeof(char *) + (num_blocks) * sizeof(char *));
char *pos = (char *) t3DBlk->data_pointer.p3 + num_blocks * sizeof(char *);
char *pos2 = (char *) t3DBlk->data_pointer.p3 + num_blocks * sizeof(char *) + num_blocks * g->height * sizeof(char *);
for (int b = 0; b < num_blocks; b++) {
t3DBlk->data_pointer.p3[b] = (int * *) pos;
pos += g->height * sizeof(char *);
for (int k = 0; k < g->height; k++) {
t3DBlk->data_pointer.p3[b][k] = (int *) pos2;
pos2 += g->blkSize * sizeof(int);
for (int e = 0; e < g->blkSize; e++) {
t3DBlk->data_pointer.p3[b][k][e] = (int) 0;
}
}
}
}
{
int num_blocks = local_edge_blocks ? local_edge_blocks : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
t3DIdx = malloc(24);
t3DIdx->name = "t3DIdx";
t3DIdx->loc = 1;
t3DIdx->dim = 3;
t3DIdx->data_pointer.p3 = malloc((num_blocks * g->height * g->blkSize) * sizeof(int) + (num_blocks * g->height) * sizeof(char *) + (num_blocks) * sizeof(char *));
char *pos = (char *) t3DIdx->data_pointer.p3 + num_blocks * sizeof(char *);
char *pos2 = (char *) t3DIdx->data_pointer.p3 + num_blocks * sizeof(char *) + num_blocks * g->height * sizeof(char *);
for (int b = 0; b < num_blocks; b++) {
t3DIdx->data_pointer.p3[b] = (int * *) pos;
pos += g->height * sizeof(char *);
for (int k = 0; k < g->height; k++) {
t3DIdx->data_pointer.p3[b][k] = (int *) pos2;
pos2 += g->blkSize * sizeof(int);
for (int e = 0; e < g->blkSize; e++) {
t3DIdx->data_pointer.p3[b][k][e] = (int) 0;
}
}
}
}
{
size_t min_block = g->mpi_rank == (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : 0;
size_t max_block = g->mpi_rank < (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) || g->mpi_rank > (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 : g->mpi_rank == (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
#pragma omp parallel for
for (size_t block_index = (min_block); block_index < (max_block); block_index++) {
for (size_t height_index = (0); height_index < (g->height); height_index++) {
for (size_t edge_index = (0); edge_index < (g->blkSize); edge_index++) {
if (gv_grad->data_pointer.p3[(block_index)][(height_index)][(edge_index)] > 0) {
t3DBlk->data_pointer.p3[(block_index)][(height_index)][(edge_index)] = g->eCellBlk[0]->data_pointer.p2[(block_index)][(edge_index)];
t3DIdx->data_pointer.p3[(block_index)][(height_index)][(edge_index)] = g->eCellIdx[0]->data_pointer.p2[(block_index)][(edge_index)];
} else {
t3DBlk->data_pointer.p3[(block_index)][(height_index)][(edge_index)] = g->eCellBlk[1]->data_pointer.p2[(block_index)][(edge_index)];
t3DIdx->data_pointer.p3[(block_index)][(height_index)][(edge_index)] = g->eCellIdx[1]->data_pointer.p2[(block_index)][(edge_index)];
}
}
}
}
}
}
void init_opO5(GRID * g)
{
{
int num_blocks = local_edge_blocks ? local_edge_blocks : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
t3DVer = malloc(24);
t3DVer->name = "t3DVer";
t3DVer->loc = 1;
t3DVer->dim = 3;
t3DVer->data_pointer.p3 = malloc((num_blocks * g->height * g->blkSize) * sizeof(int) + (num_blocks * g->height) * sizeof(char *) + (num_blocks) * sizeof(char *));
char *pos = (char *) t3DVer->data_pointer.p3 + num_blocks * sizeof(char *);
char *pos2 = (char *) t3DVer->data_pointer.p3 + num_blocks * sizeof(char *) + num_blocks * g->height * sizeof(char *);
for (int b = 0; b < num_blocks; b++) {
t3DVer->data_pointer.p3[b] = (int * *) pos;
pos += g->height * sizeof(char *);
for (int k = 0; k < g->height; k++) {
t3DVer->data_pointer.p3[b][k] = (int *) pos2;
pos2 += g->blkSize * sizeof(int);
for (int e = 0; e < g->blkSize; e++) {
t3DVer->data_pointer.p3[b][k][e] = (int) 0;
}
}
}
}
{
size_t min_block = g->mpi_rank == (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : 0;
size_t max_block = g->mpi_rank < (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) || g->mpi_rank > (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 : g->mpi_rank == (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
#pragma omp parallel for
for (size_t block_index = (min_block); block_index < (max_block); block_index++) {
for (size_t height_index = (0); height_index < ((g->height - 2)); height_index++) {
for (size_t edge_index = (0); edge_index < (g->blkSize); edge_index++) {
t3DVer->data_pointer.p3[(block_index)][(height_index)][(edge_index)] = height_index + 1;
}
}
}
}
{
size_t min_block = g->mpi_rank == (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : 0;
size_t max_block = g->mpi_rank < (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) || g->mpi_rank > (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 : g->mpi_rank == (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
#pragma omp parallel for
for (size_t block_index = (min_block); block_index < (max_block); block_index++) {
const size_t height_index = ((g->height - 1));
{
for (size_t edge_index = (0); edge_index < (g->blkSize); edge_index++) {
t3DVer->data_pointer.p3[(block_index)][(height_index)][(edge_index)] = (g->height - 1);
}
}
}
}
}
extern MODEL_COMPONENT com1;
void com3_init(GRID * g)
{
com3.loaded = 1;
if (!com1.loaded)
com1.init(g);
{
int num_blocks = local_cell_blocks ? local_cell_blocks : (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
gv_vi = malloc(24);
gv_vi->name = "gv_vi";
gv_vi->loc = 0;
gv_vi->dim = 2;
gv_vi->data_pointer.p2 = malloc((num_blocks * g->blkSize) * sizeof(GVAL) + (num_blocks) * sizeof(char *));
char *pos = (char *) gv_vi->data_pointer.p2 + num_blocks * sizeof(char *);
for (int b = 0; b < num_blocks; b++) {
gv_vi->data_pointer.p2[b] = (GVAL *) pos;
pos += g->blkSize * sizeof(GVAL);
for (int c = 0; c < g->blkSize; c++) {
gv_vi->data_pointer.p2[b][c] = (GVAL) 0;
}
}
}
{
int num_blocks = local_edge_blocks ? local_edge_blocks : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
gv_ind2Dparam = malloc(24);
gv_ind2Dparam->name = "gv_ind2Dparam";
gv_ind2Dparam->loc = 1;
gv_ind2Dparam->dim = 2;
gv_ind2Dparam->data_pointer.p2 = malloc((num_blocks * g->blkSize) * sizeof(GVAL) + (num_blocks) * sizeof(char *));
char *pos = (char *) gv_ind2Dparam->data_pointer.p2 + num_blocks * sizeof(char *);
for (int b = 0; b < num_blocks; b++) {
gv_ind2Dparam->data_pointer.p2[b] = (GVAL *) pos;
pos += g->blkSize * sizeof(GVAL);
for (int e = 0; e < g->blkSize; e++) {
gv_ind2Dparam->data_pointer.p2[b][e] = (GVAL) 0;
}
}
}
{
int num_blocks = local_edge_blocks ? local_edge_blocks : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
gv_ind2Dvar = malloc(24);
gv_ind2Dvar->name = "gv_ind2Dvar";
gv_ind2Dvar->loc = 1;
gv_ind2Dvar->dim = 3;
gv_ind2Dvar->data_pointer.p3 = malloc((num_blocks * g->height * g->blkSize) * sizeof(GVAL) + (num_blocks * g->height) * sizeof(char *) + (num_blocks) * sizeof(char *));
char *pos = (char *) gv_ind2Dvar->data_pointer.p3 + num_blocks * sizeof(char *);
char *pos2 = (char *) gv_ind2Dvar->data_pointer.p3 + num_blocks * sizeof(char *) + num_blocks * g->height * sizeof(char *);
for (int b = 0; b < num_blocks; b++) {
gv_ind2Dvar->data_pointer.p3[b] = (GVAL * *)pos;
pos += g->height * sizeof(char *);
for (int k = 0; k < g->height; k++) {
gv_ind2Dvar->data_pointer.p3[b][k] = (GVAL *) pos2;
pos2 += g->blkSize * sizeof(GVAL);
for (int e = 0; e < g->blkSize; e++) {
gv_ind2Dvar->data_pointer.p3[b][k][e] = (GVAL) 0;
}
}
}
}
{
int num_blocks = local_edge_blocks ? local_edge_blocks : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
gv_ind3Dvar = malloc(24);
gv_ind3Dvar->name = "gv_ind3Dvar";
gv_ind3Dvar->loc = 1;
gv_ind3Dvar->dim = 3;
gv_ind3Dvar->data_pointer.p3 = malloc((num_blocks * g->height * g->blkSize) * sizeof(GVAL) + (num_blocks * g->height) * sizeof(char *) + (num_blocks) * sizeof(char *));
char *pos = (char *) gv_ind3Dvar->data_pointer.p3 + num_blocks * sizeof(char *);
char *pos2 = (char *) gv_ind3Dvar->data_pointer.p3 + num_blocks * sizeof(char *) + num_blocks * g->height * sizeof(char *);
for (int b = 0; b < num_blocks; b++) {
gv_ind3Dvar->data_pointer.p3[b] = (GVAL * *)pos;
pos += g->height * sizeof(char *);
for (int k = 0; k < g->height; k++) {
gv_ind3Dvar->data_pointer.p3[b][k] = (GVAL *) pos2;
pos2 += g->blkSize * sizeof(GVAL);
for (int e = 0; e < g->blkSize; e++) {
gv_ind3Dvar->data_pointer.p3[b][k][e] = (GVAL) 0;
}
}
}
}
init_opO4(g);
init_opO5(g);
io_read_register(g, "gv_ind2Dparam", (GVAL *) gv_ind2Dparam, FLOAT32, FLOAT32, GRID_POS_EDGE, GRID_DIM_2D);
io_write_define(g, "gv_vi", (GVAL *) gv_vi, FLOAT32, GRID_POS_CELL, GRID_DIM_2D, &io_gv_vi);
io_write_define(g, "gv_ind2Dvar", (GVAL *) gv_ind2Dvar, FLOAT32, GRID_POS_EDGE, GRID_DIM_3D, &io_gv_ind2Dvar);
io_write_define(g, "gv_ind3Dvar", (GVAL *) gv_ind3Dvar, FLOAT32, GRID_POS_EDGE, GRID_DIM_3D, &io_gv_ind3Dvar);
}
void com3_compute(GRID * g)
{
O2VertIntegration(g);
O3Indirect2D(g);
O4Indirect3D(g);
O5Indirect3D(g);
}
void com3_io(GRID * g)
{
io_write_announce(g, &io_gv_vi);
io_write_announce(g, &io_gv_ind2Dvar);
io_write_announce(g, &io_gv_ind3Dvar);
}
double com3_flops(GRID * g)
{
double flop = (double) g->cellCount * (double) g->height + 3.0 * (double) g->edgeCount * (double) g->height + (double) g->edgeCount * (double) g->height;
return flop;
}
double com3_memory(GRID * g)
{
double mem = ((double) g->cellCount + (double) g->edgeCount + (double) g->edgeCount * (double) g->height + (double) g->edgeCount * (double) g->height) * (double) sizeof(GVAL) + (3.0 * (double) g->edgeCount * (double) g->height) * (double) sizeof(int);
return mem / (1024 * 1024);
}
uint64_t com3_checksum(GRID * g)
{
uint64_t ret = 0;
{
size_t min_block = g->mpi_rank == (0) / (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 % (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : 0;
size_t max_block = g->mpi_rank < (0) / (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) || g->mpi_rank > (g->cBlkCnt - 1) / (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 : g->mpi_rank == (g->cBlkCnt - 1) / (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->cBlkCnt % (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->cBlkCnt % (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->cBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
#pragma omp parallel for
for (size_t block_index = (min_block); block_index < (max_block); block_index++) {
for (size_t cell_index = (0); cell_index < (g->blkSize); cell_index++) {
ret += (uint64_t) gv_vi->data_pointer.p2[(block_index)][(cell_index)];
}
}
}
{
size_t min_block = g->mpi_rank == (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : 0;
size_t max_block = g->mpi_rank < (0) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) || g->mpi_rank > (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? 0 : g->mpi_rank == (g->eBlkCnt - 1) / (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) ? g->eBlkCnt % (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size) : (((g->eBlkCnt) + g->mpi_world_size - 1) / g->mpi_world_size);
#pragma omp parallel for
for (size_t block_index = (min_block); block_index < (max_block); block_index++) {
for (size_t height_index = (0); height_index < (g->height); height_index++) {
for (size_t edge_index = (0); edge_index < (g->blkSize); edge_index++) {
ret += (uint64_t) gv_ind2Dvar->data_pointer.p3[(block_index)][(height_index)][(edge_index)];
ret += (uint64_t) gv_ind3Dvar->data_pointer.p3[(block_index)][(height_index)][(edge_index)];
}
}
}
}
return ret;
}
void com3_cleanup(GRID * g)
{
com3.loaded = 0;
free((void *) gv_vi->data_pointer.p2);
free((void *) gv_ind2Dparam->data_pointer.p2);
free((void *) gv_ind2Dvar->data_pointer.p3);
free((void *) gv_ind3Dvar->data_pointer.p3);
free((void *) t3DBlk->data_pointer.p3);
free((void *) t3DIdx->data_pointer.p3);
free((void *) t3DVer->data_pointer.p3);
}
|
GB_binop__rdiv_uint64.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_mkl.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB_AaddB__rdiv_uint64
// A.*B function (eWiseMult): GB_AemultB__rdiv_uint64
// A*D function (colscale): GB_AxD__rdiv_uint64
// D*A function (rowscale): GB_DxB__rdiv_uint64
// C+=B function (dense accum): GB_Cdense_accumB__rdiv_uint64
// C+=b function (dense accum): GB_Cdense_accumb__rdiv_uint64
// C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__rdiv_uint64
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__rdiv_uint64
// C=scalar+B GB_bind1st__rdiv_uint64
// C=scalar+B' GB_bind1st_tran__rdiv_uint64
// C=A+scalar GB_bind2nd__rdiv_uint64
// C=A'+scalar GB_bind2nd_tran__rdiv_uint64
// C type: uint64_t
// A type: uint64_t
// B,b type: uint64_t
// BinaryOp: cij = GB_IDIV_UNSIGNED (bij, aij, 64)
#define GB_ATYPE \
uint64_t
#define GB_BTYPE \
uint64_t
#define GB_CTYPE \
uint64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint64_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y) \
z = GB_IDIV_UNSIGNED (y, x, 64) ;
// 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_RDIV || GxB_NO_UINT64 || GxB_NO_RDIV_UINT64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB_Cdense_ewise3_accum__rdiv_uint64
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__rdiv_uint64
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumB__rdiv_uint64
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__rdiv_uint64
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint64_t
uint64_t bwork = (*((uint64_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_AxD__rdiv_uint64
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_DxB__rdiv_uint64
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB_AaddB__rdiv_uint64
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_add_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB_AemultB__rdiv_uint64
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB_bind1st__rdiv_uint64
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *Cx = (uint64_t *) Cx_output ;
uint64_t x = (*((uint64_t *) x_input)) ;
uint64_t *Bx = (uint64_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint64_t bij = Bx [p] ;
Cx [p] = GB_IDIV_UNSIGNED (bij, x, 64) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__rdiv_uint64
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint64_t *Cx = (uint64_t *) Cx_output ;
uint64_t *Ax = (uint64_t *) Ax_input ;
uint64_t y = (*((uint64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint64_t aij = Ax [p] ;
Cx [p] = GB_IDIV_UNSIGNED (y, aij, 64) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = Ax [pA] ; \
Cx [pC] = GB_IDIV_UNSIGNED (aij, x, 64) ; \
}
GrB_Info GB_bind1st_tran__rdiv_uint64
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t x = (*((const uint64_t *) x_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint64_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = Ax [pA] ; \
Cx [pC] = GB_IDIV_UNSIGNED (y, aij, 64) ; \
}
GrB_Info GB_bind2nd_tran__rdiv_uint64
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t y = (*((const uint64_t *) y_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unaryop__minv_uint16_int8.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__minv_uint16_int8
// op(A') function: GB_tran__minv_uint16_int8
// C type: uint16_t
// A type: int8_t
// cast: uint16_t cij = (uint16_t) aij
// unaryop: cij = GB_IMINV_UNSIGNED (aij, 16)
#define GB_ATYPE \
int8_t
#define GB_CTYPE \
uint16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int8_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IMINV_UNSIGNED (x, 16) ;
// casting
#define GB_CASTING(z, aij) \
uint16_t z = (uint16_t) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_UINT16 || GxB_NO_INT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_uint16_int8
(
uint16_t *Cx, // Cx and Ax may be aliased
int8_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__minv_uint16_int8
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_subref_template.c | //------------------------------------------------------------------------------
// GB_subref_template: C = A(I,J), or C = pattern (A(I,J))
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
#if defined ( GB_SYMBOLIC )
// symbolic method must tolerate zombies
#define GB_Ai(p) GBI_UNFLIP (Ai, p, avlen)
#else
// numeric method will not see any zombies
#define GB_Ai(p) GBI (Ai, p, avlen)
#endif
// to iterate across all entries in a bucket:
#define GB_for_each_index_in_bucket(inew,i) \
for (int64_t inew = Mark [i] - 1 ; inew >= 0 ; inew = Inext [inew])
// copy values from A(:,kA) to C(:,kC): Cx [pC:pC+len-1] = ... (pA:pA+len-1).
#if defined ( GB_SYMBOLIC )
// symbolic copy: Cx is int64_t; Ax is ignored
#define GB_COPY_RANGE(pC,pA,len) \
for (int64_t k = 0 ; k < (len) ; k++) \
{ \
Cx [(pC) + k] = (pA) + k ; \
}
#else
// numeric copy: Cx and Ax are both (GB_void *), and point to the same type
#define GB_COPY_RANGE(pC,pA,len) \
memcpy (Cx + (pC)*asize, Ax + (pA)*asize, (len) * asize) ;
#endif
// copy a single value from A(:,kA) to C(:,kC): Cx [pC] = ... (pA])
#if defined ( GB_SYMBOLIC )
// symbolic copy: Cx is int64_t; Ax is ignored
#define GB_COPY_ENTRY(pC,pA) \
Cx [pC] = (pA) ;
#else
// numeric copy: Cx and Ax are both (GB_void *), and point to the same type
#define GB_COPY_ENTRY(pC,pA) \
/* Cx [pC] = Ax [pA] */ \
memcpy (Cx + (pC)*asize, Ax + (pA)*asize, asize) ;
#endif
// the type of Cx
#if defined ( GB_SYMBOLIC )
// C is an int64_t array; the type of A is ignored
#define GB_CTYPE int64_t
#define GB_CSIZE1 1
#define GB_CSIZE2 (sizeof (int64_t))
#else
// C and A have the same type
#define GB_CTYPE GB_void
#define GB_CSIZE1 asize
#define GB_CSIZE2 asize
#endif
{
//--------------------------------------------------------------------------
// get A
//--------------------------------------------------------------------------
const int64_t *restrict Ai = A->i ;
const int64_t avlen = A->vlen ;
#if defined ( GB_SYMBOLIC )
const int64_t nzombies = A->nzombies ;
#endif
#if defined ( GB_PHASE_2_OF_2 ) && defined ( GB_NUMERIC )
ASSERT (C->type = A->type) ;
const GB_void *restrict Ax = (GB_void *) A->x ;
const int64_t asize = A->type->size ;
#endif
//--------------------------------------------------------------------------
// get C
//--------------------------------------------------------------------------
#if defined ( GB_PHASE_2_OF_2 )
int64_t *restrict Ci = C->i ;
GB_CTYPE *restrict Cx = (GB_CTYPE *) C->x ;
#endif
//--------------------------------------------------------------------------
// get I
//--------------------------------------------------------------------------
// these values are ignored if Ikind == GB_LIST
int64_t ibegin = Icolon [GxB_BEGIN] ;
int64_t iinc = Icolon [GxB_INC ] ;
int64_t inc = (iinc < 0) ? (-iinc) : iinc ;
#ifdef GB_DEBUG
int64_t iend = Icolon [GxB_END ] ;
#endif
//--------------------------------------------------------------------------
// phase1: count entries in each C(:,kC); phase2: compute C
//--------------------------------------------------------------------------
int taskid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
int64_t kfirst = TaskList [taskid].kfirst ;
int64_t klast = TaskList [taskid].klast ;
bool fine_task = (klast < 0) ;
if (fine_task)
{
// a fine task operates on a slice of a single vector
klast = kfirst ;
}
// a coarse task accesses all of I for all its vectors
int64_t pI = 0 ;
int64_t pI_end = nI ;
int64_t ilen = nI ;
ASSERT (0 <= kfirst && kfirst <= klast && klast < Cnvec) ;
//----------------------------------------------------------------------
// compute all vectors C(:,kfirst:klast) for this task
//----------------------------------------------------------------------
for (int64_t kC = kfirst ; kC <= klast ; kC++)
{
//------------------------------------------------------------------
// get C(:,kC)
//------------------------------------------------------------------
#if defined ( GB_PHASE_1_OF_2 )
// phase1 simply counts the # of entries in C(*,kC).
int64_t clen = 0 ;
#else
// This task computes all or part of C(:,kC), which are the entries
// in Ci,Cx [pC:pC_end-1].
int64_t pC, pC_end ;
if (fine_task)
{
// A fine task computes a slice of C(:,kC)
pC = TaskList [taskid ].pC ;
pC_end = TaskList [taskid+1].pC ;
ASSERT (Cp [kC] <= pC && pC <= pC_end && pC_end <= Cp [kC+1]) ;
}
else
{
// The vectors of C are never sliced for a coarse task, so this
// task computes all of C(:,kC).
pC = Cp [kC] ;
pC_end = Cp [kC+1] ;
}
int64_t clen = pC_end - pC ;
if (clen == 0) continue ;
#endif
//------------------------------------------------------------------
// get A(:,kA)
//------------------------------------------------------------------
int64_t pA, pA_end ;
if (fine_task)
{
// a fine task computes a slice of a single vector C(:,kC).
// The task accesses Ai,Ax [pA:pA_end-1], which holds either
// the entire vector A(imin:imax,kA) for method 6, the entire
// dense A(:,kA) for methods 1 and 2, or a slice of the
// A(imin:max,kA) vector for all other methods.
pA = TaskList [taskid].pA ;
pA_end = TaskList [taskid].pA_end ;
}
else
{
// a coarse task computes the entire vector C(:,kC). The task
// accesses all of A(imin:imax,kA), for most methods, or all of
// A(:,kA) for methods 1 and 2. The vector A(*,kA) appears in
// Ai,Ax [pA:pA_end-1].
pA = Ap_start [kC] ;
pA_end = Ap_end [kC] ;
}
int64_t alen = pA_end - pA ;
if (alen == 0) continue ;
//------------------------------------------------------------------
// get I
//------------------------------------------------------------------
if (fine_task)
{
// A fine task accesses I [pI:pI_end-1]. For methods 2 and 6,
// pI:pI_end is a subset of the entire 0:nI-1 list. For all
// other methods, pI = 0 and pI_end = nI, and the task can
// access all of I.
pI = TaskList [taskid].pB ;
pI_end = TaskList [taskid].pB_end ;
ilen = pI_end - pI ;
}
//------------------------------------------------------------------
// determine the method to use
//------------------------------------------------------------------
int method ;
if (fine_task)
{
// The method that the fine task uses for its slice of A(*,kA)
// and C(*,kC) has already been determined by GB_subref_slice.
method = (int) (-TaskList [taskid].klast) ;
}
else
{
// determine the method based on A(*,kA) and I
method = GB_subref_method (NULL, NULL, alen, avlen, Ikind, nI,
(Mark != NULL), need_qsort, iinc, nduplicates) ;
}
//------------------------------------------------------------------
// extract C (:,kC) = A (I,kA): consider all cases
//------------------------------------------------------------------
switch (method)
{
//--------------------------------------------------------------
case 1 : // C(:,kC) = A(:,kA) where A(:,kA) is dense
//--------------------------------------------------------------
// A (:,kA) has not been sliced
ASSERT (Ikind == GB_ALL) ;
ASSERT (pA == Ap_start [kC]) ;
ASSERT (pA_end == Ap_end [kC]) ;
// copy the entire vector and construct indices
#if defined ( GB_PHASE_1_OF_2 )
clen = ilen ;
#else
for (int64_t k = 0 ; k < ilen ; k++)
{
int64_t inew = k + pI ;
ASSERT (inew == GB_ijlist (I, inew, Ikind, Icolon)) ;
ASSERT (inew == GB_Ai (pA + inew)) ;
Ci [pC + k] = inew ;
}
GB_COPY_RANGE (pC, pA + pI, ilen) ;
#endif
break ;
//--------------------------------------------------------------
case 2 : // C(:,kC) = A(I,kA) where A(I,kA) is dense
//--------------------------------------------------------------
// This method handles any kind of list I, but A(:,kA)
// must be dense. A(:,kA) has not been sliced.
ASSERT (pA == Ap_start [kC]) ;
ASSERT (pA_end == Ap_end [kC]) ;
// scan I and get the entry in A(:,kA) via direct lookup
#if defined ( GB_PHASE_1_OF_2 )
clen = ilen ;
#else
for (int64_t k = 0 ; k < ilen ; k++)
{
// C(inew,kC) = A(i,kA), and it always exists.
int64_t inew = k + pI ;
int64_t i = GB_ijlist (I, inew, Ikind, Icolon) ;
ASSERT (i == GB_Ai (pA + i)) ;
Ci [pC + k] = inew ;
GB_COPY_ENTRY (pC + k, pA + i) ;
}
#endif
break ;
//--------------------------------------------------------------
case 3 : // the list I has a single index, ibegin
//--------------------------------------------------------------
// binary search in GB_subref_phase0 has already found it.
// This can be any Ikind with nI=1: GB_ALL with A->vlen=1,
// GB_RANGE with ibegin==iend, GB_STRIDE such as 0:-1:0
// (with length 1), or a GB_LIST with ni=1.
// Time: 50x faster than MATLAB
ASSERT (!fine_task) ;
ASSERT (alen == 1) ;
ASSERT (nI == 1) ;
ASSERT (GB_Ai (pA) == GB_ijlist (I, 0, Ikind, Icolon)) ;
#if defined ( GB_PHASE_1_OF_2 )
clen = 1 ;
#else
Ci [pC] = 0 ;
GB_COPY_ENTRY (pC, pA) ;
#endif
break ;
//--------------------------------------------------------------
case 4 : // Ikind is ":", thus C(:,kC) = A (:,kA)
//--------------------------------------------------------------
// Time: 1x MATLAB but low speedup on the Mac. Why?
// Probably memory bound since it is just memcpy's.
ASSERT (Ikind == GB_ALL && ibegin == 0) ;
#if defined ( GB_PHASE_1_OF_2 )
clen = alen ;
#else
#if defined ( GB_SYMBOLIC )
if (nzombies == 0)
{
memcpy (Ci + pC, Ai + pA, alen * sizeof (int64_t)) ;
}
else
{
// with zombies
for (int64_t k = 0 ; k < alen ; k++)
{
// symbolic C(:,kC) = A(:,kA) where A has zombies
int64_t i = GB_Ai (pA + k) ;
ASSERT (i == GB_ijlist (I, i, Ikind, Icolon)) ;
Ci [pC + k] = i ;
}
}
#else
memcpy (Ci + pC, Ai + pA, alen * sizeof (int64_t)) ;
#endif
GB_COPY_RANGE (pC, pA, alen) ;
#endif
break ;
//--------------------------------------------------------------
case 5 : // Ikind is GB_RANGE = ibegin:iend
//--------------------------------------------------------------
// Time: much faster than MATLAB. Good speedup too.
ASSERT (Ikind == GB_RANGE) ;
#if defined ( GB_PHASE_1_OF_2 )
clen = alen ;
#else
for (int64_t k = 0 ; k < alen ; k++)
{
int64_t i = GB_Ai (pA + k) ;
int64_t inew = i - ibegin ;
ASSERT (i == GB_ijlist (I, inew, Ikind, Icolon)) ;
Ci [pC + k] = inew ;
}
GB_COPY_RANGE (pC, pA, alen) ;
#endif
break ;
//--------------------------------------------------------------
case 6 : // I is short vs nnz (A (:,kA)), use binary search
//--------------------------------------------------------------
// Time: very slow unless I is very short and A(:,kA) is
// very long.
// This case can handle any kind of I, and A(:,kA) of any
// properties. For a fine task, A(:,kA) has not been
// sliced; I has been sliced instead.
// If the I bucket inverse has not been created, this
// method is the only option. Alternatively, if nI =
// length (I) is << nnz (A (:,kA)), then scanning I and
// doing a binary search of A (:,kA) is faster than doing a
// linear-time search of A(:,kA) and a lookup into the I
// bucket inverse.
// The vector of C is constructed in sorted order, so no
// sort is needed.
// A(:,kA) has not been sliced.
ASSERT (pA == Ap_start [kC]) ;
ASSERT (pA_end == Ap_end [kC]) ;
// scan I, in order, and search for the entry in A(:,kA)
for (int64_t k = 0 ; k < ilen ; k++)
{
// C(inew,kC) = A (i,kA), if it exists.
// i = I [inew] ; or from a colon expression
int64_t inew = k + pI ;
int64_t i = GB_ijlist (I, inew, Ikind, Icolon) ;
bool found ;
int64_t pleft = pA ;
int64_t pright = pA_end - 1 ;
#if defined ( GB_SYMBOLIC )
bool is_zombie ;
GB_BINARY_SEARCH_ZOMBIE (i, Ai, pleft, pright, found,
nzombies, is_zombie) ;
#else
GB_BINARY_SEARCH (i, Ai, pleft, pright, found) ;
#endif
if (found)
{
ASSERT (i == GB_Ai (pleft)) ;
#if defined ( GB_PHASE_1_OF_2 )
clen++ ;
#else
ASSERT (pC < pC_end) ;
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pleft) ;
pC++ ;
#endif
}
}
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pC == pC_end) ;
#endif
break ;
//--------------------------------------------------------------
case 7 : // I is ibegin:iinc:iend with iinc > 1
//--------------------------------------------------------------
// Time: 1 thread: C=A(1:2:n,:) is 3x slower than MATLAB
// but has good speedup. About as fast as MATLAB with
// enough threads.
ASSERT (Ikind == GB_STRIDE && iinc > 1) ;
for (int64_t k = 0 ; k < alen ; k++)
{
// A(i,kA) present; see if it is in ibegin:iinc:iend
int64_t i = GB_Ai (pA + k) ;
ASSERT (ibegin <= i && i <= iend) ;
i = i - ibegin ;
if (i % iinc == 0)
{
// i is in the sequence ibegin:iinc:iend
#if defined ( GB_PHASE_1_OF_2 )
clen++ ;
#else
int64_t inew = i / iinc ;
ASSERT (pC < pC_end) ;
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pA + k) ;
pC++ ;
#endif
}
}
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pC == pC_end) ;
#endif
break ;
//----------------------------------------------------------
case 8 : // I = ibegin:(-iinc):iend, with iinc < -1
//----------------------------------------------------------
// Time: 2x slower than MATLAB for iinc = -2 or -8.
// Good speedup though. Faster than MATLAB for
// large values (iinc = -128).
ASSERT (Ikind == GB_STRIDE && iinc < -1) ;
for (int64_t k = alen - 1 ; k >= 0 ; k--)
{
// A(i,kA) present; see if it is in ibegin:iinc:iend
int64_t i = GB_Ai (pA + k) ;
ASSERT (iend <= i && i <= ibegin) ;
i = ibegin - i ;
if (i % inc == 0)
{
// i is in the sequence ibegin:iinc:iend
#if defined ( GB_PHASE_1_OF_2 )
clen++ ;
#else
int64_t inew = i / inc ;
ASSERT (pC < pC_end) ;
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pA + k) ;
pC++ ;
#endif
}
}
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pC == pC_end) ;
#endif
break ;
//----------------------------------------------------------
case 9 : // I = ibegin:(-1):iend
//----------------------------------------------------------
// Time: much faster than MATLAB. Good speedup.
ASSERT (Ikind == GB_STRIDE && iinc == -1) ;
#if defined ( GB_PHASE_1_OF_2 )
clen = alen ;
#else
for (int64_t k = alen - 1 ; k >= 0 ; k--)
{
// A(i,kA) is present
int64_t i = GB_Ai (pA + k) ;
int64_t inew = (ibegin - i) ;
ASSERT (i == GB_ijlist (I, inew, Ikind, Icolon)) ;
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pA + k) ;
pC++ ;
}
#endif
break ;
//--------------------------------------------------------------
case 10 : // I unsorted, and C needs qsort, duplicates OK
//--------------------------------------------------------------
// Time: with one thread: 2x slower than MATLAB, probably
// because of the qsort. Good speedup however. This used
// if qsort is needed but ndupl == 0. Try a method that
// needs qsort, but no duplicates?
// Case 10 works well when I has many entries and A(:,kA)
// has few entries. C(:,kC) must be sorted after this pass.
ASSERT (Ikind == GB_LIST) ;
for (int64_t k = 0 ; k < alen ; k++)
{
// A(i,kA) present, look it up in the I inverse buckets
int64_t i = GB_Ai (pA + k) ;
// traverse bucket i for all indices inew where
// i == I [inew] or where i is from a colon expression
GB_for_each_index_in_bucket (inew, i)
{
ASSERT (inew >= 0 && inew < nI) ;
ASSERT (i == GB_ijlist (I, inew, Ikind, Icolon)) ;
#if defined ( GB_PHASE_1_OF_2 )
clen++ ;
#else
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pA + k) ;
pC++ ;
#endif
}
}
// TODO: skip the sort if C is allowed to be jumbled on
// output. Flag C as jumbled instead.
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pC == pC_end) ;
if (!fine_task)
{
// a coarse task owns this entire C(:,kC) vector, so
// the sort can be done now. The sort for vectors
// handled by multiple fine tasks must wait until all
// task are completed, below in the post sort.
pC = Cp [kC] ;
GB_qsort_1b (Ci + pC, (GB_void *) (Cx + pC*GB_CSIZE1),
GB_CSIZE2, clen) ;
}
#endif
break ;
//--------------------------------------------------------------
case 11 : // I not contiguous, with duplicates. No qsort needed
//--------------------------------------------------------------
// Case 11 works well when I has many entries and A(:,kA)
// has few entries. It requires that I be sorted on input,
// so that no sort is required for C(:,kC). It is
// otherwise identical to Case 10.
ASSERT (Ikind == GB_LIST) ;
for (int64_t k = 0 ; k < alen ; k++)
{
// A(i,kA) present, look it up in the I inverse buckets
int64_t i = GB_Ai (pA + k) ;
// traverse bucket i for all indices inew where
// i == I [inew] or where i is from a colon expression
GB_for_each_index_in_bucket (inew, i)
{
ASSERT (inew >= 0 && inew < nI) ;
ASSERT (i == GB_ijlist (I, inew, Ikind, Icolon)) ;
#if defined ( GB_PHASE_1_OF_2 )
clen++ ;
#else
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pA + k) ;
pC++ ;
#endif
}
}
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pC == pC_end) ;
#endif
break ;
//--------------------------------------------------------------
case 12 : // I not contiguous, no duplicates. No qsort needed.
//--------------------------------------------------------------
// Identical to Case 11, except GB_for_each_index_in_bucket
// just needs to iterate 0 or 1 times. Works well when I
// has many entries and A(:,kA) has few entries.
ASSERT (Ikind == GB_LIST && nduplicates == 0) ;
for (int64_t k = 0 ; k < alen ; k++)
{
// A(i,kA) present, look it up in the I inverse buckets
int64_t i = GB_Ai (pA + k) ;
// bucket i has at most one index inew such that
// i == I [inew]
int64_t inew = Mark [i] - 1 ;
if (inew >= 0)
{
ASSERT (inew >= 0 && inew < nI) ;
ASSERT (i == GB_ijlist (I, inew, Ikind, Icolon)) ;
#if defined ( GB_PHASE_1_OF_2 )
clen++ ;
#else
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pA + k) ;
pC++ ;
#endif
}
}
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pC == pC_end) ;
#endif
break ;
//--------------------------------------------------------------
default: ;
//--------------------------------------------------------------
}
//------------------------------------------------------------------
// final count of nnz (C (:,j))
//------------------------------------------------------------------
#if defined ( GB_PHASE_1_OF_2 )
if (fine_task)
{
TaskList [taskid].pC = clen ;
}
else
{
Cp [kC] = clen ;
}
#endif
}
}
//--------------------------------------------------------------------------
// phase2: post sort for any vectors handled by fine tasks with method 10
//--------------------------------------------------------------------------
// TODO: skip the sort if C is allowed to be jumbled on output.
// Flag C as jumbled instead.
#if defined ( GB_PHASE_2_OF_2 )
if (post_sort)
{
int taskid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
int64_t kC = TaskList [taskid].kfirst ;
bool do_post_sort = (TaskList [taskid].len != 0) ;
if (do_post_sort)
{
// This is the first fine task with method 10 for C(:,kC). The
// vector C(:,kC) must be sorted, since method 10 left it with
// unsorted indices.
int64_t pC = Cp [kC] ;
int64_t clen = Cp [kC+1] - pC ;
GB_qsort_1b (Ci + pC, (GB_void *) (Cx + pC*GB_CSIZE1),
GB_CSIZE2, clen) ;
}
}
}
#endif
}
#undef GB_Ai
#undef GB_for_each_index_in_bucket
#undef GB_COPY_RANGE
#undef GB_COPY_ENTRY
#undef GB_CTYPE
#undef GB_CSIZE1
#undef GB_CSIZE2
|
kmp_taskwait_depend_in.c | // RUN: %libomp-compile-and-run
// test checks IN dep kind in depend clause on taskwait construct
// uses codegen emulation
#include <stdio.h>
#include <omp.h>
// ---------------------------------------------------------------------------
// internal data to emulate compiler codegen
typedef struct DEP {
size_t addr;
size_t len;
unsigned char flags;
} _dep;
typedef struct ID {
int reserved_1;
int flags;
int reserved_2;
int reserved_3;
char *psource;
} _id;
#ifdef __cplusplus
extern "C" {
#endif
extern int __kmpc_global_thread_num(_id*);
extern void __kmpc_omp_wait_deps(_id *, int, int, _dep *, int, _dep *);
#ifdef __cplusplus
} // extern "C"
#endif
int main()
{
int i1,i2,i3;
omp_set_num_threads(2);
printf("addresses: %p %p %p\n", &i1, &i2, &i3);
#pragma omp parallel
{
int t = omp_get_thread_num();
printf("thread %d enters parallel\n", t);
#pragma omp single
{
#pragma omp task depend(in: i3)
{
int th = omp_get_thread_num();
printf("task 0 created by th %d, executed by th %d\n", t, th);
}
#pragma omp task depend(in: i2)
{
int th = omp_get_thread_num();
printf("task 1 created by th %d, executed by th %d\n", t, th);
}
// #pragma omp taskwait depend(in: i1, i2)
{
_dep sdep[2];
static _id loc = {0, 2, 0, 0, ";test9.c;func;60;0;;"};
int gtid = __kmpc_global_thread_num(&loc);
sdep[0].addr = (size_t)&i2;
sdep[0].flags = 1; // 1-in, 2-out, 3-inout, 4-mtx, 8-inoutset
sdep[1].addr = (size_t)&i1;
sdep[1].flags = 1; // in
__kmpc_omp_wait_deps(&loc, gtid, 2, sdep, 0, NULL);
}
printf("single done\n");
}
}
printf("passed\n");
return 0;
}
|
GB_bitmap_assign_M_col_template.c | //------------------------------------------------------------------------------
// GB_bitmap_assign_M_col_template: traverse M for GB_COL_ASSIGN
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// M is a (C->vlen)-by-1 hypersparse or sparse matrix, for
// GrB_Row_assign (if C is CSR) or GrB_Col_assign (if C is CSC).
// C is bitmap/full. M is sparse/hyper, and can be jumbled.
{
const int64_t *restrict kfirst_Mslice = M_ek_slicing ;
const int64_t *restrict klast_Mslice = M_ek_slicing + M_ntasks ;
const int64_t *restrict pstart_Mslice = M_ek_slicing + M_ntasks * 2 ;
int64_t jC = J [0] ;
int tid ;
#pragma omp parallel for num_threads(M_nthreads) schedule(dynamic,1) \
reduction(+:cnvals)
for (tid = 0 ; tid < M_ntasks ; tid++)
{
int64_t kfirst = kfirst_Mslice [tid] ;
int64_t klast = klast_Mslice [tid] ;
int64_t task_cnvals = 0 ;
//----------------------------------------------------------------------
// traverse over M (:,kfirst:klast)
//----------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//------------------------------------------------------------------
// find the part of M(:,k) for this task
//------------------------------------------------------------------
ASSERT (k == 0) ;
ASSERT (GBH (Mh, k) == 0) ;
int64_t pM_start, pM_end ;
GB_get_pA (&pM_start, &pM_end, tid, k, kfirst,
klast, pstart_Mslice, Mp, mvlen) ;
//------------------------------------------------------------------
// traverse over M(:,0), the kth vector of M
//------------------------------------------------------------------
// for col_assign: M is a single vector, jC = J [0]
for (int64_t pM = pM_start ; pM < pM_end ; pM++)
{
bool mij = GB_mcast (Mx, pM, msize) ;
if (mij)
{
int64_t iC = Mi [pM] ;
int64_t pC = iC + jC * cvlen ;
GB_MASK_WORK (pC) ;
}
}
}
cnvals += task_cnvals ;
}
}
|
GB_binop__isgt_fp64.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__isgt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_08__isgt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_02__isgt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_04__isgt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__isgt_fp64)
// A*D function (colscale): GB (_AxD__isgt_fp64)
// D*A function (rowscale): GB (_DxB__isgt_fp64)
// C+=B function (dense accum): GB (_Cdense_accumB__isgt_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__isgt_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isgt_fp64)
// C=scalar+B GB (_bind1st__isgt_fp64)
// C=scalar+B' GB (_bind1st_tran__isgt_fp64)
// C=A+scalar GB (_bind2nd__isgt_fp64)
// C=A'+scalar GB (_bind2nd_tran__isgt_fp64)
// C type: double
// A type: double
// A pattern? 0
// B type: double
// B pattern? 0
// BinaryOp: cij = (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)
// 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) \
double 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) \
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 = (x > y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ISGT || GxB_NO_FP64 || GxB_NO_ISGT_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
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__isgt_fp64)
(
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__isgt_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__isgt_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
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__isgt_fp64)
(
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
double *restrict Cx = (double *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__isgt_fp64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
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
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__isgt_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 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) ;
double alpha_scalar ;
double beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((double *) alpha_scalar_in)) ;
beta_scalar = (*((double *) 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__isgt_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_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__isgt_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_04__isgt_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_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__isgt_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__isgt_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] = (x > bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__isgt_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] = (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] = (x > aij) ; \
}
GrB_Info GB (_bind1st_tran__isgt_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] = (aij > y) ; \
}
GrB_Info GB (_bind2nd_tran__isgt_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
|
axpby.c | /*
The MIT License (MIT)
Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
extern "C" void FUNC(axpby)(const dlong & N, const dlong & xOffset, const dlong& yOffset, const dfloat & alpha, const dfloat * __restrict__ cpu_a,
const dfloat &beta, dfloat * __restrict__ cpu_b){
#ifdef __NEKRS__OMP__
#pragma omp parallel for
#endif
for(dlong i=0;i<N;++i){
const dfloat ai = cpu_a[i + xOffset];
const dfloat bi = cpu_b[i + yOffset];
cpu_b[i + yOffset] = alpha*ai + beta*bi;
}
}
|
convolution_3x3_int8.h | // BUG1989 is pleased to support the open source community by supporting ncnn available.
//
// author:BUG1989 (https://github.com/BUG1989/) Long-term support.
// author:FuGuangping (https://github.com/fu1899) Implemented the first version of INT8 quantization on ARMv7.
//
// Copyright (C) 2019 BUG1989. All rights reserved.
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void conv3x3s1_winograd23_transform_kernel_int8_neon(const Mat& kernel, std::vector<Mat> &kernel_tm2, int inch, int outch)
{
Mat kernel_tm(4*4, inch, outch, 2ul);
// G
const short ktm[4][3] = {
{ 2, 0, 0},
{ 1, 1, 1},
{ 1, -1, 1},
{ 0, 0, 2}
};
#pragma omp parallel for
for (int p = 0; p<outch; p++)
{
for (int q = 0; q<inch; q++)
{
const signed char* kernel0 = (const signed char*)kernel + p*inch * 9 + q * 9;
short* kernel_tm0 = kernel_tm.channel(p).row<short>(q);
// transform kernel
const signed char* k0 = kernel0;
const signed char* k1 = kernel0 + 3;
const signed char* k2 = kernel0 + 6;
// h
short tmp[4][3];
for (int i=0; i<4; i++)
{
tmp[i][0] = (short)k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = (short)k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = (short)k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// U
for (int j=0; j<4; j++)
{
short* tmpp = &tmp[j][0];
for (int i=0; i<4; i++)
{
kernel_tm0[j*4 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
for (int r=0; r<4; r++)
{
Mat kernel_tm_test(4*8, inch, outch/8 + (outch%8)/4 + outch%4, 2u);
int p = 0;
for (; p+7<outch; p+=8)
{
const short* kernel0 = (const short*)kernel_tm + (p+0)*inch*16;
const short* kernel1 = (const short*)kernel_tm + (p+1)*inch*16;
const short* kernel2 = (const short*)kernel_tm + (p+2)*inch*16;
const short* kernel3 = (const short*)kernel_tm + (p+3)*inch*16;
const short* kernel4 = (const short*)kernel_tm + (p+4)*inch*16;
const short* kernel5 = (const short*)kernel_tm + (p+5)*inch*16;
const short* kernel6 = (const short*)kernel_tm + (p+6)*inch*16;
const short* kernel7 = (const short*)kernel_tm + (p+7)*inch*16;
short* ktmp = kernel_tm_test.channel(p/8);
for (int q=0; q<inch; q++)
{
ktmp[0] = kernel0[r*4+0];
ktmp[1] = kernel0[r*4+1];
ktmp[2] = kernel0[r*4+2];
ktmp[3] = kernel0[r*4+3];
ktmp[4] = kernel1[r*4+0];
ktmp[5] = kernel1[r*4+1];
ktmp[6] = kernel1[r*4+2];
ktmp[7] = kernel1[r*4+3];
ktmp[8] = kernel2[r*4+0];
ktmp[9] = kernel2[r*4+1];
ktmp[10] = kernel2[r*4+2];
ktmp[11] = kernel2[r*4+3];
ktmp[12] = kernel3[r*4+0];
ktmp[13] = kernel3[r*4+1];
ktmp[14] = kernel3[r*4+2];
ktmp[15] = kernel3[r*4+3];
ktmp[16] = kernel4[r*4+0];
ktmp[17] = kernel4[r*4+1];
ktmp[18] = kernel4[r*4+2];
ktmp[19] = kernel4[r*4+3];
ktmp[20] = kernel5[r*4+0];
ktmp[21] = kernel5[r*4+1];
ktmp[22] = kernel5[r*4+2];
ktmp[23] = kernel5[r*4+3];
ktmp[24] = kernel6[r*4+0];
ktmp[25] = kernel6[r*4+1];
ktmp[26] = kernel6[r*4+2];
ktmp[27] = kernel6[r*4+3];
ktmp[28] = kernel7[r*4+0];
ktmp[29] = kernel7[r*4+1];
ktmp[30] = kernel7[r*4+2];
ktmp[31] = kernel7[r*4+3];
ktmp += 32;
kernel0 += 16;
kernel1 += 16;
kernel2 += 16;
kernel3 += 16;
kernel4 += 16;
kernel5 += 16;
kernel6 += 16;
kernel7 += 16;
}
}
for (; p+3<outch; p+=4)
{
const short* kernel0 = (const short*)kernel_tm + (p+0)*inch*16;
const short* kernel1 = (const short*)kernel_tm + (p+1)*inch*16;
const short* kernel2 = (const short*)kernel_tm + (p+2)*inch*16;
const short* kernel3 = (const short*)kernel_tm + (p+3)*inch*16;
short* ktmp = kernel_tm_test.channel(p/8 + (p%8)/4);
for (int q=0; q<inch; q++)
{
ktmp[0] = kernel0[r*4+0];
ktmp[1] = kernel0[r*4+1];
ktmp[2] = kernel0[r*4+2];
ktmp[3] = kernel0[r*4+3];
ktmp[4] = kernel1[r*4+0];
ktmp[5] = kernel1[r*4+1];
ktmp[6] = kernel1[r*4+2];
ktmp[7] = kernel1[r*4+3];
ktmp[8] = kernel2[r*4+0];
ktmp[9] = kernel2[r*4+1];
ktmp[10] = kernel2[r*4+2];
ktmp[11] = kernel2[r*4+3];
ktmp[12] = kernel3[r*4+0];
ktmp[13] = kernel3[r*4+1];
ktmp[14] = kernel3[r*4+2];
ktmp[15] = kernel3[r*4+3];
ktmp += 16;
kernel0 += 16;
kernel1 += 16;
kernel2 += 16;
kernel3 += 16;
}
}
for (; p<outch; p++)
{
const short* kernel0 = (const short*)kernel_tm + p*inch*16;
short* ktmp = kernel_tm_test.channel(p/8 + (p%8)/4 + p%4);
for (int q=0; q<inch; q++)
{
ktmp[0] = kernel0[r*4+0];
ktmp[1] = kernel0[r*4+1];
ktmp[2] = kernel0[r*4+2];
ktmp[3] = kernel0[r*4+3];
ktmp += 4;
kernel0 += 16;
}
}
kernel_tm2.push_back(kernel_tm_test);
}
}
static void conv3x3s1_winograd23_int8_neon(const Mat& bottom_blob, Mat& top_blob, const std::vector<Mat> &kernel_tm_test, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
// pad to 2n+2, winograd F(2,3)
Mat bottom_blob_bordered = bottom_blob;
outw = (outw + 1) / 2 * 2;
outh = (outh + 1) / 2 * 2;
w = outw + 2;
h = outh + 2;
Option opt_b = opt;
opt_b.blob_allocator = opt.workspace_allocator;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt_b);
// BEGIN transform input
Mat bottom_blob_tm;
{
int w_tm = outw / 2 * 4;
int h_tm = outh / 2 * 4;
int nColBlocks = h_tm/4; // may be the block num in FeatherCNN
int nRowBlocks = w_tm/4;
const int tiles = nColBlocks * nRowBlocks;
bottom_blob_tm.create(4, inch, tiles*4, 2u, opt.workspace_allocator);
// BT
// const float itm[4][4] = {
// {1.0f, 0.0f, -1.0f, 0.0f},
// {0.0f, 1.0f, 1.00f, 0.0f},
// {0.0f, -1.0f, 1.00f, 0.0f},
// {0.0f, -1.0f, 0.00f, 1.0f}
// };
#pragma omp parallel for num_threads(opt.num_threads)
for (int q=0; q<inch; q++)
{
const signed char* img = bottom_blob_bordered.channel(q);
for (int j=0; j<nColBlocks; j++)
{
const signed char* r0 = img + w * j * 2;
const signed char* r1 = r0 + w;
const signed char* r2 = r1 + w;
const signed char* r3 = r2 + w;
for (int i = 0; i<nRowBlocks; i++)
{
short* out_tm0 = bottom_blob_tm.channel(tiles*0+j*nRowBlocks+i).row<short>(q);
short* out_tm1 = bottom_blob_tm.channel(tiles*1+j*nRowBlocks+i).row<short>(q);
short* out_tm2 = bottom_blob_tm.channel(tiles*2+j*nRowBlocks+i).row<short>(q);
short* out_tm3 = bottom_blob_tm.channel(tiles*3+j*nRowBlocks+i).row<short>(q);
#if __ARM_NEON
#if __aarch64__
asm volatile(
// load
"prfm pldl1keep, [%0, #64] \n"
"ld1 {v0.8b}, [%0] \n"
"prfm pldl1keep, [%1, #64] \n"
"ld1 {v1.8b}, [%1] \n"
"prfm pldl1keep, [%2, #64] \n"
"ld1 {v2.8b}, [%2] \n"
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v3.8b}, [%3] \n"
// w = B_t * d, trans int8 to int16
"ssubl v4.8h, v0.8b, v2.8b \n" // d4
"saddl v5.8h, v1.8b, v2.8b \n" // d6
"ssubl v6.8h, v2.8b, v1.8b \n" // d8
"ssubl v7.8h, v3.8b, v1.8b \n" // d10
// transpose w to w_t
"trn1 v8.4h, v4.4h, v5.4h \n"
"trn2 v9.4h, v4.4h, v5.4h \n"
"trn1 v10.4h, v6.4h, v7.4h \n"
"trn2 v11.4h, v6.4h, v7.4h \n"
"trn1 v0.2s, v8.2s, v10.2s \n"
"trn2 v2.2s, v8.2s, v10.2s \n"
"trn1 v1.2s, v9.2s, v11.2s \n"
"trn2 v3.2s, v9.2s, v11.2s \n"
// U = B_t * d_t
"sub v4.4h, v0.4h, v2.4h \n"
"add v5.4h, v1.4h, v2.4h \n"
"sub v6.4h, v2.4h, v1.4h \n"
"sub v7.4h, v3.4h, v1.4h \n"
// save
"st1 {v4.4h}, [%4] \n"
"st1 {v5.4h}, [%5] \n"
"st1 {v6.4h}, [%6] \n"
"st1 {v7.4h}, [%7] \n"
: "=r"(r0), // %0
"=r"(r1), // %1
"=r"(r2), // %2
"=r"(r3), // %3
"=r"(out_tm0), // %4
"=r"(out_tm1), // %5
"=r"(out_tm2), // %6
"=r"(out_tm3) // %7
: "0"(r0),
"1"(r1),
"2"(r2),
"3"(r3),
"4"(out_tm0),
"5"(out_tm1),
"6"(out_tm2),
"7"(out_tm3)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11"
);
#else
asm volatile(
// load
"pld [%0, #64] \n"
"vld1.s8 {d0}, [%0] \n"
"pld [%1, #64] \n"
"vld1.s8 {d1}, [%1] \n"
"pld [%2, #64] \n"
"vld1.s8 {d2}, [%2] \n"
"pld [%3, #64] \n"
"vld1.s8 {d3}, [%3] \n"
// w = B_t * d, trans int8 to int16
"vsubl.s8 q2, d0, d2 \n" // d4
"vaddl.s8 q3, d1, d2 \n" // d6
"vsubl.s8 q4, d2, d1 \n" // d8
"vsubl.s8 q5, d3, d1 \n" // d10
// transpose w to w_t
"vtrn.s16 d4, d6 \n"
"vtrn.s16 d8, d10 \n"
"vtrn.s32 d4, d8 \n"
"vtrn.s32 d6, d10 \n"
// U = B_t * d_t
"vsub.s16 d11, d4, d8 \n"
"vadd.s16 d12, d6, d8 \n"
"vsub.s16 d13, d8, d6 \n"
"vsub.s16 d14, d10, d6 \n"
// save
"vst1.s32 {d11}, [%4] \n"
"vst1.s32 {d12}, [%5] \n"
"vst1.s32 {d13}, [%6] \n"
"vst1.s32 {d14}, [%7] \n"
: "=r"(r0), // %0
"=r"(r1), // %1
"=r"(r2), // %2
"=r"(r3), // %3
"=r"(out_tm0), // %4
"=r"(out_tm1), // %5
"=r"(out_tm2), // %6
"=r"(out_tm3) // %7
: "0"(r0),
"1"(r1),
"2"(r2),
"3"(r3),
"4"(out_tm0),
"5"(out_tm1),
"6"(out_tm2),
"7"(out_tm3)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7"
);
#endif // __aarch64__
#else
short d0[4],d1[4],d2[4],d3[4];
short w0[4],w1[4],w2[4],w3[4];
short t0[4],t1[4],t2[4],t3[4];
// load
for (int n = 0; n < 4; n++)
{
d0[n] = r0[n];
d1[n] = r1[n];
d2[n] = r2[n];
d3[n] = r3[n];
}
// w = B_t * d
for (int n = 0; n < 4; n++)
{
w0[n] = d0[n] - d2[n];
w1[n] = d1[n] + d2[n];
w2[n] = d2[n] - d1[n];
w3[n] = d3[n] - d1[n];
}
// transpose d to d_t
{
t0[0]=w0[0]; t1[0]=w0[1]; t2[0]=w0[2]; t3[0]=w0[3];
t0[1]=w1[0]; t1[1]=w1[1]; t2[1]=w1[2]; t3[1]=w1[3];
t0[2]=w2[0]; t1[2]=w2[1]; t2[2]=w2[2]; t3[2]=w2[3];
t0[3]=w3[0]; t1[3]=w3[1]; t2[3]=w3[2]; t3[3]=w3[3];
}
// U = B_t * d_t
for (int n = 0; n < 4; n++)
{
d0[n] = t0[n] - t2[n];
d1[n] = t1[n] + t2[n];
d2[n] = t2[n] - t1[n];
d3[n] = t3[n] - t1[n];
}
// save to out_tm
for (int n = 0; n < 4; n++)
{
out_tm0[n] = d0[n];
out_tm1[n] = d1[n];
out_tm2[n] = d2[n];
out_tm3[n] = d3[n];
}
#endif
r0 += 2;
r1 += 2;
r2 += 2;
r3 += 2;
}
}
}
}
bottom_blob_bordered = Mat();
// BEGIN dot
Mat top_blob_tm;
{
int w_tm = outw / 2 * 4;
int h_tm = outh / 2 * 4;
int nColBlocks = h_tm/4; // may be the block num in FeatherCNN
int nRowBlocks = w_tm/4;
const int tiles = nColBlocks * nRowBlocks;
top_blob_tm.create(16, tiles, outch, 4u, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int r=0; r<4; r++)
{
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 8;
int* output0_tm = top_blob_tm.channel(p);
int* output1_tm = top_blob_tm.channel(p+1);
int* output2_tm = top_blob_tm.channel(p+2);
int* output3_tm = top_blob_tm.channel(p+3);
int* output4_tm = top_blob_tm.channel(p+4);
int* output5_tm = top_blob_tm.channel(p+5);
int* output6_tm = top_blob_tm.channel(p+6);
int* output7_tm = top_blob_tm.channel(p+7);
output0_tm = output0_tm + r*4;
output1_tm = output1_tm + r*4;
output2_tm = output2_tm + r*4;
output3_tm = output3_tm + r*4;
output4_tm = output4_tm + r*4;
output5_tm = output5_tm + r*4;
output6_tm = output6_tm + r*4;
output7_tm = output7_tm + r*4;
for (int i=0; i<tiles; i++)
{
const short* kptr = kernel_tm_test[r].channel(p/8);
const short* r0 = bottom_blob_tm.channel(tiles*r+i);
#if __ARM_NEON
#if __aarch64__
asm volatile(
// inch loop
"eor v0.16b, v0.16b, v0.16b \n"
"eor v1.16b, v1.16b, v1.16b \n"
"eor v2.16b, v2.16b, v2.16b \n"
"eor v3.16b, v3.16b, v3.16b \n"
"eor v4.16b, v4.16b, v4.16b \n"
"eor v5.16b, v5.16b, v5.16b \n"
"eor v6.16b, v6.16b, v6.16b \n"
"eor v7.16b, v7.16b, v7.16b \n"
"mov w4, %w20 \n"
"0: \n" // for (int q=0; q<inch; q++)
"prfm pldl1keep, [%9, #128] \n" // _r0 = vld1_s16(r0); // input inch0
"ld1 {v8.4h}, [%8] \n"
"ld1 {v9.4h, v10.4h}, [%9] \n" // _k0 = vld1q_s16(kptr);
"add %9, %9, #16 \n"
"ld1 {v11.4h, v12.4h}, [%9] \n" // _k0n = vld1q_s16(kptr+8);
"add %9, %9, #16 \n"
"ld1 {v13.4h, v14.4h}, [%9] \n" // _k1 = vld1q_s16(kptr+16);
"add %9, %9, #16 \n"
"ld1 {v15.4h, v16.4h}, [%9] \n" // _k1n = vld1q_s16(kptr+24);
"add %8, %8, #8 \n"
"add %9, %9, #16 \n"
"subs w4, w4, #1 \n"
"smlal v0.4s, v8.4h, v9.4h \n" // sum0 += (a00-a03) * (k00-k03)
"smlal v1.4s, v8.4h, v10.4h \n" // sum1 += (a00-a03) * (k10-k13)
"smlal v2.4s, v8.4h, v11.4h \n" // sum2 += (a00-a03) * (k20-k23)
"smlal v3.4s, v8.4h, v12.4h \n" // sum3 += (a00-a03) * (k30-k33)
"smlal v4.4s, v8.4h, v13.4h \n" // sum4 += (a00-a03) * (k40-k43)
"smlal v5.4s, v8.4h, v14.4h \n" // sum5 += (a00-a03) * (k50-k53)
"smlal v6.4s, v8.4h, v15.4h \n" // sum6 += (a00-a03) * (k60-k63)
"smlal v7.4s, v8.4h, v16.4h \n" // sum7 += (a00-a03) * (k70-k73)
"bne 0b \n" // end for
"st1 {v0.4s}, [%0] \n" // store the result to memory
"st1 {v1.4s}, [%1] \n" //
"st1 {v2.4s}, [%2] \n" //
"st1 {v3.4s}, [%3] \n" //
"st1 {v4.4s}, [%4] \n" //
"st1 {v5.4s}, [%5] \n" //
"st1 {v6.4s}, [%6] \n" //
"st1 {v7.4s}, [%7] \n" //
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(output4_tm), // %4
"=r"(output5_tm), // %5
"=r"(output6_tm), // %6
"=r"(output7_tm), // %7
"=r"(r0), // %8
"=r"(kptr) // %9
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(output4_tm),
"5"(output5_tm),
"6"(output6_tm),
"7"(output7_tm),
"8"(r0),
"9"(kptr),
"r"(inch) // %20
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16"
);
#else
asm volatile(
// inch loop
"vmov.s32 q0, #0 \n"
"vmov.s32 q1, #0 \n"
"vmov.s32 q2, #0 \n"
"vmov.s32 q3, #0 \n"
"vmov.s32 q4, #0 \n"
"vmov.s32 q5, #0 \n"
"vmov.s32 q6, #0 \n"
"vmov.s32 q7, #0 \n"
"mov r4, %20 \n"
"0: \n" // for (int q=0; q<inch; q++)
"vld1.s16 {d16}, [%8]! \n" // _r0 = vld1_s16(r0); // input inch0
"vld1.s16 {d18-d19}, [%9] \n" // _k0 = vld1q_s16(kptr);
"add %9, #16 \n"
"vld1.s16 {d20-d21}, [%9] \n" // _k0n = vld1q_s16(kptr+8);
"add %9, #16 \n"
"vld1.s16 {d22-d23}, [%9] \n" // _k1 = vld1q_s16(kptr+16);
"add %9, #16 \n"
"vld1.s16 {d24-d25}, [%9] \n" // _k1n = vld1q_s16(kptr+24);
"add %9, #16 \n"
"vmlal.s16 q0, d16, d18 \n" // sum0 += (a00-a03) * (k00-k03)
"vmlal.s16 q1, d16, d19 \n" // sum1 += (a00-a03) * (k10-k13)
"vmlal.s16 q2, d16, d20 \n" // sum2 += (a00-a03) * (k20-k23)
"vmlal.s16 q3, d16, d21 \n" // sum3 += (a00-a03) * (k30-k33)
"vmlal.s16 q4, d16, d22 \n" // sum4 += (a00-a03) * (k40-k43)
"vmlal.s16 q5, d16, d23 \n" // sum5 += (a00-a03) * (k50-k53)
"vmlal.s16 q6, d16, d24 \n" // sum6 += (a00-a03) * (k60-k63)
"vmlal.s16 q7, d16, d25 \n" // sum7 += (a00-a03) * (k70-k73)
"subs r4, r4, #1 \n"
"bne 0b \n" // end for
"vst1.s32 {d0-d1}, [%0] \n" // store the result to memory
"vst1.s32 {d2-d3}, [%1] \n"
"vst1.s32 {d4-d5}, [%2] \n"
"vst1.s32 {d6-d7}, [%3] \n"
"vst1.s32 {d8-d9}, [%4] \n"
"vst1.s32 {d10-d11}, [%5] \n"
"vst1.s32 {d12-d13}, [%6] \n"
"vst1.s32 {d14-d15}, [%7] \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(output4_tm), // %4
"=r"(output5_tm), // %5
"=r"(output6_tm), // %6
"=r"(output7_tm), // %7
"=r"(r0), // %8
"=r"(kptr) // %9
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(output4_tm),
"5"(output5_tm),
"6"(output6_tm),
"7"(output7_tm),
"8"(r0),
"9"(kptr),
"r"(inch) // %20
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12"
);
#endif // __aarch64__
#else
int sum0[4] = {0};
int sum1[4] = {0};
int sum2[4] = {0};
int sum3[4] = {0};
int sum4[4] = {0};
int sum5[4] = {0};
int sum6[4] = {0};
int sum7[4] = {0};
for (int q=0; q<inch; q++)
{
for (int n=0; n<4; n++)
{
sum0[n] += (int)r0[n] * kptr[n];
sum1[n] += (int)r0[n] * kptr[n+4];
sum2[n] += (int)r0[n] * kptr[n+8];
sum3[n] += (int)r0[n] * kptr[n+12];
sum4[n] += (int)r0[n] * kptr[n+16];
sum5[n] += (int)r0[n] * kptr[n+20];
sum6[n] += (int)r0[n] * kptr[n+24];
sum7[n] += (int)r0[n] * kptr[n+28];
}
kptr += 32;
r0 += 4;
}
for (int n=0; n<4; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
output4_tm[n] = sum4[n];
output5_tm[n] = sum5[n];
output6_tm[n] = sum6[n];
output7_tm[n] = sum7[n];
}
#endif // __ARM_NEON
output0_tm += 16;
output1_tm += 16;
output2_tm += 16;
output3_tm += 16;
output4_tm += 16;
output5_tm += 16;
output6_tm += 16;
output7_tm += 16;
}
}
nn_outch = (outch - remain_outch_start) >> 2;
for (int pp=0; pp<nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
int* output0_tm = top_blob_tm.channel(p);
int* output1_tm = top_blob_tm.channel(p+1);
int* output2_tm = top_blob_tm.channel(p+2);
int* output3_tm = top_blob_tm.channel(p+3);
output0_tm = output0_tm + r*4;
output1_tm = output1_tm + r*4;
output2_tm = output2_tm + r*4;
output3_tm = output3_tm + r*4;
for (int i=0; i<tiles; i++)
{
const short* kptr = kernel_tm_test[r].channel(p/8 + (p%8)/4);
const short* r0 = bottom_blob_tm.channel(tiles*r+i);
#if __ARM_NEON
#if __aarch64__
asm volatile(
// inch loop
"eor v0.16b, v0.16b, v0.16b \n"
"eor v1.16b, v1.16b, v1.16b \n"
"eor v2.16b, v2.16b, v2.16b \n"
"eor v3.16b, v3.16b, v3.16b \n"
"mov w4, %w12 \n"
"0: \n" // for (int q=0; q<inch; q++)
"prfm pldl1keep, [%5, #128] \n" // _r0 = vld1_s16(r0); // input inch0
"ld1 {v8.4h}, [%4] \n"
"ld1 {v9.4h, v10.4h}, [%5] \n" // _k0 = vld1q_s16(kptr);
"add %5, %5, #16 \n"
"ld1 {v11.4h, v12.4h}, [%5] \n" // _k0n = vld1q_s16(kptr+8);
"add %4, %4, #8 \n"
"add %5, %5, #16 \n"
"subs w4, w4, #1 \n"
"smlal v0.4s, v8.4h, v9.4h \n" // sum0 += (a00-a03) * (k00-k03)
"smlal v1.4s, v8.4h, v10.4h \n" // sum1 += (a00-a03) * (k10-k13)
"smlal v2.4s, v8.4h, v11.4h \n" // sum2 += (a00-a03) * (k20-k23)
"smlal v3.4s, v8.4h, v12.4h \n" // sum3 += (a00-a03) * (k30-k33)
"bne 0b \n" // end for
"st1 {v0.4s}, [%0] \n" // store the result to memory
"st1 {v1.4s}, [%1] \n" //
"st1 {v2.4s}, [%2] \n" //
"st1 {v3.4s}, [%3] \n" //
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(r0), // %4
"=r"(kptr) // %5
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(r0),
"5"(kptr),
"r"(inch) // %12
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12"
);
#else
asm volatile(
// inch loop
"vmov.s32 q0, #0 \n"
"vmov.s32 q1, #0 \n"
"vmov.s32 q2, #0 \n"
"vmov.s32 q3, #0 \n"
"mov r4, %12 \n"
"0: \n" // for (int q=0; q<inch; q++)
"vld1.s16 {d16}, [%4]! \n" // _r0 = vld1_s16(r0); // input inch0
"vld1.s16 {d18-d19}, [%5] \n" // _k0 = vld1q_s16(kptr);
"add %5, #16 \n"
"vld1.s16 {d20-d21}, [%5] \n" // _k0n = vld1q_s16(kptr+8);
"add %5, #16 \n"
"vmlal.s16 q0, d16, d18 \n" // sum0 += (a00-a03) * (k00-k03)
"vmlal.s16 q1, d16, d19 \n" // sum1 += (a00-a03) * (k10-k13)
"vmlal.s16 q2, d16, d20 \n" // sum2 += (a00-a03) * (k20-k23)
"vmlal.s16 q3, d16, d21 \n" // sum3 += (a00-a03) * (k30-k33)
"subs r4, r4, #1 \n"
"bne 0b \n" // end for
"vst1.s32 {d0-d1}, [%0] \n" // store the result to memory
"vst1.s32 {d2-d3}, [%1] \n"
"vst1.s32 {d4-d5}, [%2] \n"
"vst1.s32 {d6-d7}, [%3] \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(r0), // %4
"=r"(kptr) // %5
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(r0),
"5"(kptr),
"r"(inch) // %12
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q8", "q9", "q10"
);
#endif // __aarch64__
#else
int sum0[4] = {0};
int sum1[4] = {0};
int sum2[4] = {0};
int sum3[4] = {0};
for (int q=0; q<inch; q++)
{
for (int n=0; n<4; n++)
{
sum0[n] += (int)r0[n] * kptr[n];
sum1[n] += (int)r0[n] * kptr[n+4];
sum2[n] += (int)r0[n] * kptr[n+8];
sum3[n] += (int)r0[n] * kptr[n+12];
}
kptr += 16;
r0 += 4;
}
for (int n=0; n<4; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
}
#endif // __ARM_NEON
output0_tm += 16;
output1_tm += 16;
output2_tm += 16;
output3_tm += 16;
}
}
remain_outch_start += nn_outch << 2;
for (int p=remain_outch_start; p<outch; p++)
{
int* output0_tm = top_blob_tm.channel(p);
output0_tm = output0_tm + r*4;
for (int i=0; i<tiles; i++)
{
const short* kptr = kernel_tm_test[r].channel(p/8 + (p%8)/4 + p%4);
const short* r0 = bottom_blob_tm.channel(tiles*r+i);
#if __ARM_NEON
#if __aarch64__
asm volatile(
// inch loop
"eor v0.16b, v0.16b, v0.16b \n"
"mov w4, %w6 \n"
"0: \n" // for (int q=0; q<inch; q++)
//"prfm pldl1keep, [%2, #128] \n" // _r0 = vld1_s16(r0); // input inch0
"ld1 {v8.4h}, [%1] \n"
"ld1 {v9.4h}, [%2] \n" // _k0 = vld1q_s16(kptr);
"add %1, %1, #8 \n"
"add %2, %2, #8 \n"
"subs w4, w4, #1 \n"
"smlal v0.4s, v8.4h, v9.4h \n" // sum0 += (a00-a03) * (k00-k03)
"bne 0b \n" // end for
"st1 {v0.4s}, [%0] \n" // store the result to memory
: "=r"(output0_tm), // %0
"=r"(r0), // %1
"=r"(kptr) // %2
: "0"(output0_tm),
"1"(r0),
"2"(kptr),
"r"(inch) // %6
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9"
);
#else
asm volatile(
// inch loop
"vmov.s32 q0, #0 \n"
"mov r4, %6 \n"
"0: \n" // for (int q=0; q<inch; q++)
"vld1.s16 {d16}, [%1] \n" // _r0 = vld1_s16(r0); // input inch0
"add %1, #8 \n"
"vld1.s16 {d18}, [%2] \n" // _k0 = vld1q_s16(kptr);
"add %2, #8 \n"
"vmlal.s16 q0, d16, d18 \n" // sum0 += (a00-a03) * (k00-k03)
"subs r4, r4, #1 \n"
"bne 0b \n" // end for
"vst1.s32 {d0-d1}, [%0] \n" // store the result to memory
: "=r"(output0_tm), // %0
"=r"(r0), // %1
"=r"(kptr) // %2
: "0"(output0_tm),
"1"(r0),
"2"(kptr),
"r"(inch) // %6
: "cc", "memory", "r4", "q0", "q8", "q9"
);
#endif // __aarch64__
#else
int sum0[4] = {0};
for (int q=0; q<inch; q++)
{
for (int n=0; n<4; n++)
{
sum0[n] += (int)r0[n] * kptr[n];
}
kptr += 4;
r0 += 4;
}
for (int n=0; n<4; n++)
{
output0_tm[n] = sum0[n];
}
#endif
output0_tm += 16;
}
}
}
}
bottom_blob_tm = Mat();
// END dot
// BEGIN transform output
Mat top_blob_bordered;
top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator);
{
// AT
// const float itm[2][4] = {
// {1.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 1.0f}
// };
int w_tm = outw / 2 * 4;
int h_tm = outh / 2 * 4;
int nColBlocks = h_tm/4; // may be the block num in FeatherCNN
int nRowBlocks = w_tm/4;
#if __ARM_NEON
int32x2_t _shift = vdup_n_s32(-2);
#endif
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=0; p<outch; p++)
{
int* out_tile = top_blob_tm.channel(p);
int* outRow0 = top_blob_bordered.channel(p);
int* outRow1 = outRow0 + outw;
for (int j=0; j<nColBlocks; j++)
{
for(int i=0; i<nRowBlocks; i++)
{
#if __ARM_NEON
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n"
"add v0.4s, v0.4s, v1.4s \n" // s0 = s0 + s1 + s2;
"sub v1.4s, v1.4s, v2.4s \n"
"add v0.4s, v0.4s, v2.4s \n" // s1 = s1 - s2 + s3;
"add v1.4s, v1.4s, v3.4s \n"
"trn1 v4.4s, v0.4s, v1.4s \n"
"trn2 v5.4s, v0.4s, v1.4s \n"
"dup v6.2d, v4.d[1] \n"
"dup v7.2d, v5.d[1] \n"
"add v0.2s, v4.2s, v5.2s \n" // o0 = d0 + d1 + d2;
"sub v1.2s, v5.2s, v6.2s \n"
"add v0.2s, v0.2s, v6.2s \n" // o1 = d1 - d2 + d3;
"add v1.2s, v1.2s, v7.2s \n"
"sshl v0.2s, v0.2s, %6.2s \n" // o0 = o0 >> 2
"sshl v1.2s, v1.2s, %6.2s \n" // o1 = o1 >> 2
"st1 {v0.2s}, [%1], #8 \n"
"st1 {v1.2s}, [%2], #8 \n"
: "=r"(out_tile), // %0
"=r"(outRow0), // %1
"=r"(outRow1) // %2
: "0"(out_tile),
"1"(outRow0),
"2"(outRow1),
"w"(_shift) // %6
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7"
);
#else
asm volatile(
"pld [%0, #512] \n"
"vldm %0!, {d0-d7} \n"
"vaddq.s32 q0, q0, q1 \n" // s0 = s0 + s1 + s2;
"vsubq.s32 q1, q1, q2 \n"
"vaddq.s32 q0, q0, q2 \n" // s1 = s1 - s2 + s3;
"vaddq.s32 q1, q1, q3 \n"
"vtrn.s32 q0, q1 \n"
"vadd.s32 d8, d0, d2 \n" // o0 = d0 + d1 + d2;
"vsub.s32 d9, d2, d1 \n"
"vadd.s32 d8, d8, d1 \n" // o1 = d1 - d2 + d3;
"vadd.s32 d9, d9, d3 \n"
"vshl.s32 d8, d8, %P6 \n" // o0 = o0 >> 2
"vshl.s32 d9, d9, %P6 \n" // o1 = o1 >> 2
"vst1.s32 {d8}, [%1]! \n"
"vst1.s32 {d9}, [%2]! \n"
: "=r"(out_tile), // %0
"=r"(outRow0), // %1
"=r"(outRow1) // %2
: "0"(out_tile),
"1"(outRow0),
"2"(outRow1),
"w"(_shift) // %6
: "cc", "memory", "q0", "q1", "q2", "q3", "q4"
);
#endif // __aarch64__
#else
int s0[4],s1[4],s2[4],s3[4];
int w0[4],w1[4];
int d0[2],d1[2],d2[2],d3[2];
int o0[2],o1[2];
// load
for (int n = 0; n < 4; n++)
{
s0[n] = out_tile[n];
s1[n] = out_tile[n+ 4];
s2[n] = out_tile[n+ 8];
s3[n] = out_tile[n+12];
}
// w = A_T * W
for (int n = 0; n < 4; n++)
{
w0[n] = s0[n] + s1[n] + s2[n];
w1[n] = s1[n] - s2[n] + s3[n];
}
// transpose w to w_t
{
d0[0] = w0[0]; d0[1] = w1[0];
d1[0] = w0[1]; d1[1] = w1[1];
d2[0] = w0[2]; d2[1] = w1[2];
d3[0] = w0[3]; d3[1] = w1[3];
}
// Y = A_T * w_t
for (int n = 0; n < 2; n++)
{
o0[n] = d0[n] + d1[n] + d2[n];
o1[n] = d1[n] - d2[n] + d3[n];
}
// save to top blob tm,why right 2,because the G' = G*2
outRow0[0] = o0[0] >> 2;
outRow0[1] = o0[1] >> 2;
outRow1[0] = o1[0] >> 2;
outRow1[1] = o1[1] >> 2;
out_tile += 16;
outRow0 += 2;
outRow1 += 2;
#endif // __ARM_NEON
}
outRow0 += outw;
outRow1 += outw;
}
}
}
// END transform output
// cut result pad
copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt);
}
static void conv3x3s1_winograd43_transform_kernel_int8_neon(const Mat& kernel, std::vector<Mat> &kernel_tm2, int inch, int outch)
{
Mat kernel_tm(6*6, inch, outch, 2ul);
// G
// const float ktm[6][3] = {
// { 1.0f/4, 0.0f, 0.0f},
// { -1.0f/6, -1.0f/6, -1.0f/6},
// { -1.0f/6, 1.0f/6, -1.0f/6},
// { 1.0f/24, 1.0f/12, 1.0f/6},
// { 1.0f/24, -1.0f/12, 1.0f/6},
// { 0.0f, 0.0f, 1.0f}
// };
const short ktm[6][3] = {
{ 6, 0, 0},
{ -4, -4, -4},
{ -4, 4, -4},
{ 1, 2, 4},
{ 1, -2, 4},
{ 0, 0, 6}
};
#pragma omp parallel for
for (int p = 0; p<outch; p++)
{
for (int q = 0; q<inch; q++)
{
const signed char* kernel0 = (const signed char*)kernel + p*inch * 9 + q * 9;
short* kernel_tm0 = kernel_tm.channel(p).row<short>(q);
// transform kernel
const signed char* k0 = kernel0;
const signed char* k1 = kernel0 + 3;
const signed char* k2 = kernel0 + 6;
// h
short tmp[6][3];
for (int i=0; i<6; 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];
}
// U
for (int j=0; j<6; j++)
{
short* tmpp = &tmp[j][0];
for (int i=0; i<6; i++)
{
kernel_tm0[j*6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
for (int r=0; r<9; r++)
{
Mat kernel_tm_test(4*8, inch, outch/8 + (outch%8)/4 + outch%4, 2u);
int p = 0;
for (; p+7<outch; p+=8)
{
const short* kernel0 = (const short*)kernel_tm.channel(p);
const short* kernel1 = (const short*)kernel_tm.channel(p+1);
const short* kernel2 = (const short*)kernel_tm.channel(p+2);
const short* kernel3 = (const short*)kernel_tm.channel(p+3);
const short* kernel4 = (const short*)kernel_tm.channel(p+4);
const short* kernel5 = (const short*)kernel_tm.channel(p+5);
const short* kernel6 = (const short*)kernel_tm.channel(p+6);
const short* kernel7 = (const short*)kernel_tm.channel(p+7);
short* ktmp = kernel_tm_test.channel(p/8);
for (int q=0; q<inch; q++)
{
ktmp[0] = kernel0[r*4+0];
ktmp[1] = kernel0[r*4+1];
ktmp[2] = kernel0[r*4+2];
ktmp[3] = kernel0[r*4+3];
ktmp[4] = kernel1[r*4+0];
ktmp[5] = kernel1[r*4+1];
ktmp[6] = kernel1[r*4+2];
ktmp[7] = kernel1[r*4+3];
ktmp[8] = kernel2[r*4+0];
ktmp[9] = kernel2[r*4+1];
ktmp[10] = kernel2[r*4+2];
ktmp[11] = kernel2[r*4+3];
ktmp[12] = kernel3[r*4+0];
ktmp[13] = kernel3[r*4+1];
ktmp[14] = kernel3[r*4+2];
ktmp[15] = kernel3[r*4+3];
ktmp[16] = kernel4[r*4+0];
ktmp[17] = kernel4[r*4+1];
ktmp[18] = kernel4[r*4+2];
ktmp[19] = kernel4[r*4+3];
ktmp[20] = kernel5[r*4+0];
ktmp[21] = kernel5[r*4+1];
ktmp[22] = kernel5[r*4+2];
ktmp[23] = kernel5[r*4+3];
ktmp[24] = kernel6[r*4+0];
ktmp[25] = kernel6[r*4+1];
ktmp[26] = kernel6[r*4+2];
ktmp[27] = kernel6[r*4+3];
ktmp[28] = kernel7[r*4+0];
ktmp[29] = kernel7[r*4+1];
ktmp[30] = kernel7[r*4+2];
ktmp[31] = kernel7[r*4+3];
ktmp += 32;
kernel0 += 36;
kernel1 += 36;
kernel2 += 36;
kernel3 += 36;
kernel4 += 36;
kernel5 += 36;
kernel6 += 36;
kernel7 += 36;
}
}
for (; p+3<outch; p+=4)
{
const short* kernel0 = (const short*)kernel_tm.channel(p);
const short* kernel1 = (const short*)kernel_tm.channel(p+1);
const short* kernel2 = (const short*)kernel_tm.channel(p+2);
const short* kernel3 = (const short*)kernel_tm.channel(p+3);
short* ktmp = kernel_tm_test.channel(p/8 + (p%8)/4);
for (int q=0; q<inch; q++)
{
ktmp[0] = kernel0[r*4+0];
ktmp[1] = kernel0[r*4+1];
ktmp[2] = kernel0[r*4+2];
ktmp[3] = kernel0[r*4+3];
ktmp[4] = kernel1[r*4+0];
ktmp[5] = kernel1[r*4+1];
ktmp[6] = kernel1[r*4+2];
ktmp[7] = kernel1[r*4+3];
ktmp[8] = kernel2[r*4+0];
ktmp[9] = kernel2[r*4+1];
ktmp[10] = kernel2[r*4+2];
ktmp[11] = kernel2[r*4+3];
ktmp[12] = kernel3[r*4+0];
ktmp[13] = kernel3[r*4+1];
ktmp[14] = kernel3[r*4+2];
ktmp[15] = kernel3[r*4+3];
ktmp += 16;
kernel0 += 36;
kernel1 += 36;
kernel2 += 36;
kernel3 += 36;
}
}
for (; p<outch; p++)
{
const short* kernel0 = (const short*)kernel_tm.channel(p);
short* ktmp = kernel_tm_test.channel(p/8 + (p%8)/4 + p%4);
for (int q=0; q<inch; q++)
{
ktmp[0] = kernel0[r*4+0];
ktmp[1] = kernel0[r*4+1];
ktmp[2] = kernel0[r*4+2];
ktmp[3] = kernel0[r*4+3];
ktmp += 4;
kernel0 += 36;
}
}
kernel_tm2.push_back(kernel_tm_test);
}
}
static void conv3x3s1_winograd43_int8_neon(const Mat& bottom_blob, Mat& top_blob, const std::vector<Mat> &kernel_tm_test, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
// pad to 4n+2, winograd F(4,3)
Mat bottom_blob_bordered = bottom_blob;
outw = (outw + 3) / 4 * 4;
outh = (outh + 3) / 4 * 4;
w = outw + 2;
h = outh + 2;
Option opt_b = opt;
opt_b.blob_allocator = opt.workspace_allocator;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt_b);
// BEGIN transform input
Mat bottom_blob_tm;
{
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
int nColBlocks = h_tm/6; // may be the block num in Feathercnn
int nRowBlocks = w_tm/6;
const int tiles = nColBlocks * nRowBlocks;
bottom_blob_tm.create(4, inch, tiles*9, 2u, opt.workspace_allocator);
// BT
// const float itm[4][4] = {
// {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f},
// {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f},
// {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f},
// {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f}
// };
// 0 = 4 * r00 - 5 * r02 + r04
// 1 = -4 * (r01 + r02) + r03 + r04
// 2 = 4 * (r01 - r02) - r03 + r04
// 3 = -2 * r01 - r02 + 2 * r03 + r04
// 4 = 2 * r01 - r02 - 2 * r03 + r04
// 5 = 4 * r01 - 5 * r03 + r05
#pragma omp parallel for num_threads(opt.num_threads)
for (int q=0; q<inch; q++)
{
const signed char* img = bottom_blob_bordered.channel(q);
for (int j = 0; j < nColBlocks; j++)
{
const signed char* r0 = img + w * j * 4;
const signed char* r1 = r0 + w;
const signed char* r2 = r1 + w;
const signed char* r3 = r2 + w;
const signed char* r4 = r3 + w;
const signed char* r5 = r4 + w;
for (int i = 0; i < nRowBlocks; i++)
{
short* out_tm0 = bottom_blob_tm.channel(tiles*0+j*nRowBlocks+i).row<short>(q);
short* out_tm1 = bottom_blob_tm.channel(tiles*1+j*nRowBlocks+i).row<short>(q);
short* out_tm2 = bottom_blob_tm.channel(tiles*2+j*nRowBlocks+i).row<short>(q);
short* out_tm3 = bottom_blob_tm.channel(tiles*3+j*nRowBlocks+i).row<short>(q);
short* out_tm4 = bottom_blob_tm.channel(tiles*4+j*nRowBlocks+i).row<short>(q);
short* out_tm5 = bottom_blob_tm.channel(tiles*5+j*nRowBlocks+i).row<short>(q);
short* out_tm6 = bottom_blob_tm.channel(tiles*6+j*nRowBlocks+i).row<short>(q);
short* out_tm7 = bottom_blob_tm.channel(tiles*7+j*nRowBlocks+i).row<short>(q);
short* out_tm8 = bottom_blob_tm.channel(tiles*8+j*nRowBlocks+i).row<short>(q);
#if __ARM_NEON
int8x8_t _d0, _d1, _d2, _d3, _d4, _d5;
int16x8_t _w0, _w1, _w2, _w3, _w4, _w5;
int16x8_t _t0, _t1, _t2, _t3, _t4, _t5;
int16x8_t _n0, _n1, _n2, _n3, _n4, _n5;
// load
_d0 = vld1_s8(r0);
_d1 = vld1_s8(r1);
_d2 = vld1_s8(r2);
_d3 = vld1_s8(r3);
_d4 = vld1_s8(r4);
_d5 = vld1_s8(r5);
int8x8_t _1_n = vdup_n_s8(-1);
int8x8_t _2_p = vdup_n_s8(2);
int8x8_t _2_n = vdup_n_s8(-2);
int8x8_t _4_p = vdup_n_s8(4);
int8x8_t _4_n = vdup_n_s8(-4);
int8x8_t _5_n = vdup_n_s8(-5);
int16x8_t _1_n_s16 = vdupq_n_s16(-1);
int16x8_t _2_p_s16 = vdupq_n_s16(2);
int16x8_t _2_n_s16 = vdupq_n_s16(-2);
int16x8_t _4_p_s16 = vdupq_n_s16(4);
int16x8_t _4_n_s16 = vdupq_n_s16(-4);
int16x8_t _5_n_s16 = vdupq_n_s16(-5);
// w = B_t * d
_w0 = vmull_s8(_d0, _4_p);
_w0 = vmlal_s8(_w0, _d2, _5_n);
_w0 = vaddw_s8(_w0, _d4);
_w1 = vmull_s8(_d1, _4_n);
_w1 = vmlal_s8(_w1, _d2, _4_n);
_w1 = vaddw_s8(_w1, _d3);
_w1 = vaddw_s8(_w1, _d4);
_w2 = vmull_s8(_d1, _4_p);
_w2 = vmlal_s8(_w2, _d2, _4_n);
_w2 = vmlal_s8(_w2, _d3, _1_n);
_w2 = vaddw_s8(_w2, _d4);
_w3 = vmull_s8(_d1, _2_n);
_w3 = vmlal_s8(_w3, _d2, _1_n);
_w3 = vmlal_s8(_w3, _d3, _2_p);
_w3 = vaddw_s8(_w3, _d4);
_w4 = vmull_s8(_d1, _2_p);
_w4 = vmlal_s8(_w4, _d2, _1_n);
_w4 = vmlal_s8(_w4, _d3, _2_n);
_w4 = vaddw_s8(_w4, _d4);
_w5 = vmull_s8(_d1, _4_p);
_w5 = vmlal_s8(_w5, _d3, _5_n);
_w5 = vaddw_s8(_w5, _d5);
// transpose d to d_t
{
_t0[0]=_w0[0]; _t1[0]=_w0[1]; _t2[0]=_w0[2]; _t3[0]=_w0[3]; _t4[0]=_w0[4]; _t5[0]=_w0[5];
_t0[1]=_w1[0]; _t1[1]=_w1[1]; _t2[1]=_w1[2]; _t3[1]=_w1[3]; _t4[1]=_w1[4]; _t5[1]=_w1[5];
_t0[2]=_w2[0]; _t1[2]=_w2[1]; _t2[2]=_w2[2]; _t3[2]=_w2[3]; _t4[2]=_w2[4]; _t5[2]=_w2[5];
_t0[3]=_w3[0]; _t1[3]=_w3[1]; _t2[3]=_w3[2]; _t3[3]=_w3[3]; _t4[3]=_w3[4]; _t5[3]=_w3[5];
_t0[4]=_w4[0]; _t1[4]=_w4[1]; _t2[4]=_w4[2]; _t3[4]=_w4[3]; _t4[4]=_w4[4]; _t5[4]=_w4[5];
_t0[5]=_w5[0]; _t1[5]=_w5[1]; _t2[5]=_w5[2]; _t3[5]=_w5[3]; _t4[5]=_w5[4]; _t5[5]=_w5[5];
}
// d = B_t * d_t
_n0 = vmulq_s16(_t0, _4_p_s16);
_n0 = vmlaq_s16(_n0, _t2, _5_n_s16);
_n0 = vaddq_s16(_n0, _t4);
_n1 = vmulq_s16(_t1, _4_n_s16);
_n1 = vmlaq_s16(_n1, _t2, _4_n_s16);
_n1 = vaddq_s16(_n1, _t3);
_n1 = vaddq_s16(_n1, _t4);
_n2 = vmulq_s16(_t1, _4_p_s16);
_n2 = vmlaq_s16(_n2, _t2, _4_n_s16);
_n2 = vmlaq_s16(_n2, _t3, _1_n_s16);
_n2 = vaddq_s16(_n2, _t4);
_n3 = vmulq_s16(_t1, _2_n_s16);
_n3 = vmlaq_s16(_n3, _t2, _1_n_s16);
_n3 = vmlaq_s16(_n3, _t3, _2_p_s16);
_n3 = vaddq_s16(_n3, _t4);
_n4 = vmulq_s16(_t1, _2_p_s16);
_n4 = vmlaq_s16(_n4, _t2, _1_n_s16);
_n4 = vmlaq_s16(_n4, _t3, _2_n_s16);
_n4 = vaddq_s16(_n4, _t4);
_n5 = vmulq_s16(_t1, _4_p_s16);
_n5 = vmlaq_s16(_n5, _t3, _5_n_s16);
_n5 = vaddq_s16(_n5, _t5);
// save to out_tm
out_tm0[0]=_n0[0];out_tm0[1]=_n0[1];out_tm0[2]=_n0[2];out_tm0[3]=_n0[3];
out_tm1[0]=_n0[4];out_tm1[1]=_n0[5];out_tm1[2]=_n1[0];out_tm1[3]=_n1[1];
out_tm2[0]=_n1[2];out_tm2[1]=_n1[3];out_tm2[2]=_n1[4];out_tm2[3]=_n1[5];
out_tm3[0]=_n2[0];out_tm3[1]=_n2[1];out_tm3[2]=_n2[2];out_tm3[3]=_n2[3];
out_tm4[0]=_n2[4];out_tm4[1]=_n2[5];out_tm4[2]=_n3[0];out_tm4[3]=_n3[1];
out_tm5[0]=_n3[2];out_tm5[1]=_n3[3];out_tm5[2]=_n3[4];out_tm5[3]=_n3[5];
out_tm6[0]=_n4[0];out_tm6[1]=_n4[1];out_tm6[2]=_n4[2];out_tm6[3]=_n4[3];
out_tm7[0]=_n4[4];out_tm7[1]=_n4[5];out_tm7[2]=_n5[0];out_tm7[3]=_n5[1];
out_tm8[0]=_n5[2];out_tm8[1]=_n5[3];out_tm8[2]=_n5[4];out_tm8[3]=_n5[5];
#else
short d0[6],d1[6],d2[6],d3[6],d4[6],d5[6];
short w0[6],w1[6],w2[6],w3[6],w4[6],w5[6];
short t0[6],t1[6],t2[6],t3[6],t4[6],t5[6];
// load
for (int n = 0; n < 6; n++)
{
d0[n] = r0[n];
d1[n] = r1[n];
d2[n] = r2[n];
d3[n] = r3[n];
d4[n] = r4[n];
d5[n] = r5[n];
}
// w = B_t * d
for (int n = 0; n < 6; n++)
{
w0[n] = 4*d0[n] - 5*d2[n] + d4[n];
w1[n] = -4*d1[n] - 4*d2[n] + d3[n] + d4[n];
w2[n] = 4*d1[n] - 4*d2[n] - d3[n] + d4[n];
w3[n] = -2*d1[n] - d2[n] + 2*d3[n] + d4[n];
w4[n] = 2*d1[n] - d2[n] - 2*d3[n] + d4[n];
w5[n] = 4*d1[n] - 5*d3[n] + d5[n];
}
// transpose d to d_t
{
t0[0]=w0[0]; t1[0]=w0[1]; t2[0]=w0[2]; t3[0]=w0[3]; t4[0]=w0[4]; t5[0]=w0[5];
t0[1]=w1[0]; t1[1]=w1[1]; t2[1]=w1[2]; t3[1]=w1[3]; t4[1]=w1[4]; t5[1]=w1[5];
t0[2]=w2[0]; t1[2]=w2[1]; t2[2]=w2[2]; t3[2]=w2[3]; t4[2]=w2[4]; t5[2]=w2[5];
t0[3]=w3[0]; t1[3]=w3[1]; t2[3]=w3[2]; t3[3]=w3[3]; t4[3]=w3[4]; t5[3]=w3[5];
t0[4]=w4[0]; t1[4]=w4[1]; t2[4]=w4[2]; t3[4]=w4[3]; t4[4]=w4[4]; t5[4]=w4[5];
t0[5]=w5[0]; t1[5]=w5[1]; t2[5]=w5[2]; t3[5]=w5[3]; t4[5]=w5[4]; t5[5]=w5[5];
}
// d = B_t * d_t
for (int n = 0; n < 6; n++)
{
d0[n] = 4*t0[n] - 5*t2[n] + t4[n];
d1[n] = - 4*t1[n] - 4*t2[n] + t3[n] + t4[n];
d2[n] = 4*t1[n] - 4*t2[n] - t3[n] + t4[n];
d3[n] = - 2*t1[n] - t2[n] + 2*t3[n] + t4[n];
d4[n] = 2*t1[n] - t2[n] - 2*t3[n] + t4[n];
d5[n] = 4*t1[n] - 5*t3[n] + t5[n];
}
// save to out_tm
{
out_tm0[0]=d0[0];out_tm0[1]=d0[1];out_tm0[2]=d0[2];out_tm0[3]=d0[3];
out_tm1[0]=d0[4];out_tm1[1]=d0[5];out_tm1[2]=d1[0];out_tm1[3]=d1[1];
out_tm2[0]=d1[2];out_tm2[1]=d1[3];out_tm2[2]=d1[4];out_tm2[3]=d1[5];
out_tm3[0]=d2[0];out_tm3[1]=d2[1];out_tm3[2]=d2[2];out_tm3[3]=d2[3];
out_tm4[0]=d2[4];out_tm4[1]=d2[5];out_tm4[2]=d3[0];out_tm4[3]=d3[1];
out_tm5[0]=d3[2];out_tm5[1]=d3[3];out_tm5[2]=d3[4];out_tm5[3]=d3[5];
out_tm6[0]=d4[0];out_tm6[1]=d4[1];out_tm6[2]=d4[2];out_tm6[3]=d4[3];
out_tm7[0]=d4[4];out_tm7[1]=d4[5];out_tm7[2]=d5[0];out_tm7[3]=d5[1];
out_tm8[0]=d5[2];out_tm8[1]=d5[3];out_tm8[2]=d5[4];out_tm8[3]=d5[5];
}
#endif // __ARM_NEON
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
r4 += 4;
r5 += 4;
}
}
}
}
bottom_blob_bordered = Mat();
// BEGIN dot
Mat top_blob_tm;
{
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
int nColBlocks = h_tm/6; // may be the block num in Feathercnn
int nRowBlocks = w_tm/6;
const int tiles = nColBlocks * nRowBlocks;
top_blob_tm.create(36, tiles, outch, 4u, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int r=0; r<9; r++)
{
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 8;
int* output0_tm = top_blob_tm.channel(p);
int* output1_tm = top_blob_tm.channel(p+1);
int* output2_tm = top_blob_tm.channel(p+2);
int* output3_tm = top_blob_tm.channel(p+3);
int* output4_tm = top_blob_tm.channel(p+4);
int* output5_tm = top_blob_tm.channel(p+5);
int* output6_tm = top_blob_tm.channel(p+6);
int* output7_tm = top_blob_tm.channel(p+7);
output0_tm = output0_tm + r*4;
output1_tm = output1_tm + r*4;
output2_tm = output2_tm + r*4;
output3_tm = output3_tm + r*4;
output4_tm = output4_tm + r*4;
output5_tm = output5_tm + r*4;
output6_tm = output6_tm + r*4;
output7_tm = output7_tm + r*4;
for (int i=0; i<tiles; i++)
{
const short* kptr = kernel_tm_test[r].channel(p/8);
const short* r0 = bottom_blob_tm.channel(tiles*r+i);
#if __ARM_NEON
#if __aarch64__
asm volatile(
// inch loop
"eor v0.16b, v0.16b, v0.16b \n"
"eor v1.16b, v1.16b, v1.16b \n"
"eor v2.16b, v2.16b, v2.16b \n"
"eor v3.16b, v3.16b, v3.16b \n"
"eor v4.16b, v4.16b, v4.16b \n"
"eor v5.16b, v5.16b, v5.16b \n"
"eor v6.16b, v6.16b, v6.16b \n"
"eor v7.16b, v7.16b, v7.16b \n"
"mov w4, %w20 \n"
"0: \n" // for (int q=0; q<inch; q++)
"prfm pldl1keep, [%9, #128] \n" // _r0 = vld1_s16(r0);
"ld1 {v8.4h}, [%8] \n"
"ld1 {v9.4h, v10.4h}, [%9] \n" // _k01 = vld1q_s16(kptr);
"add %9, %9, #16 \n"
"ld1 {v11.4h, v12.4h}, [%9] \n" // _k23 = vld1q_s16(kptr+8);
"add %9, %9, #16 \n"
"ld1 {v13.4h, v14.4h}, [%9] \n" // _k45 = vld1q_s16(kptr+16);
"add %9, %9, #16 \n"
"ld1 {v15.4h, v16.4h}, [%9] \n" // _k67 = vld1q_s16(kptr+24);
"add %8, %8, #8 \n"
"add %9, %9, #16 \n"
"subs w4, w4, #1 \n"
"smlal v0.4s, v8.4h, v9.4h \n" // sum0 += (a00-a03) * (k00-k03)
"smlal v1.4s, v8.4h, v10.4h \n" // sum1 += (a00-a03) * (k10-k13)
"smlal v2.4s, v8.4h, v11.4h \n" // sum2 += (a00-a03) * (k20-k23)
"smlal v3.4s, v8.4h, v12.4h \n" // sum3 += (a00-a03) * (k30-k33)
"smlal v4.4s, v8.4h, v13.4h \n" // sum4 += (a00-a03) * (k40-k43)
"smlal v5.4s, v8.4h, v14.4h \n" // sum5 += (a00-a03) * (k50-k53)
"smlal v6.4s, v8.4h, v15.4h \n" // sum6 += (a00-a03) * (k60-k63)
"smlal v7.4s, v8.4h, v16.4h \n" // sum7 += (a00-a03) * (k70-k73)
"bne 0b \n" // end for
"st1 {v0.4s}, [%0] \n" // store the result to memory
"st1 {v1.4s}, [%1] \n" //
"st1 {v2.4s}, [%2] \n" //
"st1 {v3.4s}, [%3] \n" //
"st1 {v4.4s}, [%4] \n" //
"st1 {v5.4s}, [%5] \n" //
"st1 {v6.4s}, [%6] \n" //
"st1 {v7.4s}, [%7] \n" //
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(output4_tm), // %4
"=r"(output5_tm), // %5
"=r"(output6_tm), // %6
"=r"(output7_tm), // %7
"=r"(r0), // %8
"=r"(kptr) // %9
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(output4_tm),
"5"(output5_tm),
"6"(output6_tm),
"7"(output7_tm),
"8"(r0),
"9"(kptr),
"r"(inch) // %20
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16"
);
#else
asm volatile(
// inch loop
"vmov.s32 q0, #0 \n"
"vmov.s32 q1, #0 \n"
"vmov.s32 q2, #0 \n"
"vmov.s32 q3, #0 \n"
"vmov.s32 q4, #0 \n"
"vmov.s32 q5, #0 \n"
"vmov.s32 q6, #0 \n"
"vmov.s32 q7, #0 \n"
"mov r4, %20 \n"
"0: \n" // for (int q=0; q<inch; q++)
"vld1.s16 {d16}, [%8]! \n" // _r0 = vld1_s16(r0); // input inch0
"vld1.s16 {d18-d19}, [%9] \n" // _k01 = vld1q_s16(kptr);
"add %9, #16 \n"
"vld1.s16 {d20-d21}, [%9] \n" // _k23 = vld1q_s16(kptr+8);
"add %9, #16 \n"
"vld1.s16 {d22-d23}, [%9] \n" // _k45 = vld1q_s16(kptr+16);
"add %9, #16 \n"
"vld1.s16 {d24-d25}, [%9] \n" // _k67 = vld1q_s16(kptr+24);
"add %9, #16 \n"
"vmlal.s16 q0, d16, d18 \n" // sum0 += (a00-a03) * (k00-k03)
"vmlal.s16 q1, d16, d19 \n" // sum1 += (a00-a03) * (k10-k13)
"vmlal.s16 q2, d16, d20 \n" // sum2 += (a00-a03) * (k20-k23)
"vmlal.s16 q3, d16, d21 \n" // sum3 += (a00-a03) * (k30-k33)
"vmlal.s16 q4, d16, d22 \n" // sum4 += (a00-a03) * (k40-k43)
"vmlal.s16 q5, d16, d23 \n" // sum5 += (a00-a03) * (k50-k53)
"vmlal.s16 q6, d16, d24 \n" // sum6 += (a00-a03) * (k60-k63)
"vmlal.s16 q7, d16, d25 \n" // sum7 += (a00-a03) * (k70-k73)
"subs r4, r4, #1 \n"
"bne 0b \n" // end for
"vst1.s32 {d0-d1}, [%0] \n" // store the result to memory
"vst1.s32 {d2-d3}, [%1] \n"
"vst1.s32 {d4-d5}, [%2] \n"
"vst1.s32 {d6-d7}, [%3] \n"
"vst1.s32 {d8-d9}, [%4] \n"
"vst1.s32 {d10-d11}, [%5] \n"
"vst1.s32 {d12-d13}, [%6] \n"
"vst1.s32 {d14-d15}, [%7] \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(output4_tm), // %4
"=r"(output5_tm), // %5
"=r"(output6_tm), // %6
"=r"(output7_tm), // %7
"=r"(r0), // %8
"=r"(kptr) // %9
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(output4_tm),
"5"(output5_tm),
"6"(output6_tm),
"7"(output7_tm),
"8"(r0),
"9"(kptr),
"r"(inch) // %20
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12"
);
#endif // __aarch64__
#else
int sum0[4] = {0};
int sum1[4] = {0};
int sum2[4] = {0};
int sum3[4] = {0};
int sum4[4] = {0};
int sum5[4] = {0};
int sum6[4] = {0};
int sum7[4] = {0};
for (int q=0; q<inch; q++)
{
for (int n=0; n<4; n++)
{
sum0[n] += (int)r0[n] * kptr[n];
sum1[n] += (int)r0[n] * kptr[n+4];
sum2[n] += (int)r0[n] * kptr[n+8];
sum3[n] += (int)r0[n] * kptr[n+12];
sum4[n] += (int)r0[n] * kptr[n+16];
sum5[n] += (int)r0[n] * kptr[n+20];
sum6[n] += (int)r0[n] * kptr[n+24];
sum7[n] += (int)r0[n] * kptr[n+28];
}
kptr += 32;
r0 += 4;
}
for (int n=0; n<4; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
output4_tm[n] = sum4[n];
output5_tm[n] = sum5[n];
output6_tm[n] = sum6[n];
output7_tm[n] = sum7[n];
}
#endif // __ARM_NEON
output0_tm += 36;
output1_tm += 36;
output2_tm += 36;
output3_tm += 36;
output4_tm += 36;
output5_tm += 36;
output6_tm += 36;
output7_tm += 36;
}
}
nn_outch = (outch - remain_outch_start) >> 2;
for (int pp=0; pp<nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
int* output0_tm = top_blob_tm.channel(p);
int* output1_tm = top_blob_tm.channel(p+1);
int* output2_tm = top_blob_tm.channel(p+2);
int* output3_tm = top_blob_tm.channel(p+3);
output0_tm = output0_tm + r*4;
output1_tm = output1_tm + r*4;
output2_tm = output2_tm + r*4;
output3_tm = output3_tm + r*4;
for (int i=0; i<tiles; i++)
{
const short* kptr = kernel_tm_test[r].channel(p/8 + (p%8)/4);
const short* r0 = bottom_blob_tm.channel(tiles*r+i);
#if __ARM_NEON
#if __aarch64__
asm volatile(
// inch loop
"eor v0.16b, v0.16b, v0.16b \n"
"eor v1.16b, v1.16b, v1.16b \n"
"eor v2.16b, v2.16b, v2.16b \n"
"eor v3.16b, v3.16b, v3.16b \n"
"mov w4, %w12 \n"
"0: \n" // for (int q=0; q<inch; q++)
"prfm pldl1keep, [%5, #128] \n" // _r0 = vld1_s16(r0); // input inch0
"ld1 {v8.4h}, [%4] \n"
"ld1 {v9.4h, v10.4h}, [%5] \n" // _k01 = vld1q_s16(kptr);
"add %5, %5, #16 \n"
"ld1 {v11.4h, v12.4h}, [%5] \n" // _k23 = vld1q_s16(kptr+8);
"add %4, %4, #8 \n"
"add %5, %5, #16 \n"
"subs w4, w4, #1 \n"
"smlal v0.4s, v8.4h, v9.4h \n" // sum0 += (a00-a03) * (k00-k03)
"smlal v1.4s, v8.4h, v10.4h \n" // sum1 += (a00-a03) * (k10-k13)
"smlal v2.4s, v8.4h, v11.4h \n" // sum2 += (a00-a03) * (k20-k23)
"smlal v3.4s, v8.4h, v12.4h \n" // sum3 += (a00-a03) * (k30-k33)
"bne 0b \n" // end for
"st1 {v0.4s}, [%0] \n" // store the result to memory
"st1 {v1.4s}, [%1] \n" //
"st1 {v2.4s}, [%2] \n" //
"st1 {v3.4s}, [%3] \n" //
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(r0), // %4
"=r"(kptr) // %5
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(r0),
"5"(kptr),
"r"(inch) // %12
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12"
);
#else
asm volatile(
// inch loop
"vmov.s32 q0, #0 \n"
"vmov.s32 q1, #0 \n"
"vmov.s32 q2, #0 \n"
"vmov.s32 q3, #0 \n"
"mov r4, %12 \n"
"0: \n" // for (int q=0; q<inch; q++)
"vld1.s16 {d16}, [%4]! \n" // _r0 = vld1_s16(r0); // input inch0
"vld1.s16 {d18-d19}, [%5] \n" // _k01 = vld1q_s16(kptr);
"add %5, #16 \n"
"vld1.s16 {d20-d21}, [%5] \n" // _k23 = vld1q_s16(kptr+8);
"add %5, #16 \n"
"vmlal.s16 q0, d16, d18 \n" // sum0 += (a00-a03) * (k00-k03)
"vmlal.s16 q1, d16, d19 \n" // sum1 += (a00-a03) * (k10-k13)
"vmlal.s16 q2, d16, d20 \n" // sum2 += (a00-a03) * (k20-k23)
"vmlal.s16 q3, d16, d21 \n" // sum3 += (a00-a03) * (k30-k33)
"subs r4, r4, #1 \n"
"bne 0b \n" // end for
"vst1.s32 {d0-d1}, [%0] \n" // store the result to memory
"vst1.s32 {d2-d3}, [%1] \n"
"vst1.s32 {d4-d5}, [%2] \n"
"vst1.s32 {d6-d7}, [%3] \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(r0), // %4
"=r"(kptr) // %5
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(r0),
"5"(kptr),
"r"(inch) // %12
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q8", "q9", "q10"
);
#endif // __aarch64__
#else
int sum0[4] = {0};
int sum1[4] = {0};
int sum2[4] = {0};
int sum3[4] = {0};
for (int q=0; q<inch; q++)
{
for (int n=0; n<4; n++)
{
sum0[n] += (int)r0[n] * kptr[n];
sum1[n] += (int)r0[n] * kptr[n+4];
sum2[n] += (int)r0[n] * kptr[n+8];
sum3[n] += (int)r0[n] * kptr[n+12];
}
kptr += 16;
r0 += 4;
}
for (int n=0; n<4; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
}
#endif // __ARM_NEON
output0_tm += 36;
output1_tm += 36;
output2_tm += 36;
output3_tm += 36;
}
}
remain_outch_start += nn_outch << 2;
for (int p=remain_outch_start; p<outch; p++)
{
int* output0_tm = top_blob_tm.channel(p);
output0_tm = output0_tm + r*4;
for (int i=0; i<tiles; i++)
{
const short* kptr = kernel_tm_test[r].channel(p/8 + (p%8)/4 + p%4);
const short* r0 = bottom_blob_tm.channel(tiles*r+i);
#if __ARM_NEON
#if __aarch64__
asm volatile(
// inch loop
"eor v0.16b, v0.16b, v0.16b \n"
"mov w4, %w6 \n"
"0: \n" // for (int q=0; q<inch; q++)
"ld1 {v8.4h}, [%1] \n" // _r0 = vld1_s16(r0); // input inch0
"ld1 {v9.4h}, [%2] \n" // _k0 = vld1q_s16(kptr);
"add %1, %1, #8 \n"
"add %2, %2, #8 \n"
"subs w4, w4, #1 \n"
"smlal v0.4s, v8.4h, v9.4h \n" // sum0 += (a00-a03) * (k00-k03)
"bne 0b \n" // end for
"st1 {v0.4s}, [%0] \n" // store the result to memory
: "=r"(output0_tm), // %0
"=r"(r0), // %1
"=r"(kptr) // %2
: "0"(output0_tm),
"1"(r0),
"2"(kptr),
"r"(inch) // %6
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9"
);
#else
asm volatile(
// inch loop
"vmov.s32 q0, #0 \n"
"mov r4, %6 \n"
"0: \n" // for (int q=0; q<inch; q++)
"vld1.s16 {d16}, [%1] \n" // _r0 = vld1_s16(r0); // input inch0
"add %1, #8 \n"
"vld1.s16 {d18}, [%2] \n" // _k0 = vld1q_s16(kptr);
"add %2, #8 \n"
"vmlal.s16 q0, d16, d18 \n" // sum0 += (a00-a03) * (k00-k03)
"subs r4, r4, #1 \n"
"bne 0b \n" // end for
"vst1.s32 {d0-d1}, [%0] \n" // store the result to memory
: "=r"(output0_tm), // %0
"=r"(r0), // %1
"=r"(kptr) // %2
: "0"(output0_tm),
"1"(r0),
"2"(kptr),
"r"(inch) // %6
: "cc", "memory", "r4", "q0", "q8", "q9"
);
#endif // __aarch64__
#else // __ARM_NEON
int sum0[4] = {0};
for (int q=0; q<inch; q++)
{
for (int n=0; n<4; n++)
{
sum0[n] += (int)r0[n] * kptr[n];
}
kptr += 4;
r0 += 4;
}
for (int n=0; n<4; n++)
{
output0_tm[n] = sum0[n];
}
#endif // __ARM_NEON
output0_tm += 36;
}
}
// for (int p=0; p<outch; p++)
// {
// Mat out0_tm = top_blob_tm.channel(p);
// const Mat kernel0_tm = kernel_tm.channel(p);
// for (int i=0; i<tiles; i++)
// {
// int* output0_tm = out0_tm.row<int>(i);
// int sum0[36] = {0};
// for (int q=0; q<inch; q++)
// {
// const short* r0 = bottom_blob_tm.channel(q).row<short>(i);
// const short* k0 = kernel0_tm.row<short>(q);
// for (int n=0; n<36; n++)
// {
// sum0[n] += (int)r0[n] * k0[n];
// }
// }
// for (int n=0; n<36; n++)
// {
// output0_tm[n] = sum0[n];
// }
// }
// }
}
}
bottom_blob_tm = Mat();
// END dot
// BEGIN transform output
Mat top_blob_bordered;
top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator);
{
// AT
// const float itm[4][6] = {
// {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f}
// };
// 0 = r00 + r01 + r02 + r03 + r04
// 1 = r01 - r02 + 2 * (r03 - r04)
// 2 = r01 + r02 + 4 * (r03 + r04)
// 3 = r01 - r02 + 8 * (r03 - r04) + r05
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
int nColBlocks = h_tm/6; // may be the block num in Feathercnn
int nRowBlocks = w_tm/6;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=0; p<outch; p++)
{
int* out_tile = top_blob_tm.channel(p);
int* outRow0 = top_blob_bordered.channel(p);
int* outRow1 = outRow0 + outw;
int* outRow2 = outRow0 + outw * 2;
int* outRow3 = outRow0 + outw * 3;
for (int j=0; j<nColBlocks; j++)
{
for(int i=0; i<nRowBlocks; i++)
{
#if __ARM_NEON
int32x4_t _s0, _s1, _s2, _s3, _s4, _s5;
int32x2_t _s0n, _s1n, _s2n, _s3n, _s4n, _s5n;
int32x4_t _w0, _w1, _w2, _w3;
int32x2_t _w0n, _w1n, _w2n, _w3n;
int32x4_t _d0, _d1, _d2, _d3, _d4, _d5;
int32x4_t _o0, _o1, _o2, _o3;
// load
_s0 = vld1q_s32(out_tile);
_s0n = vld1_s32(out_tile+4);
_s1 = vld1q_s32(out_tile+6);
_s1n = vld1_s32(out_tile+10);
_s2 = vld1q_s32(out_tile+12);
_s2n = vld1_s32(out_tile+16);
_s3 = vld1q_s32(out_tile+18);
_s3n = vld1_s32(out_tile+22);
_s4 = vld1q_s32(out_tile+24);
_s4n = vld1_s32(out_tile+28);
_s5 = vld1q_s32(out_tile+30);
_s5n = vld1_s32(out_tile+34);
// w = A_T * W
int32x2_t _tp0 = {1, 4};
int32x2_t _tp1 = {2, 8};
// 4*s5[n]
int32x4_t _s5x4 = vshlq_n_s32(_s5, 2);
int32x2_t _s5x4n = vshl_n_s32(_s5n, 2);
int32x4_t _t1p2 = vaddq_s32(_s1, _s2);
int32x2_t _t1p2n = vadd_s32 (_s1n, _s2n);
int32x4_t _t3p4 = vaddq_s32(_s3, _s4);
int32x2_t _t3p4n = vadd_s32 (_s3n, _s4n);
int32x4_t _t1s2 = vsubq_s32(_s1, _s2);
int32x2_t _t1s2n = vsub_s32 (_s1n, _s2n);
int32x4_t _t3s4 = vsubq_s32(_s3, _s4);
int32x2_t _t3s4n = vsub_s32 (_s3n, _s4n);
_w0 = vaddq_s32(_s0, _t1p2);
_w0n = vadd_s32 (_s0n, _t1p2n);
_w0 = vaddq_s32(_w0, _t3p4);
_w0n = vadd_s32 (_w0n, _t3p4n);
_w0n = vmul_s32(_w0n, _tp0);
// _w2,_w2n
_t1p2 = vmlaq_lane_s32(_t1p2, _t3p4, _tp0, 1);
_t1p2n = vmla_lane_s32 (_t1p2n, _t3p4n, _tp0, 1);
_t1p2n = vmul_s32(_t1p2n, _tp0);
_w3 = vaddq_s32(_s5x4, _t1s2);
_w3n = vadd_s32 (_s5x4n, _t1s2n);
_w3 = vmlaq_lane_s32(_w3, _t3s4, _tp1, 1);
_w3n = vmla_lane_s32 (_w3n, _t3s4n, _tp1, 1);
_w3n = vmul_s32(_w3n, _tp0);
// _w1, _w1n
_t1s2 = vmlaq_lane_s32(_t1s2, _t3s4, _tp1, 0);
_t1s2n = vmla_lane_s32 (_t1s2n, _t3s4n, _tp1, 0);
_t1s2n = vmul_s32(_t1s2n, _tp0);
int32x4_t _w02n = vcombine_s32(_w0n, _t1p2n);
int32x4_t _w13n = vcombine_s32(_t1s2n, _w3n);
// transpose w to w_t
#if __aarch64__
int32x4_t _wt0 = vtrn1q_s32(_w0, _t1s2);
int32x4_t _wt1 = vtrn2q_s32(_w0, _t1s2);
int32x4_t _wt2 = vtrn1q_s32(_t1p2, _w3);
int32x4_t _wt3 = vtrn2q_s32(_t1p2, _w3);
int64x2_t _dt0 = vtrn1q_s64(vreinterpretq_s64_s32(_wt0), vreinterpretq_s64_s32(_wt2));
int64x2_t _dt2 = vtrn2q_s64(vreinterpretq_s64_s32(_wt0), vreinterpretq_s64_s32(_wt2));
int64x2_t _dt1 = vtrn1q_s64(vreinterpretq_s64_s32(_wt1), vreinterpretq_s64_s32(_wt3));
int64x2_t _dt3 = vtrn2q_s64(vreinterpretq_s64_s32(_wt1), vreinterpretq_s64_s32(_wt3));
_d0 = vreinterpretq_s32_s64(_dt0);
_d1 = vreinterpretq_s32_s64(_dt1);
_d2 = vreinterpretq_s32_s64(_dt2);
_d3 = vreinterpretq_s32_s64(_dt3);
_d4 = vtrn1q_s32(_w02n, _w13n);
_d5 = vtrn2q_s32(_w02n, _w13n);
#else
asm volatile(
"vtrn.32 %q[_w0], %q[_w1] \n"
"vtrn.32 %q[_w2], %q[_w3] \n"
"vswp %f[_w0], %e[_w2] \n"
"vswp %f[_w1], %e[_w3] \n"
"vtrn.32 %q[_w02n], %q[_w13n] \n"
: [_w0]"+w"(_w0),
[_w1]"+w"(_t1s2),
[_w2]"+w"(_t1p2),
[_w3]"+w"(_w3),
[_w02n]"+w"(_w02n),
[_w13n]"+w"(_w13n)
:
: "cc", "memory"
);
_d0 = _w0;
_d1 = _t1s2;
_d2 = _t1p2;
_d3 = _w3;
_d4 = _w02n;
_d5 = _w13n;
#endif
// Y = A_T * w_t
_t1p2 = vaddq_s32(_d1, _d2);
_t3p4 = vaddq_s32(_d3, _d4);
_t1s2 = vsubq_s32(_d1, _d2);
_t3s4 = vsubq_s32(_d3, _d4);
_o0 = vaddq_s32(_d0, _t1p2);
_o0 = vaddq_s32(_o0, _t3p4);
// _o2
_t1p2 = vmlaq_lane_s32(_t1p2, _t3p4, _tp0, 1);
_o3 = vaddq_s32(_d5, _t1s2);
_o3 = vmlaq_lane_s32(_o3, _t3s4, _tp1, 1);
// _o1
_t1s2 = vmlaq_lane_s32(_t1s2, _t3s4, _tp1, 0);
// save to top blob tm
float32x4_t _ot0 = vcvtq_f32_s32(_o0);
float32x4_t _ot1 = vcvtq_f32_s32(_t1s2);
float32x4_t _ot2 = vcvtq_f32_s32(_t1p2);
float32x4_t _ot3 = vcvtq_f32_s32(_o3);
_ot0 = vmulq_n_f32(_ot0, 0.0017361112);
_ot1 = vmulq_n_f32(_ot1, 0.0017361112);
_ot2 = vmulq_n_f32(_ot2, 0.0017361112);
_ot3 = vmulq_n_f32(_ot3, 0.0017361112);
_o0 = vcvtq_s32_f32(_ot0);
_o1 = vcvtq_s32_f32(_ot1);
_o2 = vcvtq_s32_f32(_ot2);
_o3 = vcvtq_s32_f32(_ot3);
vst1q_s32(outRow0, _o0);
vst1q_s32(outRow1, _o1);
vst1q_s32(outRow2, _o2);
vst1q_s32(outRow3, _o3);
#else
int s0[6],s1[6],s2[6],s3[6],s4[6],s5[6];
int w0[6],w1[6],w2[6],w3[6];
int d0[4],d1[4],d2[4],d3[4],d4[4],d5[4];
int o0[4],o1[4],o2[4],o3[4];
// load
for (int n = 0; n < 6; n++)
{
s0[n] = out_tile[n];
s1[n] = out_tile[n+ 6];
s2[n] = out_tile[n+12];
s3[n] = out_tile[n+18];
s4[n] = out_tile[n+24];
s5[n] = out_tile[n+30];
}
// w = A_T * W
for (int n = 0; n < 5; n++)
{
w0[n] = s0[n] + s1[n] + s2[n] + s3[n] + s4[n];
w1[n] = s1[n] - s2[n] + 2*s3[n] - 2*s4[n];
w2[n] = s1[n] + s2[n] + 4*s3[n] + 4*s4[n];
w3[n] = s1[n] - s2[n] + 8*s3[n] - 8*s4[n] + 4*s5[n];
}
for (int n = 5; n < 6; n++)
{
w0[n] = 4*(s0[n] + s1[n] + s2[n] + s3[n] + s4[n]);
w1[n] = 4*(s1[n] - s2[n] + 2*s3[n] - 2*s4[n]);
w2[n] = 4*(s1[n] + s2[n] + 4*s3[n] + 4*s4[n]);
w3[n] = 4*(s1[n] - s2[n] + 8*s3[n] - 8*s4[n] + 4*s5[n]);
}
// transpose w to w_t
{
d0[0] = w0[0]; d0[1] = w1[0]; d0[2] = w2[0]; d0[3] = w3[0];
d1[0] = w0[1]; d1[1] = w1[1]; d1[2] = w2[1]; d1[3] = w3[1];
d2[0] = w0[2]; d2[1] = w1[2]; d2[2] = w2[2]; d2[3] = w3[2];
d3[0] = w0[3]; d3[1] = w1[3]; d3[2] = w2[3]; d3[3] = w3[3];
d4[0] = w0[4]; d4[1] = w1[4]; d4[2] = w2[4]; d4[3] = w3[4];
d5[0] = w0[5]; d5[1] = w1[5]; d5[2] = w2[5]; d5[3] = w3[5];
}
// Y = A_T * w_t
for (int n = 0; n < 4; n++)
{
o0[n] = d0[n] + d1[n] + d2[n] + d3[n] + d4[n];
o1[n] = d1[n] - d2[n] + 2*d3[n] - 2*d4[n];
o2[n] = d1[n] + d2[n] + 4*d3[n] + 4*d4[n];
o3[n] = d1[n] - d2[n] + 8*d3[n] - 8*d4[n] + d5[n];
}
// save to top blob tm
for (int n = 0; n < 4; n++)
{
outRow0[n] = o0[n] / 576;
outRow1[n] = o1[n] / 576;
outRow2[n] = o2[n] / 576;
outRow3[n] = o3[n] / 576;
}
#endif // __ARM_NEON
out_tile += 36;
outRow0 += 4;
outRow1 += 4;
outRow2 += 4;
outRow3 += 4;
}
outRow0 += outw * 3;
outRow1 += outw * 3;
outRow2 += outw * 3;
outRow3 += outw * 3;
}
}
}
// END transform output
// cut result pad
copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt);
}
static void conv3x3s1_winograd43_dequant_int8_neon(const Mat& bottom_blob, Mat& top_blob, const std::vector<Mat> &kernel_tm_test, const Mat &_bias, std::vector<float> scales_dequant, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float* bias = _bias;
// pad to 4n+2, winograd F(4,3)
Mat bottom_blob_bordered = bottom_blob;
outw = (outw + 3) / 4 * 4;
outh = (outh + 3) / 4 * 4;
w = outw + 2;
h = outh + 2;
Option opt_b = opt;
opt_b.blob_allocator = opt.workspace_allocator;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt_b);
// BEGIN transform input
Mat bottom_blob_tm;
{
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
int nColBlocks = h_tm/6; // may be the block num in Feathercnn
int nRowBlocks = w_tm/6;
const int tiles = nColBlocks * nRowBlocks;
bottom_blob_tm.create(4, inch, tiles*9, 2u, opt.workspace_allocator);
// BT
// const float itm[4][4] = {
// {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f},
// {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f},
// {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f},
// {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f}
// };
// 0 = 4 * r00 - 5 * r02 + r04
// 1 = -4 * (r01 + r02) + r03 + r04
// 2 = 4 * (r01 - r02) - r03 + r04
// 3 = -2 * r01 - r02 + 2 * r03 + r04
// 4 = 2 * r01 - r02 - 2 * r03 + r04
// 5 = 4 * r01 - 5 * r03 + r05
#pragma omp parallel for num_threads(opt.num_threads)
for (int q=0; q<inch; q++)
{
const signed char* img = bottom_blob_bordered.channel(q);
for (int j = 0; j < nColBlocks; j++)
{
const signed char* r0 = img + w * j * 4;
const signed char* r1 = r0 + w;
const signed char* r2 = r1 + w;
const signed char* r3 = r2 + w;
const signed char* r4 = r3 + w;
const signed char* r5 = r4 + w;
for (int i = 0; i < nRowBlocks; i++)
{
short* out_tm0 = bottom_blob_tm.channel(tiles*0+j*nRowBlocks+i).row<short>(q);
short* out_tm1 = bottom_blob_tm.channel(tiles*1+j*nRowBlocks+i).row<short>(q);
short* out_tm2 = bottom_blob_tm.channel(tiles*2+j*nRowBlocks+i).row<short>(q);
short* out_tm3 = bottom_blob_tm.channel(tiles*3+j*nRowBlocks+i).row<short>(q);
short* out_tm4 = bottom_blob_tm.channel(tiles*4+j*nRowBlocks+i).row<short>(q);
short* out_tm5 = bottom_blob_tm.channel(tiles*5+j*nRowBlocks+i).row<short>(q);
short* out_tm6 = bottom_blob_tm.channel(tiles*6+j*nRowBlocks+i).row<short>(q);
short* out_tm7 = bottom_blob_tm.channel(tiles*7+j*nRowBlocks+i).row<short>(q);
short* out_tm8 = bottom_blob_tm.channel(tiles*8+j*nRowBlocks+i).row<short>(q);
#if __ARM_NEON
int8x8_t _d0, _d1, _d2, _d3, _d4, _d5;
int16x8_t _w0, _w1, _w2, _w3, _w4, _w5;
int16x8_t _t0, _t1, _t2, _t3, _t4, _t5;
int16x8_t _n0, _n1, _n2, _n3, _n4, _n5;
// load
_d0 = vld1_s8(r0);
_d1 = vld1_s8(r1);
_d2 = vld1_s8(r2);
_d3 = vld1_s8(r3);
_d4 = vld1_s8(r4);
_d5 = vld1_s8(r5);
int8x8_t _1_n = vdup_n_s8(-1);
int8x8_t _2_p = vdup_n_s8(2);
int8x8_t _2_n = vdup_n_s8(-2);
int8x8_t _4_p = vdup_n_s8(4);
int8x8_t _4_n = vdup_n_s8(-4);
int8x8_t _5_n = vdup_n_s8(-5);
int16x8_t _1_n_s16 = vdupq_n_s16(-1);
int16x8_t _2_p_s16 = vdupq_n_s16(2);
int16x8_t _2_n_s16 = vdupq_n_s16(-2);
int16x8_t _4_p_s16 = vdupq_n_s16(4);
int16x8_t _4_n_s16 = vdupq_n_s16(-4);
int16x8_t _5_n_s16 = vdupq_n_s16(-5);
// w = B_t * d
_w0 = vmull_s8(_d0, _4_p);
_w0 = vmlal_s8(_w0, _d2, _5_n);
_w0 = vaddw_s8(_w0, _d4);
_w1 = vmull_s8(_d1, _4_n);
_w1 = vmlal_s8(_w1, _d2, _4_n);
_w1 = vaddw_s8(_w1, _d3);
_w1 = vaddw_s8(_w1, _d4);
_w2 = vmull_s8(_d1, _4_p);
_w2 = vmlal_s8(_w2, _d2, _4_n);
_w2 = vmlal_s8(_w2, _d3, _1_n);
_w2 = vaddw_s8(_w2, _d4);
_w3 = vmull_s8(_d1, _2_n);
_w3 = vmlal_s8(_w3, _d2, _1_n);
_w3 = vmlal_s8(_w3, _d3, _2_p);
_w3 = vaddw_s8(_w3, _d4);
_w4 = vmull_s8(_d1, _2_p);
_w4 = vmlal_s8(_w4, _d2, _1_n);
_w4 = vmlal_s8(_w4, _d3, _2_n);
_w4 = vaddw_s8(_w4, _d4);
_w5 = vmull_s8(_d1, _4_p);
_w5 = vmlal_s8(_w5, _d3, _5_n);
_w5 = vaddw_s8(_w5, _d5);
// transpose d to d_t
{
_t0[0]=_w0[0]; _t1[0]=_w0[1]; _t2[0]=_w0[2]; _t3[0]=_w0[3]; _t4[0]=_w0[4]; _t5[0]=_w0[5];
_t0[1]=_w1[0]; _t1[1]=_w1[1]; _t2[1]=_w1[2]; _t3[1]=_w1[3]; _t4[1]=_w1[4]; _t5[1]=_w1[5];
_t0[2]=_w2[0]; _t1[2]=_w2[1]; _t2[2]=_w2[2]; _t3[2]=_w2[3]; _t4[2]=_w2[4]; _t5[2]=_w2[5];
_t0[3]=_w3[0]; _t1[3]=_w3[1]; _t2[3]=_w3[2]; _t3[3]=_w3[3]; _t4[3]=_w3[4]; _t5[3]=_w3[5];
_t0[4]=_w4[0]; _t1[4]=_w4[1]; _t2[4]=_w4[2]; _t3[4]=_w4[3]; _t4[4]=_w4[4]; _t5[4]=_w4[5];
_t0[5]=_w5[0]; _t1[5]=_w5[1]; _t2[5]=_w5[2]; _t3[5]=_w5[3]; _t4[5]=_w5[4]; _t5[5]=_w5[5];
}
// d = B_t * d_t
_n0 = vmulq_s16(_t0, _4_p_s16);
_n0 = vmlaq_s16(_n0, _t2, _5_n_s16);
_n0 = vaddq_s16(_n0, _t4);
_n1 = vmulq_s16(_t1, _4_n_s16);
_n1 = vmlaq_s16(_n1, _t2, _4_n_s16);
_n1 = vaddq_s16(_n1, _t3);
_n1 = vaddq_s16(_n1, _t4);
_n2 = vmulq_s16(_t1, _4_p_s16);
_n2 = vmlaq_s16(_n2, _t2, _4_n_s16);
_n2 = vmlaq_s16(_n2, _t3, _1_n_s16);
_n2 = vaddq_s16(_n2, _t4);
_n3 = vmulq_s16(_t1, _2_n_s16);
_n3 = vmlaq_s16(_n3, _t2, _1_n_s16);
_n3 = vmlaq_s16(_n3, _t3, _2_p_s16);
_n3 = vaddq_s16(_n3, _t4);
_n4 = vmulq_s16(_t1, _2_p_s16);
_n4 = vmlaq_s16(_n4, _t2, _1_n_s16);
_n4 = vmlaq_s16(_n4, _t3, _2_n_s16);
_n4 = vaddq_s16(_n4, _t4);
_n5 = vmulq_s16(_t1, _4_p_s16);
_n5 = vmlaq_s16(_n5, _t3, _5_n_s16);
_n5 = vaddq_s16(_n5, _t5);
// save to out_tm
out_tm0[0]=_n0[0];out_tm0[1]=_n0[1];out_tm0[2]=_n0[2];out_tm0[3]=_n0[3];
out_tm1[0]=_n0[4];out_tm1[1]=_n0[5];out_tm1[2]=_n1[0];out_tm1[3]=_n1[1];
out_tm2[0]=_n1[2];out_tm2[1]=_n1[3];out_tm2[2]=_n1[4];out_tm2[3]=_n1[5];
out_tm3[0]=_n2[0];out_tm3[1]=_n2[1];out_tm3[2]=_n2[2];out_tm3[3]=_n2[3];
out_tm4[0]=_n2[4];out_tm4[1]=_n2[5];out_tm4[2]=_n3[0];out_tm4[3]=_n3[1];
out_tm5[0]=_n3[2];out_tm5[1]=_n3[3];out_tm5[2]=_n3[4];out_tm5[3]=_n3[5];
out_tm6[0]=_n4[0];out_tm6[1]=_n4[1];out_tm6[2]=_n4[2];out_tm6[3]=_n4[3];
out_tm7[0]=_n4[4];out_tm7[1]=_n4[5];out_tm7[2]=_n5[0];out_tm7[3]=_n5[1];
out_tm8[0]=_n5[2];out_tm8[1]=_n5[3];out_tm8[2]=_n5[4];out_tm8[3]=_n5[5];
#else
short d0[6],d1[6],d2[6],d3[6],d4[6],d5[6];
short w0[6],w1[6],w2[6],w3[6],w4[6],w5[6];
short t0[6],t1[6],t2[6],t3[6],t4[6],t5[6];
// load
for (int n = 0; n < 6; n++)
{
d0[n] = r0[n];
d1[n] = r1[n];
d2[n] = r2[n];
d3[n] = r3[n];
d4[n] = r4[n];
d5[n] = r5[n];
}
// w = B_t * d
for (int n = 0; n < 6; n++)
{
w0[n] = 4*d0[n] - 5*d2[n] + d4[n];
w1[n] = -4*d1[n] - 4*d2[n] + d3[n] + d4[n];
w2[n] = 4*d1[n] - 4*d2[n] - d3[n] + d4[n];
w3[n] = -2*d1[n] - d2[n] + 2*d3[n] + d4[n];
w4[n] = 2*d1[n] - d2[n] - 2*d3[n] + d4[n];
w5[n] = 4*d1[n] - 5*d3[n] + d5[n];
}
// transpose d to d_t
{
t0[0]=w0[0]; t1[0]=w0[1]; t2[0]=w0[2]; t3[0]=w0[3]; t4[0]=w0[4]; t5[0]=w0[5];
t0[1]=w1[0]; t1[1]=w1[1]; t2[1]=w1[2]; t3[1]=w1[3]; t4[1]=w1[4]; t5[1]=w1[5];
t0[2]=w2[0]; t1[2]=w2[1]; t2[2]=w2[2]; t3[2]=w2[3]; t4[2]=w2[4]; t5[2]=w2[5];
t0[3]=w3[0]; t1[3]=w3[1]; t2[3]=w3[2]; t3[3]=w3[3]; t4[3]=w3[4]; t5[3]=w3[5];
t0[4]=w4[0]; t1[4]=w4[1]; t2[4]=w4[2]; t3[4]=w4[3]; t4[4]=w4[4]; t5[4]=w4[5];
t0[5]=w5[0]; t1[5]=w5[1]; t2[5]=w5[2]; t3[5]=w5[3]; t4[5]=w5[4]; t5[5]=w5[5];
}
// d = B_t * d_t
for (int n = 0; n < 6; n++)
{
d0[n] = 4*t0[n] - 5*t2[n] + t4[n];
d1[n] = - 4*t1[n] - 4*t2[n] + t3[n] + t4[n];
d2[n] = 4*t1[n] - 4*t2[n] - t3[n] + t4[n];
d3[n] = - 2*t1[n] - t2[n] + 2*t3[n] + t4[n];
d4[n] = 2*t1[n] - t2[n] - 2*t3[n] + t4[n];
d5[n] = 4*t1[n] - 5*t3[n] + t5[n];
}
// save to out_tm
{
out_tm0[0]=d0[0];out_tm0[1]=d0[1];out_tm0[2]=d0[2];out_tm0[3]=d0[3];
out_tm1[0]=d0[4];out_tm1[1]=d0[5];out_tm1[2]=d1[0];out_tm1[3]=d1[1];
out_tm2[0]=d1[2];out_tm2[1]=d1[3];out_tm2[2]=d1[4];out_tm2[3]=d1[5];
out_tm3[0]=d2[0];out_tm3[1]=d2[1];out_tm3[2]=d2[2];out_tm3[3]=d2[3];
out_tm4[0]=d2[4];out_tm4[1]=d2[5];out_tm4[2]=d3[0];out_tm4[3]=d3[1];
out_tm5[0]=d3[2];out_tm5[1]=d3[3];out_tm5[2]=d3[4];out_tm5[3]=d3[5];
out_tm6[0]=d4[0];out_tm6[1]=d4[1];out_tm6[2]=d4[2];out_tm6[3]=d4[3];
out_tm7[0]=d4[4];out_tm7[1]=d4[5];out_tm7[2]=d5[0];out_tm7[3]=d5[1];
out_tm8[0]=d5[2];out_tm8[1]=d5[3];out_tm8[2]=d5[4];out_tm8[3]=d5[5];
}
#endif // __ARM_NEON
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
r4 += 4;
r5 += 4;
}
}
}
}
bottom_blob_bordered = Mat();
// BEGIN dot
Mat top_blob_tm;
{
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
int nColBlocks = h_tm/6; // may be the block num in Feathercnn
int nRowBlocks = w_tm/6;
const int tiles = nColBlocks * nRowBlocks;
top_blob_tm.create(36, tiles, outch, 4u, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int r=0; r<9; r++)
{
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 8;
int* output0_tm = top_blob_tm.channel(p);
int* output1_tm = top_blob_tm.channel(p+1);
int* output2_tm = top_blob_tm.channel(p+2);
int* output3_tm = top_blob_tm.channel(p+3);
int* output4_tm = top_blob_tm.channel(p+4);
int* output5_tm = top_blob_tm.channel(p+5);
int* output6_tm = top_blob_tm.channel(p+6);
int* output7_tm = top_blob_tm.channel(p+7);
output0_tm = output0_tm + r*4;
output1_tm = output1_tm + r*4;
output2_tm = output2_tm + r*4;
output3_tm = output3_tm + r*4;
output4_tm = output4_tm + r*4;
output5_tm = output5_tm + r*4;
output6_tm = output6_tm + r*4;
output7_tm = output7_tm + r*4;
for (int i=0; i<tiles; i++)
{
const short* kptr = kernel_tm_test[r].channel(p/8);
const short* r0 = bottom_blob_tm.channel(tiles*r+i);
#if __ARM_NEON
#if __aarch64__
asm volatile(
// inch loop
"eor v0.16b, v0.16b, v0.16b \n"
"eor v1.16b, v1.16b, v1.16b \n"
"eor v2.16b, v2.16b, v2.16b \n"
"eor v3.16b, v3.16b, v3.16b \n"
"eor v4.16b, v4.16b, v4.16b \n"
"eor v5.16b, v5.16b, v5.16b \n"
"eor v6.16b, v6.16b, v6.16b \n"
"eor v7.16b, v7.16b, v7.16b \n"
"mov w4, %w20 \n"
"0: \n" // for (int q=0; q<inch; q++)
"prfm pldl1keep, [%9, #128] \n" // _r0 = vld1_s16(r0);
"ld1 {v8.4h}, [%8] \n"
"ld1 {v9.4h, v10.4h}, [%9] \n" // _k01 = vld1q_s16(kptr);
"add %9, %9, #16 \n"
"ld1 {v11.4h, v12.4h}, [%9] \n" // _k23 = vld1q_s16(kptr+8);
"add %9, %9, #16 \n"
"ld1 {v13.4h, v14.4h}, [%9] \n" // _k45 = vld1q_s16(kptr+16);
"add %9, %9, #16 \n"
"ld1 {v15.4h, v16.4h}, [%9] \n" // _k67 = vld1q_s16(kptr+24);
"add %8, %8, #8 \n"
"add %9, %9, #16 \n"
"subs w4, w4, #1 \n"
"smlal v0.4s, v8.4h, v9.4h \n" // sum0 += (a00-a03) * (k00-k03)
"smlal v1.4s, v8.4h, v10.4h \n" // sum1 += (a00-a03) * (k10-k13)
"smlal v2.4s, v8.4h, v11.4h \n" // sum2 += (a00-a03) * (k20-k23)
"smlal v3.4s, v8.4h, v12.4h \n" // sum3 += (a00-a03) * (k30-k33)
"smlal v4.4s, v8.4h, v13.4h \n" // sum4 += (a00-a03) * (k40-k43)
"smlal v5.4s, v8.4h, v14.4h \n" // sum5 += (a00-a03) * (k50-k53)
"smlal v6.4s, v8.4h, v15.4h \n" // sum6 += (a00-a03) * (k60-k63)
"smlal v7.4s, v8.4h, v16.4h \n" // sum7 += (a00-a03) * (k70-k73)
"bne 0b \n" // end for
"st1 {v0.4s}, [%0] \n" // store the result to memory
"st1 {v1.4s}, [%1] \n" //
"st1 {v2.4s}, [%2] \n" //
"st1 {v3.4s}, [%3] \n" //
"st1 {v4.4s}, [%4] \n" //
"st1 {v5.4s}, [%5] \n" //
"st1 {v6.4s}, [%6] \n" //
"st1 {v7.4s}, [%7] \n" //
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(output4_tm), // %4
"=r"(output5_tm), // %5
"=r"(output6_tm), // %6
"=r"(output7_tm), // %7
"=r"(r0), // %8
"=r"(kptr) // %9
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(output4_tm),
"5"(output5_tm),
"6"(output6_tm),
"7"(output7_tm),
"8"(r0),
"9"(kptr),
"r"(inch) // %20
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16"
);
#else
asm volatile(
// inch loop
"vmov.s32 q0, #0 \n"
"vmov.s32 q1, #0 \n"
"vmov.s32 q2, #0 \n"
"vmov.s32 q3, #0 \n"
"vmov.s32 q4, #0 \n"
"vmov.s32 q5, #0 \n"
"vmov.s32 q6, #0 \n"
"vmov.s32 q7, #0 \n"
"mov r4, %20 \n"
"0: \n" // for (int q=0; q<inch; q++)
"vld1.s16 {d16}, [%8]! \n" // _r0 = vld1_s16(r0); // input inch0
"vld1.s16 {d18-d19}, [%9] \n" // _k01 = vld1q_s16(kptr);
"add %9, #16 \n"
"vld1.s16 {d20-d21}, [%9] \n" // _k23 = vld1q_s16(kptr+8);
"add %9, #16 \n"
"vld1.s16 {d22-d23}, [%9] \n" // _k45 = vld1q_s16(kptr+16);
"add %9, #16 \n"
"vld1.s16 {d24-d25}, [%9] \n" // _k67 = vld1q_s16(kptr+24);
"add %9, #16 \n"
"vmlal.s16 q0, d16, d18 \n" // sum0 += (a00-a03) * (k00-k03)
"vmlal.s16 q1, d16, d19 \n" // sum1 += (a00-a03) * (k10-k13)
"vmlal.s16 q2, d16, d20 \n" // sum2 += (a00-a03) * (k20-k23)
"vmlal.s16 q3, d16, d21 \n" // sum3 += (a00-a03) * (k30-k33)
"vmlal.s16 q4, d16, d22 \n" // sum4 += (a00-a03) * (k40-k43)
"vmlal.s16 q5, d16, d23 \n" // sum5 += (a00-a03) * (k50-k53)
"vmlal.s16 q6, d16, d24 \n" // sum6 += (a00-a03) * (k60-k63)
"vmlal.s16 q7, d16, d25 \n" // sum7 += (a00-a03) * (k70-k73)
"subs r4, r4, #1 \n"
"bne 0b \n" // end for
"vst1.s32 {d0-d1}, [%0] \n" // store the result to memory
"vst1.s32 {d2-d3}, [%1] \n"
"vst1.s32 {d4-d5}, [%2] \n"
"vst1.s32 {d6-d7}, [%3] \n"
"vst1.s32 {d8-d9}, [%4] \n"
"vst1.s32 {d10-d11}, [%5] \n"
"vst1.s32 {d12-d13}, [%6] \n"
"vst1.s32 {d14-d15}, [%7] \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(output4_tm), // %4
"=r"(output5_tm), // %5
"=r"(output6_tm), // %6
"=r"(output7_tm), // %7
"=r"(r0), // %8
"=r"(kptr) // %9
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(output4_tm),
"5"(output5_tm),
"6"(output6_tm),
"7"(output7_tm),
"8"(r0),
"9"(kptr),
"r"(inch) // %20
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12"
);
#endif // __aarch64__
#else
int sum0[4] = {0};
int sum1[4] = {0};
int sum2[4] = {0};
int sum3[4] = {0};
int sum4[4] = {0};
int sum5[4] = {0};
int sum6[4] = {0};
int sum7[4] = {0};
for (int q=0; q<inch; q++)
{
for (int n=0; n<4; n++)
{
sum0[n] += (int)r0[n] * kptr[n];
sum1[n] += (int)r0[n] * kptr[n+4];
sum2[n] += (int)r0[n] * kptr[n+8];
sum3[n] += (int)r0[n] * kptr[n+12];
sum4[n] += (int)r0[n] * kptr[n+16];
sum5[n] += (int)r0[n] * kptr[n+20];
sum6[n] += (int)r0[n] * kptr[n+24];
sum7[n] += (int)r0[n] * kptr[n+28];
}
kptr += 32;
r0 += 4;
}
for (int n=0; n<4; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
output4_tm[n] = sum4[n];
output5_tm[n] = sum5[n];
output6_tm[n] = sum6[n];
output7_tm[n] = sum7[n];
}
#endif // __ARM_NEON
output0_tm += 36;
output1_tm += 36;
output2_tm += 36;
output3_tm += 36;
output4_tm += 36;
output5_tm += 36;
output6_tm += 36;
output7_tm += 36;
}
}
nn_outch = (outch - remain_outch_start) >> 2;
for (int pp=0; pp<nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
int* output0_tm = top_blob_tm.channel(p);
int* output1_tm = top_blob_tm.channel(p+1);
int* output2_tm = top_blob_tm.channel(p+2);
int* output3_tm = top_blob_tm.channel(p+3);
output0_tm = output0_tm + r*4;
output1_tm = output1_tm + r*4;
output2_tm = output2_tm + r*4;
output3_tm = output3_tm + r*4;
for (int i=0; i<tiles; i++)
{
const short* kptr = kernel_tm_test[r].channel(p/8 + (p%8)/4);
const short* r0 = bottom_blob_tm.channel(tiles*r+i);
#if __ARM_NEON
#if __aarch64__
asm volatile(
// inch loop
"eor v0.16b, v0.16b, v0.16b \n"
"eor v1.16b, v1.16b, v1.16b \n"
"eor v2.16b, v2.16b, v2.16b \n"
"eor v3.16b, v3.16b, v3.16b \n"
"mov w4, %w12 \n"
"0: \n" // for (int q=0; q<inch; q++)
"prfm pldl1keep, [%5, #128] \n" // _r0 = vld1_s16(r0); // input inch0
"ld1 {v8.4h}, [%4] \n"
"ld1 {v9.4h, v10.4h}, [%5] \n" // _k01 = vld1q_s16(kptr);
"add %5, %5, #16 \n"
"ld1 {v11.4h, v12.4h}, [%5] \n" // _k23 = vld1q_s16(kptr+8);
"add %4, %4, #8 \n"
"add %5, %5, #16 \n"
"subs w4, w4, #1 \n"
"smlal v0.4s, v8.4h, v9.4h \n" // sum0 += (a00-a03) * (k00-k03)
"smlal v1.4s, v8.4h, v10.4h \n" // sum1 += (a00-a03) * (k10-k13)
"smlal v2.4s, v8.4h, v11.4h \n" // sum2 += (a00-a03) * (k20-k23)
"smlal v3.4s, v8.4h, v12.4h \n" // sum3 += (a00-a03) * (k30-k33)
"bne 0b \n" // end for
"st1 {v0.4s}, [%0] \n" // store the result to memory
"st1 {v1.4s}, [%1] \n" //
"st1 {v2.4s}, [%2] \n" //
"st1 {v3.4s}, [%3] \n" //
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(r0), // %4
"=r"(kptr) // %5
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(r0),
"5"(kptr),
"r"(inch) // %12
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12"
);
#else
asm volatile(
// inch loop
"vmov.s32 q0, #0 \n"
"vmov.s32 q1, #0 \n"
"vmov.s32 q2, #0 \n"
"vmov.s32 q3, #0 \n"
"mov r4, %12 \n"
"0: \n" // for (int q=0; q<inch; q++)
"vld1.s16 {d16}, [%4]! \n" // _r0 = vld1_s16(r0); // input inch0
"vld1.s16 {d18-d19}, [%5] \n" // _k01 = vld1q_s16(kptr);
"add %5, #16 \n"
"vld1.s16 {d20-d21}, [%5] \n" // _k23 = vld1q_s16(kptr+8);
"add %5, #16 \n"
"vmlal.s16 q0, d16, d18 \n" // sum0 += (a00-a03) * (k00-k03)
"vmlal.s16 q1, d16, d19 \n" // sum1 += (a00-a03) * (k10-k13)
"vmlal.s16 q2, d16, d20 \n" // sum2 += (a00-a03) * (k20-k23)
"vmlal.s16 q3, d16, d21 \n" // sum3 += (a00-a03) * (k30-k33)
"subs r4, r4, #1 \n"
"bne 0b \n" // end for
"vst1.s32 {d0-d1}, [%0] \n" // store the result to memory
"vst1.s32 {d2-d3}, [%1] \n"
"vst1.s32 {d4-d5}, [%2] \n"
"vst1.s32 {d6-d7}, [%3] \n"
: "=r"(output0_tm), // %0
"=r"(output1_tm), // %1
"=r"(output2_tm), // %2
"=r"(output3_tm), // %3
"=r"(r0), // %4
"=r"(kptr) // %5
: "0"(output0_tm),
"1"(output1_tm),
"2"(output2_tm),
"3"(output3_tm),
"4"(r0),
"5"(kptr),
"r"(inch) // %12
: "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q8", "q9", "q10"
);
#endif // __aarch64__
#else
int sum0[4] = {0};
int sum1[4] = {0};
int sum2[4] = {0};
int sum3[4] = {0};
for (int q=0; q<inch; q++)
{
for (int n=0; n<4; n++)
{
sum0[n] += (int)r0[n] * kptr[n];
sum1[n] += (int)r0[n] * kptr[n+4];
sum2[n] += (int)r0[n] * kptr[n+8];
sum3[n] += (int)r0[n] * kptr[n+12];
}
kptr += 16;
r0 += 4;
}
for (int n=0; n<4; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
}
#endif // __ARM_NEON
output0_tm += 36;
output1_tm += 36;
output2_tm += 36;
output3_tm += 36;
}
}
remain_outch_start += nn_outch << 2;
for (int p=remain_outch_start; p<outch; p++)
{
int* output0_tm = top_blob_tm.channel(p);
output0_tm = output0_tm + r*4;
for (int i=0; i<tiles; i++)
{
const short* kptr = kernel_tm_test[r].channel(p/8 + (p%8)/4 + p%4);
const short* r0 = bottom_blob_tm.channel(tiles*r+i);
#if __ARM_NEON
#if __aarch64__
asm volatile(
// inch loop
"eor v0.16b, v0.16b, v0.16b \n"
"mov w4, %w6 \n"
"0: \n" // for (int q=0; q<inch; q++)
"ld1 {v8.4h}, [%1] \n" // _r0 = vld1_s16(r0); // input inch0
"ld1 {v9.4h}, [%2] \n" // _k0 = vld1q_s16(kptr);
"add %1, %1, #8 \n"
"add %2, %2, #8 \n"
"subs w4, w4, #1 \n"
"smlal v0.4s, v8.4h, v9.4h \n" // sum0 += (a00-a03) * (k00-k03)
"bne 0b \n" // end for
"st1 {v0.4s}, [%0] \n" // store the result to memory
: "=r"(output0_tm), // %0
"=r"(r0), // %1
"=r"(kptr) // %2
: "0"(output0_tm),
"1"(r0),
"2"(kptr),
"r"(inch) // %6
: "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9"
);
#else
asm volatile(
// inch loop
"vmov.s32 q0, #0 \n"
"mov r4, %6 \n"
"0: \n" // for (int q=0; q<inch; q++)
"vld1.s16 {d16}, [%1] \n" // _r0 = vld1_s16(r0); // input inch0
"add %1, #8 \n"
"vld1.s16 {d18}, [%2] \n" // _k0 = vld1q_s16(kptr);
"add %2, #8 \n"
"vmlal.s16 q0, d16, d18 \n" // sum0 += (a00-a03) * (k00-k03)
"subs r4, r4, #1 \n"
"bne 0b \n" // end for
"vst1.s32 {d0-d1}, [%0] \n" // store the result to memory
: "=r"(output0_tm), // %0
"=r"(r0), // %1
"=r"(kptr) // %2
: "0"(output0_tm),
"1"(r0),
"2"(kptr),
"r"(inch) // %6
: "cc", "memory", "r4", "q0", "q8", "q9"
);
#endif // __aarch64__
#else // __ARM_NEON
int sum0[4] = {0};
for (int q=0; q<inch; q++)
{
for (int n=0; n<4; n++)
{
sum0[n] += (int)r0[n] * kptr[n];
}
kptr += 4;
r0 += 4;
}
for (int n=0; n<4; n++)
{
output0_tm[n] = sum0[n];
}
#endif // __ARM_NEON
output0_tm += 36;
}
}
// for (int p=0; p<outch; p++)
// {
// Mat out0_tm = top_blob_tm.channel(p);
// const Mat kernel0_tm = kernel_tm.channel(p);
// for (int i=0; i<tiles; i++)
// {
// int* output0_tm = out0_tm.row<int>(i);
// int sum0[36] = {0};
// for (int q=0; q<inch; q++)
// {
// const short* r0 = bottom_blob_tm.channel(q).row<short>(i);
// const short* k0 = kernel0_tm.row<short>(q);
// for (int n=0; n<36; n++)
// {
// sum0[n] += (int)r0[n] * k0[n];
// }
// }
// for (int n=0; n<36; n++)
// {
// output0_tm[n] = sum0[n];
// }
// }
// }
}
}
bottom_blob_tm = Mat();
// END dot
// BEGIN transform output
Mat top_blob_bordered;
top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator);
{
// AT
// const float itm[4][6] = {
// {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f}
// };
// 0 = r00 + r01 + r02 + r03 + r04
// 1 = r01 - r02 + 2 * (r03 - r04)
// 2 = r01 + r02 + 4 * (r03 + r04)
// 3 = r01 - r02 + 8 * (r03 - r04) + r05
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
int nColBlocks = h_tm/6; // may be the block num in Feathercnn
int nRowBlocks = w_tm/6;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=0; p<outch; p++)
{
int* out_tile = top_blob_tm.channel(p);
float* outRow0 = top_blob_bordered.channel(p);
float* outRow1 = outRow0 + outw;
float* outRow2 = outRow0 + outw * 2;
float* outRow3 = outRow0 + outw * 3;
const float bias0 = bias ? bias[p] : 0.f;
const float scale_dequant0 = scales_dequant[p];
const float scale0 = scale_dequant0 / 576.0;
for (int j=0; j<nColBlocks; j++)
{
for(int i=0; i<nRowBlocks; i++)
{
#if __ARM_NEON
int32x4_t _s0, _s1, _s2, _s3, _s4, _s5;
int32x2_t _s0n, _s1n, _s2n, _s3n, _s4n, _s5n;
int32x4_t _w0, _w1, _w2, _w3;
int32x2_t _w0n, _w1n, _w2n, _w3n;
int32x4_t _d0, _d1, _d2, _d3, _d4, _d5;
int32x4_t _o0, _o1, _o2, _o3;
// load
_s0 = vld1q_s32(out_tile);
_s0n = vld1_s32(out_tile+4);
_s1 = vld1q_s32(out_tile+6);
_s1n = vld1_s32(out_tile+10);
_s2 = vld1q_s32(out_tile+12);
_s2n = vld1_s32(out_tile+16);
_s3 = vld1q_s32(out_tile+18);
_s3n = vld1_s32(out_tile+22);
_s4 = vld1q_s32(out_tile+24);
_s4n = vld1_s32(out_tile+28);
_s5 = vld1q_s32(out_tile+30);
_s5n = vld1_s32(out_tile+34);
// w = A_T * W
int32x2_t _tp0 = {1, 4};
int32x2_t _tp1 = {2, 8};
// 4*s5[n]
int32x4_t _s5x4 = vshlq_n_s32(_s5, 2);
int32x2_t _s5x4n = vshl_n_s32(_s5n, 2);
int32x4_t _t1p2 = vaddq_s32(_s1, _s2);
int32x2_t _t1p2n = vadd_s32 (_s1n, _s2n);
int32x4_t _t3p4 = vaddq_s32(_s3, _s4);
int32x2_t _t3p4n = vadd_s32 (_s3n, _s4n);
int32x4_t _t1s2 = vsubq_s32(_s1, _s2);
int32x2_t _t1s2n = vsub_s32 (_s1n, _s2n);
int32x4_t _t3s4 = vsubq_s32(_s3, _s4);
int32x2_t _t3s4n = vsub_s32 (_s3n, _s4n);
_w0 = vaddq_s32(_s0, _t1p2);
_w0n = vadd_s32 (_s0n, _t1p2n);
_w0 = vaddq_s32(_w0, _t3p4);
_w0n = vadd_s32 (_w0n, _t3p4n);
_w0n = vmul_s32(_w0n, _tp0);
// _w2,_w2n
_t1p2 = vmlaq_lane_s32(_t1p2, _t3p4, _tp0, 1);
_t1p2n = vmla_lane_s32 (_t1p2n, _t3p4n, _tp0, 1);
_t1p2n = vmul_s32(_t1p2n, _tp0);
_w3 = vaddq_s32(_s5x4, _t1s2);
_w3n = vadd_s32 (_s5x4n, _t1s2n);
_w3 = vmlaq_lane_s32(_w3, _t3s4, _tp1, 1);
_w3n = vmla_lane_s32 (_w3n, _t3s4n, _tp1, 1);
_w3n = vmul_s32(_w3n, _tp0);
// _w1, _w1n
_t1s2 = vmlaq_lane_s32(_t1s2, _t3s4, _tp1, 0);
_t1s2n = vmla_lane_s32 (_t1s2n, _t3s4n, _tp1, 0);
_t1s2n = vmul_s32(_t1s2n, _tp0);
int32x4_t _w02n = vcombine_s32(_w0n, _t1p2n);
int32x4_t _w13n = vcombine_s32(_t1s2n, _w3n);
// transpose w to w_t
#if __aarch64__
int32x4_t _wt0 = vtrn1q_s32(_w0, _t1s2);
int32x4_t _wt1 = vtrn2q_s32(_w0, _t1s2);
int32x4_t _wt2 = vtrn1q_s32(_t1p2, _w3);
int32x4_t _wt3 = vtrn2q_s32(_t1p2, _w3);
int64x2_t _dt0 = vtrn1q_s64(vreinterpretq_s64_s32(_wt0), vreinterpretq_s64_s32(_wt2));
int64x2_t _dt2 = vtrn2q_s64(vreinterpretq_s64_s32(_wt0), vreinterpretq_s64_s32(_wt2));
int64x2_t _dt1 = vtrn1q_s64(vreinterpretq_s64_s32(_wt1), vreinterpretq_s64_s32(_wt3));
int64x2_t _dt3 = vtrn2q_s64(vreinterpretq_s64_s32(_wt1), vreinterpretq_s64_s32(_wt3));
_d0 = vreinterpretq_s32_s64(_dt0);
_d1 = vreinterpretq_s32_s64(_dt1);
_d2 = vreinterpretq_s32_s64(_dt2);
_d3 = vreinterpretq_s32_s64(_dt3);
_d4 = vtrn1q_s32(_w02n, _w13n);
_d5 = vtrn2q_s32(_w02n, _w13n);
#else
asm volatile(
"vtrn.32 %q[_w0], %q[_w1] \n"
"vtrn.32 %q[_w2], %q[_w3] \n"
"vswp %f[_w0], %e[_w2] \n"
"vswp %f[_w1], %e[_w3] \n"
"vtrn.32 %q[_w02n], %q[_w13n] \n"
: [_w0]"+w"(_w0),
[_w1]"+w"(_t1s2),
[_w2]"+w"(_t1p2),
[_w3]"+w"(_w3),
[_w02n]"+w"(_w02n),
[_w13n]"+w"(_w13n)
:
: "cc", "memory"
);
_d0 = _w0;
_d1 = _t1s2;
_d2 = _t1p2;
_d3 = _w3;
_d4 = _w02n;
_d5 = _w13n;
#endif
// Y = A_T * w_t
_t1p2 = vaddq_s32(_d1, _d2);
_t3p4 = vaddq_s32(_d3, _d4);
_t1s2 = vsubq_s32(_d1, _d2);
_t3s4 = vsubq_s32(_d3, _d4);
_o0 = vaddq_s32(_d0, _t1p2);
_o0 = vaddq_s32(_o0, _t3p4);
// _o2
_t1p2 = vmlaq_lane_s32(_t1p2, _t3p4, _tp0, 1);
_o3 = vaddq_s32(_d5, _t1s2);
_o3 = vmlaq_lane_s32(_o3, _t3s4, _tp1, 1);
// _o1
_t1s2 = vmlaq_lane_s32(_t1s2, _t3s4, _tp1, 0);
// save to top blob tm
float32x4_t _scale0 = vdupq_n_f32(scale0);
float32x4_t _out0_f32 = vdupq_n_f32(bias0);
float32x4_t _out1_f32 = vdupq_n_f32(bias0);
float32x4_t _out2_f32 = vdupq_n_f32(bias0);
float32x4_t _out3_f32 = vdupq_n_f32(bias0);
_out0_f32 = vmlaq_f32(_out0_f32, vcvtq_f32_s32(_o0), _scale0);
_out1_f32 = vmlaq_f32(_out1_f32, vcvtq_f32_s32(_t1s2), _scale0);
_out2_f32 = vmlaq_f32(_out2_f32, vcvtq_f32_s32(_t1p2), _scale0);
_out3_f32 = vmlaq_f32(_out3_f32, vcvtq_f32_s32(_o3), _scale0);
vst1q_f32(outRow0, _out0_f32);
vst1q_f32(outRow1, _out1_f32);
vst1q_f32(outRow2, _out2_f32);
vst1q_f32(outRow3, _out3_f32);
#else
int s0[6],s1[6],s2[6],s3[6],s4[6],s5[6];
int w0[6],w1[6],w2[6],w3[6];
int d0[4],d1[4],d2[4],d3[4],d4[4],d5[4];
int o0[4],o1[4],o2[4],o3[4];
// load
for (int n = 0; n < 6; n++)
{
s0[n] = out_tile[n];
s1[n] = out_tile[n+ 6];
s2[n] = out_tile[n+12];
s3[n] = out_tile[n+18];
s4[n] = out_tile[n+24];
s5[n] = out_tile[n+30];
}
// w = A_T * W
for (int n = 0; n < 5; n++)
{
w0[n] = s0[n] + s1[n] + s2[n] + s3[n] + s4[n];
w1[n] = s1[n] - s2[n] + 2*s3[n] - 2*s4[n];
w2[n] = s1[n] + s2[n] + 4*s3[n] + 4*s4[n];
w3[n] = s1[n] - s2[n] + 8*s3[n] - 8*s4[n] + 4*s5[n];
}
for (int n = 5; n < 6; n++)
{
w0[n] = 4*(s0[n] + s1[n] + s2[n] + s3[n] + s4[n]);
w1[n] = 4*(s1[n] - s2[n] + 2*s3[n] - 2*s4[n]);
w2[n] = 4*(s1[n] + s2[n] + 4*s3[n] + 4*s4[n]);
w3[n] = 4*(s1[n] - s2[n] + 8*s3[n] - 8*s4[n] + 4*s5[n]);
}
// transpose w to w_t
{
d0[0] = w0[0]; d0[1] = w1[0]; d0[2] = w2[0]; d0[3] = w3[0];
d1[0] = w0[1]; d1[1] = w1[1]; d1[2] = w2[1]; d1[3] = w3[1];
d2[0] = w0[2]; d2[1] = w1[2]; d2[2] = w2[2]; d2[3] = w3[2];
d3[0] = w0[3]; d3[1] = w1[3]; d3[2] = w2[3]; d3[3] = w3[3];
d4[0] = w0[4]; d4[1] = w1[4]; d4[2] = w2[4]; d4[3] = w3[4];
d5[0] = w0[5]; d5[1] = w1[5]; d5[2] = w2[5]; d5[3] = w3[5];
}
// Y = A_T * w_t
for (int n = 0; n < 4; n++)
{
o0[n] = d0[n] + d1[n] + d2[n] + d3[n] + d4[n];
o1[n] = d1[n] - d2[n] + 2*d3[n] - 2*d4[n];
o2[n] = d1[n] + d2[n] + 4*d3[n] + 4*d4[n];
o3[n] = d1[n] - d2[n] + 8*d3[n] - 8*d4[n] + d5[n];
}
// save to top blob tm
for (int n = 0; n < 4; n++)
{
outRow0[n] = (float)o0[n] * scale0 + bias0;
outRow1[n] = (float)o1[n] * scale0 + bias0;
outRow2[n] = (float)o2[n] * scale0 + bias0;
outRow3[n] = (float)o3[n] * scale0 + bias0;
}
#endif // __ARM_NEON
out_tile += 36;
outRow0 += 4;
outRow1 += 4;
outRow2 += 4;
outRow3 += 4;
}
outRow0 += outw * 3;
outRow1 += outw * 3;
outRow2 += outw * 3;
outRow3 += outw * 3;
}
}
}
// END transform output
// cut result pad
copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt);
}
static void conv3x3s2_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch)
{
kernel_tm.create(8*9, inch, outch/8 + outch%8, (size_t)1u);
const signed char* kernel = _kernel;
int p=0;
for (; p+7<outch; p+=8)
{
const signed char* k0 = kernel + (p+0)*inch*9;
const signed char* k1 = kernel + (p+1)*inch*9;
const signed char* k2 = kernel + (p+2)*inch*9;
const signed char* k3 = kernel + (p+3)*inch*9;
const signed char* k4 = kernel + (p+4)*inch*9;
const signed char* k5 = kernel + (p+5)*inch*9;
const signed char* k6 = kernel + (p+6)*inch*9;
const signed char* k7 = kernel + (p+7)*inch*9;
signed char* ktmp = kernel_tm.channel(p/8);
for (int q=0; q<inch; q++)
{
for (int k=0; k<9; k++)
{
ktmp[0] = k0[k];
ktmp[1] = k1[k];
ktmp[2] = k2[k];
ktmp[3] = k3[k];
ktmp[4] = k4[k];
ktmp[5] = k5[k];
ktmp[6] = k6[k];
ktmp[7] = k7[k];
ktmp += 8;
}
k0 += 9;
k1 += 9;
k2 += 9;
k3 += 9;
k4 += 9;
k5 += 9;
k6 += 9;
k7 += 9;
}
}
for (; p<outch; p++)
{
const signed char* k0 = kernel + (p+0)*inch*9;
signed char* ktmp = kernel_tm.channel(p/8 + p%8);
for (int q=0; q<inch; q++)
{
for (int k=0; k<9; k++)
{
ktmp[k] = k0[k];
}
ktmp += 9;
k0 += 9;
}
}
}
static void conv3x3s2_packed_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;
int nn_outch = outch >> 3;
int remain_outch_start = nn_outch << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 8;
Mat out0 = top_blob.channel(p+0);
Mat out1 = top_blob.channel(p+1);
Mat out2 = top_blob.channel(p+2);
Mat out3 = top_blob.channel(p+3);
Mat out4 = top_blob.channel(p+4);
Mat out5 = top_blob.channel(p+5);
Mat out6 = top_blob.channel(p+6);
Mat out7 = top_blob.channel(p+7);
out0.fill(0);
out1.fill(0);
out2.fill(0);
out3.fill(0);
out4.fill(0);
out5.fill(0);
out6.fill(0);
out7.fill(0);
const signed char* ktmp = _kernel.channel(p/8);
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
int* outptr1 = out1;
int* outptr2 = out2;
int* outptr3 = out3;
int* outptr4 = out4;
int* outptr5 = out5;
int* outptr6 = out6;
int* outptr7 = out7;
const signed char* img0 = bottom_blob.channel(q);
const signed char* r0 = img0;
const signed char* r1 = img0 + w;
const signed char* r2 = img0 + w*2;
int i = 0;
for (; i < outh; i++)
{
#if __ARM_NEON
#if __aarch64__
int nn = outw >> 3;
int remain = outw & 7;
#else
int nn = outw >> 2;
int remain = outw & 3;
#endif // __aarch64__
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"0: \n"
"ld1 {v0.8b, v1.8b, v2.8b}, [%12], #24 \n"//ktmp
"ld2 {v3.8b, v4.8b}, [%9], #16 \n"//r0-r2
"ld2 {v5.8b, v6.8b}, [%9] \n"
"ld1 {v8.4s, v9.4s}, [%1] \n"//out0
"ld1 {v10.4s, v11.4s}, [%2] \n"//out1
"ld1 {v12.4s, v13.4s}, [%3] \n"//out2
"ld1 {v14.4s, v15.4s}, [%4] \n"//out3
"ld1 {v16.4s, v17.4s}, [%5] \n"//out4
"ld1 {v18.4s, v19.4s}, [%6] \n"//out5
"ld1 {v20.4s, v21.4s}, [%7] \n"//out6
"ld1 {v22.4s, v23.4s}, [%8] \n"//out7
"ext v7.8b, v3.8b, v5.8b, #1 \n"
"sshll v0.8h, v0.8b, #0 \n"//(k00-k70)
"sshll v1.8h, v1.8b, #0 \n"//(k01-k71)
"sshll v2.8h, v2.8b, #0 \n"//(k02-k72)
"sshll v3.8h, v3.8b, #0 \n"// r0
"sshll v4.8h, v4.8b, #0 \n"// r1
"sshll v7.8h, v7.8b, #0 \n"// r2
// r0
"smlal v8.4s, v3.4h, v0.h[0] \n"// out0 += (r00-r07)*k00
"smlal2 v9.4s, v3.8h, v0.h[0] \n"
"smlal v10.4s, v3.4h, v0.h[1] \n"// out1 += (r00-r07)*k10
"smlal2 v11.4s, v3.8h, v0.h[1] \n"
"smlal v12.4s, v3.4h, v0.h[2] \n"// out2 += (r00-r07)*k20
"smlal2 v13.4s, v3.8h, v0.h[2] \n"
"smlal v14.4s, v3.4h, v0.h[3] \n"// out3 += (r00-r07)*k30
"smlal2 v15.4s, v3.8h, v0.h[3] \n"
"smlal v16.4s, v3.4h, v0.h[4] \n"// out4 += (r00-r07)*k40
"smlal2 v17.4s, v3.8h, v0.h[4] \n"
"smlal v18.4s, v3.4h, v0.h[5] \n"// out5 += (r00-r07)*k50
"smlal2 v19.4s, v3.8h, v0.h[5] \n"
"smlal v20.4s, v3.4h, v0.h[6] \n"// out6 += (r00-r07)*k60
"smlal2 v21.4s, v3.8h, v0.h[6] \n"
"smlal v22.4s, v3.4h, v0.h[7] \n"// out7 += (r00-r07)*k70
"smlal2 v23.4s, v3.8h, v0.h[7] \n"
// r1
"smlal v8.4s, v4.4h, v1.h[0] \n"// out0 += (r10-r17)*k01
"smlal2 v9.4s, v4.8h, v1.h[0] \n"
"smlal v10.4s, v4.4h, v1.h[1] \n"// out1 += (r10-r17)*k11
"smlal2 v11.4s, v4.8h, v1.h[1] \n"
"smlal v12.4s, v4.4h, v1.h[2] \n"// out2 += (r10-r17)*k21
"smlal2 v13.4s, v4.8h, v1.h[2] \n"
"smlal v14.4s, v4.4h, v1.h[3] \n"// out3 += (r10-r17)*k31
"smlal2 v15.4s, v4.8h, v1.h[3] \n"
"smlal v16.4s, v4.4h, v1.h[4] \n"// out4 += (r10-r17)*k41
"smlal2 v17.4s, v4.8h, v1.h[4] \n"
"smlal v18.4s, v4.4h, v1.h[5] \n"// out5 += (r10-r17)*k51
"smlal2 v19.4s, v4.8h, v1.h[5] \n"
"smlal v20.4s, v4.4h, v1.h[6] \n"// out6 += (r10-r17)*k61
"smlal2 v21.4s, v4.8h, v1.h[6] \n"
"smlal v22.4s, v4.4h, v1.h[7] \n"// out7 += (r10-r17)*k71
"smlal2 v23.4s, v4.8h, v1.h[7] \n"
// r2
"smlal v8.4s, v7.4h, v2.h[0] \n"// out0 += (r20-r27)*k02
"smlal2 v9.4s, v7.8h, v2.h[0] \n"
"smlal v10.4s, v7.4h, v2.h[1] \n"// out1 += (r20-r27)*k12
"smlal2 v11.4s, v7.8h, v2.h[1] \n"
"smlal v12.4s, v7.4h, v2.h[2] \n"// out2 += (r20-r27)*k22
"smlal2 v13.4s, v7.8h, v2.h[2] \n"
"smlal v14.4s, v7.4h, v2.h[3] \n"// out3 += (r20-r27)*k32
"smlal2 v15.4s, v7.8h, v2.h[3] \n"
"smlal v16.4s, v7.4h, v2.h[4] \n"// out4 += (r20-r27)*k42
"smlal2 v17.4s, v7.8h, v2.h[4] \n"
"smlal v18.4s, v7.4h, v2.h[5] \n"// out5 += (r20-r27)*k52
"smlal2 v19.4s, v7.8h, v2.h[5] \n"
"smlal v20.4s, v7.4h, v2.h[6] \n"// out6 += (r20-r27)*k62
"smlal2 v21.4s, v7.8h, v2.h[6] \n"
"smlal v22.4s, v7.4h, v2.h[7] \n"// out7 += (r20-r27)*k72
"smlal2 v23.4s, v7.8h, v2.h[7] \n"
"ld1 {v0.8b, v1.8b, v2.8b}, [%12], #24 \n"//ktmp
"ld2 {v3.8b, v4.8b}, [%10], #16 \n"//r3-r5
"ld2 {v5.8b, v6.8b}, [%10] \n"
"ext v7.8b, v3.8b, v5.8b, #1 \n"
"sshll v0.8h, v0.8b, #0 \n"//(k03-k73)
"sshll v1.8h, v1.8b, #0 \n"//(k04-k74)
"sshll v2.8h, v2.8b, #0 \n"//(k05-k75)
"sshll v3.8h, v3.8b, #0 \n"// r3
"sshll v4.8h, v4.8b, #0 \n"// r4
"sshll v7.8h, v7.8b, #0 \n"// r5
// r3
"smlal v8.4s, v3.4h, v0.h[0] \n"// out0 += (r30-r37)*k03
"smlal2 v9.4s, v3.8h, v0.h[0] \n"
"smlal v10.4s, v3.4h, v0.h[1] \n"// out1 += (r30-r37)*k13
"smlal2 v11.4s, v3.8h, v0.h[1] \n"
"smlal v12.4s, v3.4h, v0.h[2] \n"// out2 += (r30-r37)*k23
"smlal2 v13.4s, v3.8h, v0.h[2] \n"
"smlal v14.4s, v3.4h, v0.h[3] \n"// out3 += (r30-r37)*k33
"smlal2 v15.4s, v3.8h, v0.h[3] \n"
"smlal v16.4s, v3.4h, v0.h[4] \n"// out4 += (r30-r37)*k43
"smlal2 v17.4s, v3.8h, v0.h[4] \n"
"smlal v18.4s, v3.4h, v0.h[5] \n"// out5 += (r30-r37)*k53
"smlal2 v19.4s, v3.8h, v0.h[5] \n"
"smlal v20.4s, v3.4h, v0.h[6] \n"// out6 += (r30-r37)*k63
"smlal2 v21.4s, v3.8h, v0.h[6] \n"
"smlal v22.4s, v3.4h, v0.h[7] \n"// out7 += (r30-r37)*k73
"smlal2 v23.4s, v3.8h, v0.h[7] \n"
// r4
"smlal v8.4s, v4.4h, v1.h[0] \n"// out0 += (r40-r47)*k04
"smlal2 v9.4s, v4.8h, v1.h[0] \n"
"smlal v10.4s, v4.4h, v1.h[1] \n"// out1 += (r40-r47)*k14
"smlal2 v11.4s, v4.8h, v1.h[1] \n"
"smlal v12.4s, v4.4h, v1.h[2] \n"// out2 += (r40-r47)*k24
"smlal2 v13.4s, v4.8h, v1.h[2] \n"
"smlal v14.4s, v4.4h, v1.h[3] \n"// out3 += (r40-r47)*k34
"smlal2 v15.4s, v4.8h, v1.h[3] \n"
"smlal v16.4s, v4.4h, v1.h[4] \n"// out4 += (r40-r47)*k44
"smlal2 v17.4s, v4.8h, v1.h[4] \n"
"smlal v18.4s, v4.4h, v1.h[5] \n"// out5 += (r40-r47)*k54
"smlal2 v19.4s, v4.8h, v1.h[5] \n"
"smlal v20.4s, v4.4h, v1.h[6] \n"// out6 += (r40-r47)*k64
"smlal2 v21.4s, v4.8h, v1.h[6] \n"
"smlal v22.4s, v4.4h, v1.h[7] \n"// out7 += (r40-r47)*k74
"smlal2 v23.4s, v4.8h, v1.h[7] \n"
// r5
"smlal v8.4s, v7.4h, v2.h[0] \n"// out0 += (r50-r57)*k05
"smlal2 v9.4s, v7.8h, v2.h[0] \n"
"smlal v10.4s, v7.4h, v2.h[1] \n"// out1 += (r50-r57)*k15
"smlal2 v11.4s, v7.8h, v2.h[1] \n"
"smlal v12.4s, v7.4h, v2.h[2] \n"// out2 += (r50-r57)*k25
"smlal2 v13.4s, v7.8h, v2.h[2] \n"
"smlal v14.4s, v7.4h, v2.h[3] \n"// out3 += (r50-r57)*k35
"smlal2 v15.4s, v7.8h, v2.h[3] \n"
"smlal v16.4s, v7.4h, v2.h[4] \n"// out4 += (r50-r57)*k45
"smlal2 v17.4s, v7.8h, v2.h[4] \n"
"smlal v18.4s, v7.4h, v2.h[5] \n"// out5 += (r50-r57)*k55
"smlal2 v19.4s, v7.8h, v2.h[5] \n"
"smlal v20.4s, v7.4h, v2.h[6] \n"// out6 += (r50-r57)*k65
"smlal2 v21.4s, v7.8h, v2.h[6] \n"
"smlal v22.4s, v7.4h, v2.h[7] \n"// out7 += (r50-r57)*k75
"smlal2 v23.4s, v7.8h, v2.h[7] \n"
"ld1 {v0.8b, v1.8b, v2.8b}, [%12], #24 \n"//ktmp
"ld2 {v3.8b, v4.8b}, [%11], #16 \n"//r6-r8
"ld2 {v5.8b, v6.8b}, [%11] \n"
"ext v7.8b, v3.8b, v5.8b, #1 \n"
"sshll v0.8h, v0.8b, #0 \n"//(k06-k76)
"sshll v1.8h, v1.8b, #0 \n"//(k07-k77)
"sshll v2.8h, v2.8b, #0 \n"//(k08-k78)
"sshll v3.8h, v3.8b, #0 \n"// r6
"sshll v4.8h, v4.8b, #0 \n"// r7
"sshll v7.8h, v7.8b, #0 \n"// r8
// r6
"smlal v8.4s, v3.4h, v0.h[0] \n"// out0 += (r60-r67)*k06
"smlal2 v9.4s, v3.8h, v0.h[0] \n"
"smlal v10.4s, v3.4h, v0.h[1] \n"// out1 += (r60-r67)*k16
"smlal2 v11.4s, v3.8h, v0.h[1] \n"
"smlal v12.4s, v3.4h, v0.h[2] \n"// out2 += (r60-r67)*k26
"smlal2 v13.4s, v3.8h, v0.h[2] \n"
"smlal v14.4s, v3.4h, v0.h[3] \n"// out3 += (r60-r67)*k36
"smlal2 v15.4s, v3.8h, v0.h[3] \n"
"smlal v16.4s, v3.4h, v0.h[4] \n"// out4 += (r60-r67)*k46
"smlal2 v17.4s, v3.8h, v0.h[4] \n"
"smlal v18.4s, v3.4h, v0.h[5] \n"// out5 += (r60-r67)*k56
"smlal2 v19.4s, v3.8h, v0.h[5] \n"
"smlal v20.4s, v3.4h, v0.h[6] \n"// out6 += (r60-r67)*k66
"smlal2 v21.4s, v3.8h, v0.h[6] \n"
"smlal v22.4s, v3.4h, v0.h[7] \n"// out7 += (r60-r67)*k76
"smlal2 v23.4s, v3.8h, v0.h[7] \n"
// r7
"smlal v8.4s, v4.4h, v1.h[0] \n"// out0 += (r70-r77)*k07
"smlal2 v9.4s, v4.8h, v1.h[0] \n"
"smlal v10.4s, v4.4h, v1.h[1] \n"// out1 += (r70-r77)*k17
"smlal2 v11.4s, v4.8h, v1.h[1] \n"
"smlal v12.4s, v4.4h, v1.h[2] \n"// out2 += (r70-r77)*k27
"smlal2 v13.4s, v4.8h, v1.h[2] \n"
"smlal v14.4s, v4.4h, v1.h[3] \n"// out3 += (r70-r77)*k37
"smlal2 v15.4s, v4.8h, v1.h[3] \n"
"smlal v16.4s, v4.4h, v1.h[4] \n"// out4 += (r70-r77)*k47
"smlal2 v17.4s, v4.8h, v1.h[4] \n"
"smlal v18.4s, v4.4h, v1.h[5] \n"// out5 += (r70-r77)*k57
"smlal2 v19.4s, v4.8h, v1.h[5] \n"
"smlal v20.4s, v4.4h, v1.h[6] \n"// out6 += (r70-r77)*k67
"smlal2 v21.4s, v4.8h, v1.h[6] \n"
"smlal v22.4s, v4.4h, v1.h[7] \n"// out7 += (r70-r77)*k77
"smlal2 v23.4s, v4.8h, v1.h[7] \n"
// r8
"smlal v8.4s, v7.4h, v2.h[0] \n"// out0 += (r80-r87)*k08
"smlal2 v9.4s, v7.8h, v2.h[0] \n"
"smlal v10.4s, v7.4h, v2.h[1] \n"// out1 += (r80-r87)*k18
"smlal2 v11.4s, v7.8h, v2.h[1] \n"
"smlal v12.4s, v7.4h, v2.h[2] \n"// out2 += (r80-r87)*k28
"smlal2 v13.4s, v7.8h, v2.h[2] \n"
"smlal v14.4s, v7.4h, v2.h[3] \n"// out3 += (r80-r87)*k38
"smlal2 v15.4s, v7.8h, v2.h[3] \n"
"smlal v16.4s, v7.4h, v2.h[4] \n"// out4 += (r80-r87)*k48
"smlal2 v17.4s, v7.8h, v2.h[4] \n"
"smlal v18.4s, v7.4h, v2.h[5] \n"// out5 += (r80-r87)*k58
"smlal2 v19.4s, v7.8h, v2.h[5] \n"
"smlal v20.4s, v7.4h, v2.h[6] \n"// out6 += (r80-r87)*k68
"smlal2 v21.4s, v7.8h, v2.h[6] \n"
"smlal v22.4s, v7.4h, v2.h[7] \n"// out7 += (r80-r87)*k78
"smlal2 v23.4s, v7.8h, v2.h[7] \n"
"st1 {v8.4s, v9.4s}, [%1], #32 \n"
"st1 {v10.4s, v11.4s}, [%2], #32 \n"
"st1 {v12.4s, v13.4s}, [%3], #32 \n"
"st1 {v14.4s, v15.4s}, [%4], #32 \n"
"st1 {v16.4s, v17.4s}, [%5], #32 \n"
"st1 {v18.4s, v19.4s}, [%6], #32 \n"
"st1 {v20.4s, v21.4s}, [%7], #32 \n"
"st1 {v22.4s, v23.4s}, [%8], #32 \n"
"subs %w0, %w0, #1 \n"
"sub %12, %12, #72 \n"// reset ktmp
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(outptr4), // %5
"=r"(outptr5), // %6
"=r"(outptr6), // %7
"=r"(outptr7), // %8
"=r"(r0), // %9
"=r"(r1), // %10
"=r"(r2), // %11
"=r"(ktmp) // %12
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(outptr4),
"6"(outptr5),
"7"(outptr6),
"8"(outptr7),
"9"(r0),
"10"(r1),
"11"(r2),
"12"(ktmp)
: "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"
);
}
#else // __aarch64__
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%1, #128] \n"
"vld1.s32 {d16-d17}, [%1] \n"// out0
"pld [%2, #128] \n"
"vld1.s32 {d18-d19}, [%2] \n"// out1
"pld [%3, #128] \n"
"vld1.s32 {d20-d21}, [%3] \n"// out2
"pld [%4, #128] \n"
"vld1.s32 {d22-d23}, [%4] \n"// out3
// r0
"pld [%9, #64] \n"
"vld2.s8 {d8-d9}, [%9] \n"// d8(a00 a02 a04 a06 a08 a010 a012 a014), d9(a01 a03 a05 a07 a09 a011 a013 a015)
"add %9, #8 \n"
"pld [%12, #64] \n"
"vld1.s8 {d0-d2}, [%12]! \n"// d0(k00-k70) d1(k01-k71) d2(k02-k72)
"pld [%5, #128] \n"
"vld1.s32 {d24-d25}, [%5] \n"// out4
"pld [%6, #128] \n"
"vld1.s32 {d26-d27}, [%6] \n"// out5
"vmovl.s8 q2, d2 \n"// q2(k02-k72)
"vmovl.s8 q1, d1 \n"// q1(k01-k71)
"vmovl.s8 q0, d0 \n"// q0(k00-k70)
"vext.s8 d12, d8, d8, #1 \n"// d12(a02 a04 a06 a08 x x x x)
"pld [%7, #128] \n"
"vld1.s32 {d28-d29}, [%7] \n"// out6
"vmovl.s8 q5, d9 \n"// q5(a01 a03 a05 a07 a09 a011 a013 a015) d11
"vmovl.s8 q4, d8 \n"// q4(a00 a02 a04 a06 a08 a010 a012 a014) d9
"vmovl.s8 q6, d12 \n"// q6(a02 a04 a06 a08 a010 a012 a014 a016) d13
"pld [%8, #128] \n"
"vld1.s32 {d30-d31}, [%8] \n"// out7
"vmlal.s16 q8, d8, d0[0] \n"// sum0 += (a00 a02 a04 a06) * k00
"vmlal.s16 q9, d8, d0[1] \n"// sum1 += (a00 a02 a04 a06) * k10
"vmlal.s16 q10, d8, d0[2] \n"// sum2 += (a00 a02 a04 a06) * k20
"vmlal.s16 q11, d8, d0[3] \n"// sum3 += (a00 a02 a04 a06) * k30
"vmlal.s16 q12, d8, d1[0] \n"// sum4 += (a00 a02 a04 a06) * k40
"vmlal.s16 q13, d8, d1[1] \n"// sum5 += (a00 a02 a04 a06) * k50
"vmlal.s16 q14, d8, d1[2] \n"// sum6 += (a00 a02 a04 a06) * k60
"vmlal.s16 q15, d8, d1[3] \n"// sum7 += (a00 a02 a04 a06) * k70
"vmlal.s16 q8, d10, d2[0] \n"// sum0 += (a01-a07) * k01
"vmlal.s16 q9, d10, d2[1] \n"// sum1 += (a01-a07) * k11
"vmlal.s16 q10, d10, d2[2] \n"// sum2 += (a01-a07) * k21
"vmlal.s16 q11, d10, d2[3] \n"// sum3 += (a01-a07) * k31
"vmlal.s16 q12, d10, d3[0] \n"// sum4 += (a01-a07) * k41
"vmlal.s16 q13, d10, d3[1] \n"// sum5 += (a01-a07) * k51
"vmlal.s16 q14, d10, d3[2] \n"// sum6 += (a01-a07) * k61
"vmlal.s16 q15, d10, d3[3] \n"// sum7 += (a01-a07) * k71
"pld [%10, #64] \n"
"vld2.s8 {d8-d9}, [%10] \n"// d8(a10 a12 a14 a16 a18 a110 a112 a114), d9(a11 a13 a15 a17 a19 a111 a113 a115)
"add %10, #8 \n"
"vmlal.s16 q8, d12, d4[0] \n"// sum0 += (a02-a08) * k02
"vmlal.s16 q9, d12, d4[1] \n"// sum1 += (a02-a08) * k12
"vmlal.s16 q10, d12, d4[2] \n"// sum2 += (a02-a08) * k22
"vmlal.s16 q11, d12, d4[3] \n"// sum3 += (a02-a08) * k32
"pld [%12, #64] \n"
"vld1.s8 {d0-d2}, [%12]! \n"// d0(k03-k73) d1(k04-k74) d2(k05-k75)
"vmlal.s16 q12, d12, d5[0] \n"// sum4 += (a02-a08) * k42
"vmlal.s16 q13, d12, d5[1] \n"// sum5 += (a02-a08) * k52
"vmlal.s16 q14, d12, d5[2] \n"// sum6 += (a02-a08) * k62
"vmlal.s16 q15, d12, d5[3] \n"// sum7 += (a02-a08) * k72
// r1
"vext.s8 d12, d8, d8, #1 \n"// d12(a12 a14 a16 a18 x x x x)
"vmovl.s8 q2, d2 \n"// q2(k05-k75)
"vmovl.s8 q1, d1 \n"// q1(k04-k74)
"vmovl.s8 q0, d0 \n"// q0(k03-k73)
"vmovl.s8 q5, d9 \n"// q5(a11-a115)
"vmovl.s8 q4, d8 \n"// q4(a10-a114)
"vmovl.s8 q6, d12 \n"// q6(a12-a116)
"vmlal.s16 q8, d8, d0[0] \n"// sum0 += (a10-a16) * k03
"vmlal.s16 q9, d8, d0[1] \n"// sum1 += (a10-a16) * k13
"vmlal.s16 q10, d8, d0[2] \n"// sum2 += (a10-a16) * k23
"vmlal.s16 q11, d8, d0[3] \n"// sum3 += (a10-a16) * k33
"vmlal.s16 q12, d8, d1[0] \n"// sum4 += (a10-a16) * k43
"vmlal.s16 q13, d8, d1[1] \n"// sum5 += (a10-a16) * k53
"vmlal.s16 q14, d8, d1[2] \n"// sum6 += (a10-a16) * k63
"vmlal.s16 q15, d8, d1[3] \n"// sum7 += (a10-a16) * k73
"vmlal.s16 q8, d10, d2[0] \n"// sum0 += (a11-a17) * k04
"vmlal.s16 q9, d10, d2[1] \n"// sum1 += (a11-a17) * k14
"vmlal.s16 q10, d10, d2[2] \n"// sum2 += (a11-a17) * k24
"vmlal.s16 q11, d10, d2[3] \n"// sum3 += (a11-a17) * k34
"vmlal.s16 q12, d10, d3[0] \n"// sum4 += (a11-a17) * k44
"vmlal.s16 q13, d10, d3[1] \n"// sum5 += (a11-a17) * k54
"vmlal.s16 q14, d10, d3[2] \n"// sum6 += (a11-a17) * k64
"vmlal.s16 q15, d10, d3[3] \n"// sum7 += (a11-a17) * k74
"pld [%11, #64] \n"
"vld2.s8 {d8-d9}, [%11] \n"// d8(a20 a22 a24 a26 a28 a210 a212 a214), d9(a21 a23 a25 a27 a29 a211 a213 a215)
"add %11, #8 \n"
"vmlal.s16 q8, d12, d4[0] \n"// sum0 += (a12-a18) * k05
"vmlal.s16 q9, d12, d4[1] \n"// sum1 += (a12-a18) * k15
"vmlal.s16 q10, d12, d4[2] \n"// sum2 += (a12-a18) * k25
"vmlal.s16 q11, d12, d4[3] \n"// sum3 += (a12-a18) * k35
"pld [%12, #64] \n"
"vld1.s8 {d0-d2}, [%12]! \n"// d0(k06-k76) d1(k07-k77) d2(k08-k78)
"vmlal.s16 q12, d12, d5[0] \n"// sum4 += (a12-a18) * k45
"vmlal.s16 q13, d12, d5[1] \n"// sum5 += (a12-a18) * k55
"vmlal.s16 q14, d12, d5[2] \n"// sum6 += (a12-a18) * k65
"vmlal.s16 q15, d12, d5[3] \n"// sum7 += (a12-a18) * k75
// r2
"vext.s8 d12, d8, d8, #1 \n"// d12(a22 a24 a26 a28 x x x x)
"vmovl.s8 q2, d2 \n"// q2(k08-k78)
"vmovl.s8 q1, d1 \n"// q1(k07-k77)
"vmovl.s8 q0, d0 \n"// q0(k06-k76)
"vmovl.s8 q5, d9 \n"// q5(a21-a215)
"vmovl.s8 q4, d8 \n"// q4(a20-a214)
"vmovl.s8 q6, d12 \n"// q6(a22-a216)
"vmlal.s16 q8, d8, d0[0] \n"// sum0 += (a20-a26) * k06
"vmlal.s16 q9, d8, d0[1] \n"// sum1 += (a20-a26) * k16
"vmlal.s16 q10, d8, d0[2] \n"// sum2 += (a20-a26) * k26
"vmlal.s16 q11, d8, d0[3] \n"// sum3 += (a20-a26) * k36
"vmlal.s16 q12, d8, d1[0] \n"// sum4 += (a20-a26) * k46
"vmlal.s16 q13, d8, d1[1] \n"// sum5 += (a20-a26) * k56
"vmlal.s16 q14, d8, d1[2] \n"// sum6 += (a20-a26) * k66
"vmlal.s16 q15, d8, d1[3] \n"// sum7 += (a20-a26) * k76
"vmlal.s16 q8, d10, d2[0] \n"// sum0 += (a21-a27) * k07
"vmlal.s16 q9, d10, d2[1] \n"// sum1 += (a21-a27) * k17
"vmlal.s16 q10, d10, d2[2] \n"// sum2 += (a21-a27) * k27
"vmlal.s16 q11, d10, d2[3] \n"// sum3 += (a21-a27) * k37
"vmlal.s16 q12, d10, d3[0] \n"// sum4 += (a21-a27) * k47
"vmlal.s16 q13, d10, d3[1] \n"// sum5 += (a21-a27) * k57
"vmlal.s16 q14, d10, d3[2] \n"// sum6 += (a21-a27) * k67
"vmlal.s16 q15, d10, d3[3] \n"// sum7 += (a21-a27) * k77
"vmlal.s16 q8, d12, d4[0] \n"// sum0 += (a22-a28) * k08
"vmlal.s16 q9, d12, d4[1] \n"// sum1 += (a22-a28) * k18
"vmlal.s16 q10, d12, d4[2] \n"// sum2 += (a22-a28) * k28
"vmlal.s16 q11, d12, d4[3] \n"// sum3 += (a22-a28) * k38
"vmlal.s16 q12, d12, d5[0] \n"// sum4 += (a22-a28) * k48
"vmlal.s16 q13, d12, d5[1] \n"// sum5 += (a22-a28) * k58
"vmlal.s16 q14, d12, d5[2] \n"// sum6 += (a22-a28) * k68
"vmlal.s16 q15, d12, d5[3] \n"// sum7 += (a22-a28) * k78
// save s32 to memory
"sub %12, %12, #72 \n"
"vst1.s32 {d16-d17}, [%1]! \n"// out0
"vst1.s32 {d18-d19}, [%2]! \n"// out1
"vst1.s32 {d20-d21}, [%3]! \n"// out2
"vst1.s32 {d22-d23}, [%4]! \n"// out3
"subs %0, #1 \n"
"vst1.s32 {d24-d25}, [%5]! \n"// out4
"vst1.s32 {d26-d27}, [%6]! \n"// out5
"vst1.s32 {d28-d29}, [%7]! \n"// out6
"vst1.s32 {d30-d31}, [%8]! \n"// out7
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(outptr4), // %5
"=r"(outptr5), // %6
"=r"(outptr6), // %7
"=r"(outptr7), // %8
"=r"(r0), // %9
"=r"(r1), // %10
"=r"(r2), // %11
"=r"(ktmp) // %12
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(outptr4),
"6"(outptr5),
"7"(outptr6),
"8"(outptr7),
"9"(r0),
"10"(r1),
"11"(r2),
"12"(ktmp)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain>0; remain--)
{
#if __ARM_NEON
#if __aarch64__
int8x8_t _r0_s8 = vld1_s8(r0);// (a00 a01 a02 ....)
int8x8_t _r1_s8 = vld1_s8(r1);// (a10 a11 a12 ....)
int8x8_t _r2_s8 = vld1_s8(r2);// (a20 a21 a22 ....)
int16x8_t _r0 = vmovl_s8(_r0_s8);
int16x8_t _r1 = vmovl_s8(_r1_s8);
int16x8_t _r2 = vmovl_s8(_r2_s8);
int32x4_t _sum03, _sum47;
_sum03 = vld1q_lane_s32(outptr0, _sum03, 0);// out0
_sum03 = vld1q_lane_s32(outptr1, _sum03, 1);// out1
_sum03 = vld1q_lane_s32(outptr2, _sum03, 2);// out2
_sum03 = vld1q_lane_s32(outptr3, _sum03, 3);// out3
_sum47 = vld1q_lane_s32(outptr4, _sum47, 0);// out4
_sum47 = vld1q_lane_s32(outptr5, _sum47, 1);// out5
_sum47 = vld1q_lane_s32(outptr6, _sum47, 2);// out6
_sum47 = vld1q_lane_s32(outptr7, _sum47, 3);// out7
// k0 - k2
int8x8_t _k0_8 = vld1_s8(ktmp); //(k00-k70)
int8x8_t _k1_8 = vld1_s8(ktmp+8); //(k01-k71)
int8x8_t _k2_8 = vld1_s8(ktmp+16); //(k02-k72)
int16x8_t _k0 = vmovl_s8(_k0_8);
int16x8_t _k1 = vmovl_s8(_k1_8);
int16x8_t _k2 = vmovl_s8(_k2_8);
int32x4_t _sum0 = vmull_laneq_s16(vget_low_s16(_k0), _r0, 0);
int32x4_t _sum0n = vmull_laneq_s16(vget_high_s16(_k0), _r0, 0);
int32x4_t _sum1 = vmull_laneq_s16(vget_low_s16(_k1), _r0, 1);
int32x4_t _sum1n = vmull_laneq_s16(vget_high_s16(_k1), _r0, 1);
_sum03 = vmlal_laneq_s16(_sum03, vget_low_s16(_k2), _r0, 2);
_sum47 = vmlal_laneq_s16(_sum47, vget_high_s16(_k2), _r0, 2);
// k3 - k5
_k0_8 = vld1_s8(ktmp+24); //(k03-k73)
_k1_8 = vld1_s8(ktmp+32); //(k04-k74)
_k2_8 = vld1_s8(ktmp+40); //(k05-k75)
_k0 = vmovl_s8(_k0_8);
_k1 = vmovl_s8(_k1_8);
_k2 = vmovl_s8(_k2_8);
_sum0 = vmlal_laneq_s16(_sum0, vget_low_s16(_k0), _r1, 0);
_sum0n = vmlal_laneq_s16(_sum0n, vget_high_s16(_k0), _r1, 0);
_sum1 = vmlal_laneq_s16(_sum1, vget_low_s16(_k1), _r1, 1);
_sum1n = vmlal_laneq_s16(_sum1n, vget_high_s16(_k1), _r1, 1);
_sum03 = vmlal_laneq_s16(_sum03, vget_low_s16(_k2), _r1, 2);
_sum47 = vmlal_laneq_s16(_sum47, vget_high_s16(_k2), _r1, 2);
// k6 - k8
_k0_8 = vld1_s8(ktmp+48); //(k06-k76)
_k1_8 = vld1_s8(ktmp+56); //(k07-k77)
_k2_8 = vld1_s8(ktmp+64); //(k08-k78)
_k0 = vmovl_s8(_k0_8);
_k1 = vmovl_s8(_k1_8);
_k2 = vmovl_s8(_k2_8);
_sum0 = vmlal_laneq_s16(_sum0, vget_low_s16(_k0), _r2, 0);
_sum0n = vmlal_laneq_s16(_sum0n, vget_high_s16(_k0), _r2, 0);
_sum1 = vmlal_laneq_s16(_sum1, vget_low_s16(_k1), _r2, 1);
_sum1n = vmlal_laneq_s16(_sum1n, vget_high_s16(_k1), _r2, 1);
_sum03 = vmlal_laneq_s16(_sum03, vget_low_s16(_k2), _r2, 2);
_sum47 = vmlal_laneq_s16(_sum47, vget_high_s16(_k2), _r2, 2);
_sum0 = vaddq_s32(_sum0, _sum1);
_sum0n = vaddq_s32(_sum0n, _sum1n);
_sum03 = vaddq_s32(_sum03, _sum0);
_sum47 = vaddq_s32(_sum47, _sum0n);
vst1q_lane_s32(outptr0, _sum03, 0);
vst1q_lane_s32(outptr1, _sum03, 1);
vst1q_lane_s32(outptr2, _sum03, 2);
vst1q_lane_s32(outptr3, _sum03, 3);
vst1q_lane_s32(outptr4, _sum47, 0);
vst1q_lane_s32(outptr5, _sum47, 1);
vst1q_lane_s32(outptr6, _sum47, 2);
vst1q_lane_s32(outptr7, _sum47, 3);
outptr0++;
outptr1++;
outptr2++;
outptr3++;
outptr4++;
outptr5++;
outptr6++;
outptr7++;
#else // __aarch64__
asm volatile(
"pld [%8, #64] \n"
"vld1.s8 {d0}, [%8] \n"// d0(a00 a01 a02 ....)
"pld [%9, #64] \n"
"vld1.s8 {d2}, [%9] \n"// d2(a10 a11 a12 ....)
"pld [%10, #64] \n"
"vld1.s8 {d4}, [%10] \n"// d4(a20 a21 a22 ....)
"pld [%11, #64] \n"
"vld1.s8 {d6-d8}, [%11]! \n"// d6(k00-k70) d7(k01-k71) d8(k02-k72)
"vmovl.s8 q0, d0 \n"// d0(a00 a01 a02 x)
"vmovl.s8 q1, d2 \n"// d2(a10 a11 a12 x)
"vmovl.s8 q2, d4 \n"// d4(a20 a21 a22 x)
"vmovl.s8 q5, d8 \n"// d10(k02-k32) d11(k42-k72)
"vmovl.s8 q4, d7 \n"// d8(k01-k31) d9(k41-k71)
"vmovl.s8 q3, d6 \n"// d6(k00-k30) d7(k40-k70)
"vld1.s32 {d20[0]}, [%0] \n"// out0 q10
"vld1.s32 {d20[1]}, [%1] \n"// out1
"vld1.s32 {d21[0]}, [%2] \n"// out2
"vld1.s32 {d21[1]}, [%3] \n"// out3
"pld [%11, #64] \n"
"vld1.s8 {d24-d26}, [%11]! \n"
"vmovl.s8 q14, d26 \n"// d28(k05-k35) d29(k45-k75)
"vmovl.s8 q13, d25 \n"// d26(k04-k34) d27(k44-k74)
"vmovl.s8 q12, d24 \n"// d24(k03-k33) d25(k43-k73)
"vld1.s32 {d22[0]}, [%4] \n"// out4 q11
"vld1.s32 {d22[1]}, [%5] \n"// out5
"vld1.s32 {d23[0]}, [%6] \n"// out6
"vld1.s32 {d23[1]}, [%7] \n"// out7
"vmull.s16 q6, d6, d0[0] \n"// a00 x (k00-k30)
"vmull.s16 q7, d7, d0[0] \n"// a00 x (k40-k70)
"vmull.s16 q8, d8, d0[1] \n"// a01 x (k01-k31)
"vmull.s16 q9, d9, d0[1] \n"// a01 x (k41-k71)
"vmlal.s16 q10, d10, d0[2] \n"// a02 x (k02-k32)
"vmlal.s16 q11, d11, d0[2] \n"// a02 x (k42-k72)
"pld [%11, #64] \n"
"vld1.s8 {d6-d8}, [%11]! \n"
"vmovl.s8 q5, d8 \n"// d10(k08-k38) d11(k48-k78)
"vmovl.s8 q4, d7 \n"// d8(k07-k37) d9(k47-k77)
"vmovl.s8 q3, d6 \n"// d6(k06-k36) d7(k46-k76)
"vmlal.s16 q6, d24, d2[0] \n"// a10 x (k03-k33)
"vmlal.s16 q7, d25, d2[0] \n"// a10 x (k43-k73)
"vmlal.s16 q8, d26, d2[1] \n"// a11 x (k04-k34)
"vmlal.s16 q9, d27, d2[1] \n"// a11 x (k44-k74)
"vmlal.s16 q10, d28, d2[2] \n"// a12 x (k05-k35)
"vmlal.s16 q11, d29, d2[2] \n"// a12 x (k45-k75)
"vmlal.s16 q6, d6, d4[0] \n"// a20 x (k06-k36)
"vmlal.s16 q7, d7, d4[0] \n"// a20 x (k46-k76)
"vmlal.s16 q8, d8, d4[1] \n"// a21 x (k07-k37)
"vmlal.s16 q9, d9, d4[1] \n"// a21 x (k47-k77)
"vmlal.s16 q10, d10, d4[2] \n"// a22 x (k08-k38)
"vmlal.s16 q11, d11, d4[2] \n"// a22 x (k48-k78)
"vadd.s32 q8, q8, q6 \n"
"vadd.s32 q9, q9, q7 \n"
"sub %11, %11, #72 \n"
"vadd.s32 q10, q10, q8 \n"
"vadd.s32 q11, q11, q9 \n"
"vst1.s32 {d20[0]}, [%0]! \n"// out0
"vst1.s32 {d20[1]}, [%1]! \n"// out1
"vst1.s32 {d21[0]}, [%2]! \n"// out2
"vst1.s32 {d21[1]}, [%3]! \n"// out3
"vst1.s32 {d22[0]}, [%4]! \n"// out4
"vst1.s32 {d22[1]}, [%5]! \n"// out5
"vst1.s32 {d23[0]}, [%6]! \n"// out6
"vst1.s32 {d23[1]}, [%7]! \n"// out7
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(outptr4), // %4
"=r"(outptr5), // %5
"=r"(outptr6), // %6
"=r"(outptr7), // %7
"=r"(r0), // %8
"=r"(r1), // %9
"=r"(r2), // %10
"=r"(ktmp) // %11
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(outptr4),
"5"(outptr5),
"6"(outptr6),
"7"(outptr7),
"8"(r0),
"9"(r1),
"10"(r2),
"11"(ktmp)
: "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
#endif // __aarch64__
#else // __ARM_NEON
int sum0 = 0;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
int sum4 = 0;
int sum5 = 0;
int sum6 = 0;
int sum7 = 0;
sum0 += (int)r0[0] * ktmp[0];
sum1 += (int)r0[0] * ktmp[1];
sum2 += (int)r0[0] * ktmp[2];
sum3 += (int)r0[0] * ktmp[3];
sum4 += (int)r0[0] * ktmp[4];
sum5 += (int)r0[0] * ktmp[5];
sum6 += (int)r0[0] * ktmp[6];
sum7 += (int)r0[0] * ktmp[7];
ktmp += 8;
sum0 += (int)r0[1] * ktmp[0];
sum1 += (int)r0[1] * ktmp[1];
sum2 += (int)r0[1] * ktmp[2];
sum3 += (int)r0[1] * ktmp[3];
sum4 += (int)r0[1] * ktmp[4];
sum5 += (int)r0[1] * ktmp[5];
sum6 += (int)r0[1] * ktmp[6];
sum7 += (int)r0[1] * ktmp[7];
ktmp += 8;
sum0 += (int)r0[2] * ktmp[0];
sum1 += (int)r0[2] * ktmp[1];
sum2 += (int)r0[2] * ktmp[2];
sum3 += (int)r0[2] * ktmp[3];
sum4 += (int)r0[2] * ktmp[4];
sum5 += (int)r0[2] * ktmp[5];
sum6 += (int)r0[2] * ktmp[6];
sum7 += (int)r0[2] * ktmp[7];
ktmp += 8;
sum0 += (int)r1[0] * ktmp[0];
sum1 += (int)r1[0] * ktmp[1];
sum2 += (int)r1[0] * ktmp[2];
sum3 += (int)r1[0] * ktmp[3];
sum4 += (int)r1[0] * ktmp[4];
sum5 += (int)r1[0] * ktmp[5];
sum6 += (int)r1[0] * ktmp[6];
sum7 += (int)r1[0] * ktmp[7];
ktmp += 8;
sum0 += (int)r1[1] * ktmp[0];
sum1 += (int)r1[1] * ktmp[1];
sum2 += (int)r1[1] * ktmp[2];
sum3 += (int)r1[1] * ktmp[3];
sum4 += (int)r1[1] * ktmp[4];
sum5 += (int)r1[1] * ktmp[5];
sum6 += (int)r1[1] * ktmp[6];
sum7 += (int)r1[1] * ktmp[7];
ktmp += 8;
sum0 += (int)r1[2] * ktmp[0];
sum1 += (int)r1[2] * ktmp[1];
sum2 += (int)r1[2] * ktmp[2];
sum3 += (int)r1[2] * ktmp[3];
sum4 += (int)r1[2] * ktmp[4];
sum5 += (int)r1[2] * ktmp[5];
sum6 += (int)r1[2] * ktmp[6];
sum7 += (int)r1[2] * ktmp[7];
ktmp += 8;
sum0 += (int)r2[0] * ktmp[0];
sum1 += (int)r2[0] * ktmp[1];
sum2 += (int)r2[0] * ktmp[2];
sum3 += (int)r2[0] * ktmp[3];
sum4 += (int)r2[0] * ktmp[4];
sum5 += (int)r2[0] * ktmp[5];
sum6 += (int)r2[0] * ktmp[6];
sum7 += (int)r2[0] * ktmp[7];
ktmp += 8;
sum0 += (int)r2[1] * ktmp[0];
sum1 += (int)r2[1] * ktmp[1];
sum2 += (int)r2[1] * ktmp[2];
sum3 += (int)r2[1] * ktmp[3];
sum4 += (int)r2[1] * ktmp[4];
sum5 += (int)r2[1] * ktmp[5];
sum6 += (int)r2[1] * ktmp[6];
sum7 += (int)r2[1] * ktmp[7];
ktmp += 8;
sum0 += (int)r2[2] * ktmp[0];
sum1 += (int)r2[2] * ktmp[1];
sum2 += (int)r2[2] * ktmp[2];
sum3 += (int)r2[2] * ktmp[3];
sum4 += (int)r2[2] * ktmp[4];
sum5 += (int)r2[2] * ktmp[5];
sum6 += (int)r2[2] * ktmp[6];
sum7 += (int)r2[2] * ktmp[7];
ktmp += 8;
*outptr0 += sum0;
*outptr1 += sum1;
*outptr2 += sum2;
*outptr3 += sum3;
*outptr4 += sum4;
*outptr5 += sum5;
*outptr6 += sum6;
*outptr7 += sum7;
ktmp -= 8*9;
outptr0++;
outptr1++;
outptr2++;
outptr3++;
outptr4++;
outptr5++;
outptr6++;
outptr7++;
#endif // __ARM_NEON
r0 += 2;
r1 += 2;
r2 += 2;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
ktmp += 8*9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out = top_blob.channel(p);
out.fill(0);
const signed char* ktmp = _kernel.channel(p/8 + p%8);
for (int q=0; q<inch; q++)
{
int* outptr = out;
const signed char* img0 = bottom_blob.channel(q);
const signed char* r0 = img0;
const signed char* r1 = img0 + w;
const signed char* r2 = img0 + w*2;
int i = 0;
for (; i < outh; i++)
{
#if __ARM_NEON
int nn = outw >> 3;
int remain = outw & 7;
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"0: \n"
"ld1 {v0.8b, v1.8b}, [%5] \n"//ktmp
"ld2 {v2.8b, v3.8b}, [%2], #16 \n"//r0-r2
"ld2 {v4.8b, v5.8b}, [%2] \n"
"ld2 {v6.8b, v7.8b}, [%3], #16 \n"//r3-r5
"ld2 {v8.8b, v9.8b}, [%3] \n"
"ld2 {v10.8b, v11.8b}, [%4], #16 \n"//r6-r8
"ld2 {v12.8b, v13.8b}, [%4] \n"
"ld1 {v14.4s, v15.4s}, [%1] \n"//out0
"ext v4.8b, v2.8b, v4.8b, #1 \n"
"ext v8.8b, v6.8b, v8.8b, #1 \n"
"ext v12.8b, v10.8b, v12.8b, #1 \n"
"sshll v0.8h, v0.8b, #0 \n"//(k0-k7)
"sshll v1.8h, v1.8b, #0 \n"//(k8)
"sshll v2.8h, v2.8b, #0 \n"// r0
"sshll v3.8h, v3.8b, #0 \n"// r1
"sshll v4.8h, v4.8b, #0 \n"// r2
"sshll v6.8h, v6.8b, #0 \n"// r3
"sshll v7.8h, v7.8b, #0 \n"// r4
"sshll v8.8h, v8.8b, #0 \n"// r5
"sshll v10.8h, v10.8b, #0 \n"// r6
"sshll v11.8h, v11.8b, #0 \n"// r7
"sshll v12.8h, v12.8b, #0 \n"// r8
// r0
"smull v16.4s, v2.4h, v0.h[0] \n"// out = r0*k0
"smull2 v17.4s, v2.8h, v0.h[0] \n"
"smull v18.4s, v3.4h, v0.h[1] \n"// outn = r1*k1
"smull2 v19.4s, v3.8h, v0.h[1] \n"
"smlal v16.4s, v4.4h, v0.h[2] \n"// out = r2*k2
"smlal2 v17.4s, v4.8h, v0.h[2] \n"
"smlal v18.4s, v6.4h, v0.h[3] \n"// outn = r3*k3
"smlal2 v19.4s, v6.8h, v0.h[3] \n"
"smlal v16.4s, v7.4h, v0.h[4] \n"// out = r4*k4
"smlal2 v17.4s, v7.8h, v0.h[4] \n"
"smlal v18.4s, v8.4h, v0.h[5] \n"// outn = r5*k5
"smlal2 v19.4s, v8.8h, v0.h[5] \n"
"smlal v16.4s, v10.4h, v0.h[6] \n"// out = r6*k6
"smlal2 v17.4s, v10.8h, v0.h[6] \n"
"smlal v18.4s, v11.4h, v0.h[7] \n"// outn = r7*k7
"smlal2 v19.4s, v11.8h, v0.h[7] \n"
"smlal v16.4s, v12.4h, v1.h[0] \n"// out = r8*k8
"smlal2 v17.4s, v12.8h, v1.h[0] \n"
"add v8.4s, v16.4s, v18.4s \n"
"add v9.4s, v17.4s, v19.4s \n"
"st1 {v8.4s, v9.4s}, [%1], #32 \n"
"subs %w0, %w0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2), // %4
"=r"(ktmp) // %5
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"5"(ktmp)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19"
);
}
#else
if (nn > 0)
{
asm volatile(
"vld1.s8 {d0-d1}, [%5] \n"// d0(k0 - k7) d1(k8 ...)
"vmovl.s8 q1, d1 \n"// d2(k8 ...)
"vmovl.s8 q0, d0 \n"// d0(k0 - k3) d1(k4 - k7)
"0: \n"
"pld [%2, #192] \n"
"vld2.s8 {d4-d5}, [%2]! \n"// r0 d4(a00 a02 ... a014) d5(a01 a03 ... a015)
"vld2.s8 {d8-d9}, [%2] \n"// d8(a016 ....)
"vld2.s8 {d10-d11}, [%3]! \n"// r1 d10(a10 a12 ... a114) d11(a11 a13 ... a115)
"vld2.s8 {d14-d15}, [%3] \n"// d14(a116 ....)
"vld2.s8 {d16-d17}, [%4]! \n"// r2 d16(a20 a22 ... a214) d17(a21 a23 ... a215)
"vld2.s8 {d20-d21}, [%4] \n"// d20(a216 ....)
"vld1.s32 {d22-d25}, [%1] \n"// q11(out0 - out3) q12(out4 - out7)
"vext.s8 d8, d4, d8, #1 \n"// d8(a02 a04 ... a016)
"vext.s8 d14, d10, d14, #1 \n"// d14(a12 a14 ... a116)
"vext.s8 d20, d16, d20, #1 \n"// d20(a22 a24 ... a216)
"vmovl.s8 q3, d5 \n"// q3(a01 a03 ... a015)
"vmovl.s8 q2, d4 \n"// q2(a00 a02 ... a014)
"vmovl.s8 q4, d8 \n"// q4(a02 a04 ... a016)
"vmovl.s8 q6, d11 \n"// q6(a11 a13 ... a115)
"vmovl.s8 q5, d10 \n"// q5(a10 a12 ... a114)
"vmovl.s8 q7, d14 \n"// q7(a12 a14 ... a116)
"vmovl.s8 q9, d17 \n"// q9(a21 a23 ... a215)
"vmovl.s8 q8, d16 \n"// q8(a20 a22 ... a214)
"vmovl.s8 q10, d20 \n"// q10(a22 a24 ... a216)
"vmlal.s16 q11, d4, d0[0] \n"// k0
"vmlal.s16 q12, d5, d0[0] \n"
"vmull.s16 q13, d6, d0[1] \n"// k1
"vmull.s16 q14, d7, d0[1] \n"
"vmlal.s16 q11, d8, d0[2] \n"// k2
"vmlal.s16 q12, d9, d0[2] \n"
"vmlal.s16 q13, d12, d1[0] \n"// k4
"vmlal.s16 q14, d13, d1[0] \n"
"vmlal.s16 q11, d10, d0[3] \n"// k3
"vmlal.s16 q12, d11, d0[3] \n"
"vmlal.s16 q13, d14, d1[1] \n"// k5
"vmlal.s16 q14, d15, d1[1] \n"
"vmlal.s16 q11, d16, d1[2] \n"// k6
"vmlal.s16 q12, d17, d1[2] \n"
"vmlal.s16 q13, d18, d1[3] \n"// k7
"vmlal.s16 q14, d19, d1[3] \n"
"vmlal.s16 q11, d20, d2[0] \n"// k8
"vmlal.s16 q12, d21, d2[0] \n"
"vadd.s32 q11, q11, q13 \n"
"vadd.s32 q12, q12, q14 \n"
"vst1.32 {d22-d25}, [%1]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2), // %4
"=r"(ktmp) // %5
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"5"(ktmp)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
#endif // __aarch64__
#endif // __ARM_NEON
if (remain > 0)
{
#if __ARM_NEON
int8x8_t _k01234567s8 = vld1_s8(ktmp);
int8x8_t _k8xxxxxxxs8 = vld1_s8(ktmp+8);
int8x8_t _k34567xxxs8 = vext_s8(_k01234567s8, _k01234567s8, 3);
int8x8_t _k678xxxxxs8 = vext_s8(_k01234567s8, _k8xxxxxxxs8, 6);
int16x8_t _k0123_s16 = vmovl_s8(_k01234567s8);
int16x8_t _k3456_s16 = vmovl_s8(_k34567xxxs8);
int16x8_t _k678x_s16 = vmovl_s8(_k678xxxxxs8);
#endif
for (; remain>0; remain--)
{
#if __ARM_NEON
int8x8_t _r00s8 = vld1_s8(r0);
int8x8_t _r10s8 = vld1_s8(r1);
int8x8_t _r20s8 = vld1_s8(r2);
int16x8_t _r00s16 = vmovl_s8(_r00s8);
int16x8_t _r10s16 = vmovl_s8(_r10s8);
int16x8_t _r20s16 = vmovl_s8(_r20s8);
int32x4_t _sum = vmull_s16(vget_low_s16(_r00s16), vget_low_s16(_k0123_s16));
_sum = vmlal_s16(_sum, vget_low_s16(_r10s16), vget_low_s16(_k3456_s16));
_sum = vmlal_s16(_sum, vget_low_s16(_r20s16), vget_low_s16(_k678x_s16));
_sum = vsetq_lane_s32(*outptr, _sum, 3);
#if __aarch64__
*outptr = vaddvq_s32(_sum);
#else
int32x2_t _ss = vadd_s32(vget_low_s32(_sum), vget_high_s32(_sum));
_ss = vpadd_s32(_ss, _ss);
*outptr = vget_lane_s32(_ss, 0);
#endif // __aarch64__
#else
int sum = 0;
sum += (int)r0[0] * ktmp[0];
sum += (int)r0[1] * ktmp[1];
sum += (int)r0[2] * ktmp[2];
sum += (int)r1[0] * ktmp[3];
sum += (int)r1[1] * ktmp[4];
sum += (int)r1[2] * ktmp[5];
sum += (int)r2[0] * ktmp[6];
sum += (int)r2[1] * ktmp[7];
sum += (int)r2[2] * ktmp[8];
*outptr += sum;
#endif // __ARM_NEON
r0 += 2;
r1 += 2;
r2 += 2;
outptr++;
}
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
ktmp += 9;
}
}
}
|
SpatialSubSampling.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/SpatialSubSampling.c"
#else
static int nn_(SpatialSubSampling_updateOutput)(lua_State *L)
{
THTensor *input = luaT_checkudata(L, 2, torch_Tensor);
int kW = luaT_getfieldcheckint(L, 1, "kW");
int kH = luaT_getfieldcheckint(L, 1, "kH");
int dW = luaT_getfieldcheckint(L, 1, "dW");
int dH = luaT_getfieldcheckint(L, 1, "dH");
int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane");
THTensor *weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
THTensor *bias = luaT_getfieldcheckudata(L, 1, "bias", torch_Tensor);
THTensor *output = luaT_getfieldcheckudata(L, 1, "output", torch_Tensor);
real *weight_data = THTensor_(data)(weight);
real *bias_data = THTensor_(data)(bias);
real *output_data;
real *input_data;
luaL_argcheck(L, input->nDimension == 3 || input->nDimension == 4, 2, "3D or 4D(batch mode) tensor expected");
int dimw = 2;
int dimh = 1;
long nbatch = 1;
if (input->nDimension == 4) {
nbatch = input->size[0];
dimw++;
dimh++;
}
long inputWidth = input->size[dimw];
long inputHeight = input->size[dimh];
long outputWidth = (inputWidth - kW) / dW + 1;
long outputHeight = (inputHeight - kH) / dH + 1;
luaL_argcheck(L, input->size[dimh-1] == nInputPlane, 2, "invalid number of input planes");
luaL_argcheck(L, inputWidth >= kW && inputHeight >= kH, 2, "input image smaller than kernel size");
if (input->nDimension == 3)
THTensor_(resize3d)(output, nInputPlane, outputHeight, outputWidth);
else
THTensor_(resize4d)(output, input->size[0], nInputPlane, outputHeight, outputWidth);
input = THTensor_(newContiguous)(input);
input_data = THTensor_(data)(input);
output_data = THTensor_(data)(output);
long k;
#pragma omp parallel for private(k)
for(k = 0; k < nInputPlane; k++)
{
long p;
for(p = 0; p < nbatch; p++)
{
long xx, yy;
/* For all output pixels... */
real *ptr_output = output_data + p*nInputPlane*outputWidth*outputHeight + k*outputWidth*outputHeight;
/* Get the good mask for (k,i) (k out, i in) */
real the_weight = weight_data[k];
/* Initialize to the bias */
real z = bias_data[k];
long i;
for(i = 0; i < outputWidth*outputHeight; i++)
ptr_output[i] = z;
for(yy = 0; yy < outputHeight; yy++)
{
for(xx = 0; xx < outputWidth; xx++)
{
// Compute the mean of the input image...
real *ptr_input = input_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight + yy*dH*inputWidth+xx*dW;
real sum = 0;
long kx, ky;
for(ky = 0; ky < kH; ky++)
{
for(kx = 0; kx < kW; kx++)
sum += ptr_input[kx];
ptr_input += inputWidth; // next input line
}
// Update output
*ptr_output++ += the_weight*sum;
}
}
}
}
THTensor_(free)(input);
return 1;
}
static int nn_(SpatialSubSampling_updateGradInput)(lua_State *L)
{
THTensor *input = luaT_checkudata(L, 2, torch_Tensor);
THTensor *gradOutput = luaT_checkudata(L, 3, torch_Tensor);
int kW = luaT_getfieldcheckint(L, 1, "kW");
int kH = luaT_getfieldcheckint(L, 1, "kH");
int dW = luaT_getfieldcheckint(L, 1, "dW");
int dH = luaT_getfieldcheckint(L, 1, "dH");
int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane");
THTensor *weight = luaT_getfieldcheckudata(L, 1, "weight", torch_Tensor);
THTensor *gradInput = luaT_getfieldcheckudata(L, 1, "gradInput", torch_Tensor);
int dimw = 2;
int dimh = 1;
long nbatch = 1;
if (input->nDimension == 4) {
nbatch = input->size[0];
dimw++;
dimh++;
}
long inputWidth = input->size[dimw];
long inputHeight = input->size[dimh];
long outputWidth = (inputWidth - kW) / dW + 1;
long outputHeight = (inputHeight - kH) / dH + 1;
real *weight_data = THTensor_(data)(weight);
real *gradOutput_data = THTensor_(data)(gradOutput);
real *input_data, *gradInput_data;
input_data = THTensor_(data)(input);
THTensor_(resizeAs)(gradInput, input);
gradInput_data = THTensor_(data)(gradInput);
gradOutput_data = THTensor_(data)(gradOutput);
long k;
#pragma omp parallel for private(k)
for(k = 0; k < nInputPlane; k++)
{
long p;
for(p = 0; p < nbatch; p++)
{
real the_weight = weight_data[k];
real *ptr_gradOutput = gradOutput_data + p*nInputPlane*outputHeight*outputWidth + k*outputWidth*outputHeight;
long xx, yy;
real* ptr_gi = gradInput_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight;
long i;
for(i=0; i<inputWidth*inputHeight; i++)
ptr_gi[i] = 0.0;
for(yy = 0; yy < outputHeight; yy++)
{
for(xx = 0; xx < outputWidth; xx++)
{
real *ptr_gradInput = gradInput_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight + yy*dH*inputWidth+xx*dW;
real z = *ptr_gradOutput++ * the_weight;
long kx, ky;
for(ky = 0; ky < kH; ky++)
{
for(kx = 0; kx < kW; kx++)
ptr_gradInput[kx] += z;
ptr_gradInput += inputWidth;
}
}
}
}
}
return 1;
}
static int nn_(SpatialSubSampling_accGradParameters)(lua_State *L)
{
THTensor *input = luaT_checkudata(L, 2, torch_Tensor);
THTensor *gradOutput = luaT_checkudata(L, 3, torch_Tensor);
real scale = luaL_optnumber(L, 4, 1);
int kW = luaT_getfieldcheckint(L, 1, "kW");
int kH = luaT_getfieldcheckint(L, 1, "kH");
int dW = luaT_getfieldcheckint(L, 1, "dW");
int dH = luaT_getfieldcheckint(L, 1, "dH");
int nInputPlane = luaT_getfieldcheckint(L, 1, "nInputPlane");
THTensor *gradWeight = luaT_getfieldcheckudata(L, 1, "gradWeight", torch_Tensor);
THTensor *gradBias = luaT_getfieldcheckudata(L, 1, "gradBias", torch_Tensor);
long nbatch = 1;
long dimw = 2;
long dimh = 1;
if (input->nDimension == 4) {
dimw++;
dimh++;
nbatch = input->size[0];
}
long inputWidth = input->size[dimw];
long inputHeight = input->size[dimh];
long outputWidth = (inputWidth - kW) / dW + 1;
long outputHeight = (inputHeight - kH) / dH + 1;
real *gradWeight_data = THTensor_(data)(gradWeight);
real *gradBias_data = THTensor_(data)(gradBias);
real *gradOutput_data = THTensor_(data)(gradOutput);
real *input_data;
input = THTensor_(newContiguous)(input);
input_data = THTensor_(data)(input);
long k;
#pragma omp parallel for private(k)
for(k = 0; k < nInputPlane; k++)
{
long p;
for(p = 0; p < nbatch; p++)
{
real *ptr_gradOutput = gradOutput_data + p*nInputPlane*outputHeight*outputWidth + k*outputWidth*outputHeight;
real sum;
long xx, yy;
sum = 0;
long i;
for(i = 0; i < outputWidth*outputHeight; i++)
sum += ptr_gradOutput[i];
gradBias_data[k] += scale*sum;
sum = 0;
for(yy = 0; yy < outputHeight; yy++)
{
for(xx = 0; xx < outputWidth; xx++)
{
real *ptr_input = input_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight + yy*dH*inputWidth+xx*dW;
real z = *ptr_gradOutput++;
long kx, ky;
for(ky = 0; ky < kH; ky++)
{
for(kx = 0; kx < kW; kx++)
sum += z * ptr_input[kx];
ptr_input += inputWidth;
}
}
}
gradWeight_data[k] += scale*sum;
}
}
THTensor_(free)(input);
return 0;
}
static const struct luaL_Reg nn_(SpatialSubSampling__) [] = {
{"SpatialSubSampling_updateOutput", nn_(SpatialSubSampling_updateOutput)},
{"SpatialSubSampling_updateGradInput", nn_(SpatialSubSampling_updateGradInput)},
{"SpatialSubSampling_accGradParameters", nn_(SpatialSubSampling_accGradParameters)},
{NULL, NULL}
};
static void nn_(SpatialSubSampling_init)(lua_State *L)
{
luaT_pushmetatable(L, torch_Tensor);
luaT_registeratname(L, nn_(SpatialSubSampling__), "nn");
lua_pop(L,1);
}
#endif
|
ten_tusscher_2004_epi_S3_8.c | //Original Ten Tusscher
#include <assert.h>
#include <stdlib.h>
#include "ten_tusscher_2004_epi_S3_8.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.5688991140338,0.00128989076010967,0.779725008886256,0.779565445880938,0.000174810397692260,0.485096814769478,0.00294016686914029,0.999998347733673,1.93329393974683e-08,1.89090484255682e-05,0.999774687563683,1.00740027710241,0.999998374863597,3.79573975372647e-05,0.444542717705145,10.8941497006382,138.749766452892};
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 []={14.6547878509413,0.000331163124393016,0.000141848395724115,0.000152715872289379,0.252276201531683,0.136233497412623,0.183769392016071,4.74149143708928,0.0131007982469289,1.00337677402750,1087.25426932732,0.000473578600176269,0.442234646717894,0.0191683130689928,0.00379077132033936,3.87868758690519e-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;
}
|
Common.h | #ifndef _COMMON_
#define _COMMON_
#include "zeroin.h"
#include "average.h"
#include <map>
#include <vector>
#ifdef _STRSTREAM
#include <strstream>
#endif
using namespace std;
typedef vector<int>::size_type vint;
int Binomial(int n, int m)
{
int Mf = 1;
for (int i=2; i<=m; i++) Mf *= i;
int r = 1;
for (int i=n; i>=n-m+1; i--) r*=i;
return r/Mf;
}
//Common constants and variables
class common{
public:
static double U;
static double T;
// static double J;
static int baths;
static int Na, Nc;
static function1D<int> Ns;
static function2D<double> Ms;
static function1D<int> Mtot;
static function1D<int> deg;
static function1D<double> sJc;
static vector<vector<map<int,double> > > sncab; // index for hole diagrams
static vector<vector<map<int,double> > > sncaf; // index for particle diagrams
static vector<map<int,double> > suscb; // index for susceptibility
static function2D<int> ncab; // index for hole diagrams
static function2D<int> ncaf; // index for particle diagrams
static function2D<double> prefactb; // prefactor for hole digrams
static function2D<double> prefactf; // prefactor for particle diagrams
static function2D<double> prefactG; // prefactor to calculate local Green's function
static function1D<double> Ed;
static function1D<double> Sinfty;
static function1D<double> nalpha;
static function1D<double> miss_nd;
static function2D<double> moment;
static double beta;
static double delta;
static double Q;
static double Q0;
static double nd;
static double nd0;
static double lambda0;
static string outdir;
static int totDeg;
static function1D<string> Eds;
static int N_ac;
static double dom_ac;
static int acore, pcore;
static bool SubtractLorentz;
static double LorentzMaxRatio;
static double SearchLorentz;
static int FirstLorentz;
static int LastLorentz;
static double dlmin;
static bool renorm_core, renorm;
static bool cmp_susc;
static double Fimp, Epot, TrLogGimp;
static void SetParameters(Par<double>& Ed_, double U_, /*double J_, */double T_, double Q0_, const string& outdir_, int N_ac_,
double dom_ac_, int acore_, int pcore_, bool SubtractLorentz_, double SearchLorentz_,
double LorentzMaxRatio_, int FirstLorentz_, int LastLorentz_,
bool renorm_core_, bool renorm_)
{
dlmin = 2.0;
LorentzMaxRatio = LorentzMaxRatio_;
SearchLorentz = SearchLorentz_;
SubtractLorentz=SubtractLorentz_;
FirstLorentz=FirstLorentz_; // First pseudoparticle which could be augmented with lorentz
LastLorentz=LastLorentz_; // Last pseudoparticle which could be augmented with lorentz
Ed.resize(baths);
int i=0;
while (Ed_.next() && i<baths) {
Ed[i] = Ed_;
i++;
}
for (int j=i; j<baths; j++) Ed[j]=Ed[i-1];
T = T_;
U = U_;
// J = J_;
beta=1/T_;
Q0 = Q0_;
outdir = outdir_;
Eds.resize(baths);
for (int i=0; i<baths; i++){
stringstream t; t<<"E"<<i;
Eds[i] = t.str();
}
nalpha.resize(baths);
miss_nd.resize(baths);
for (int i=0; i<baths; i++) miss_nd[i]=0;
N_ac = N_ac_;
dom_ac = dom_ac_;
acore = acore_;
pcore = pcore_;
renorm_core=renorm_core_;
renorm=renorm_;
moment.resize(baths,2);
Fimp=Epot=TrLogGimp=0.0;
}
static void ParsInputFile(const string& filename);
static void PrintParsedData(ostream& stream);
static ostream& printHead(ostream& stream);
};
class sLorentz{
public:
double x0, gamma, P;
bool exist;
sLorentz() : x0(0), gamma(1), P(0), exist(false){};
void Set(double zero, double eps, double a, double p, double q, double r)
{
exist = true;
//double A = (sqr(1-p)+sqr(q))/a-2*eps*q*r/sqr(a)+sqr(eps*r/a)/a;
double A = (sqr(1-p)+sqr(q))/a-2*eps*q*(r/a)/a+sqr(eps*r/a)/a;
double B = eps*q/a-sqr(eps)/a*(r/a)/2;
double C = sqr(eps)/a;
double b2 = C/A-sqr(B/A);
x0 = -B/A;
gamma = (b2>0)? sqrt(b2) : sqrt(abs(C/A));
if (gamma==0) {
exist=false; P=0;
return;
}
//cout<<"a="<<a<<" A="<<A<<" B="<<B<<" C="<<C<<" b2="<<b2<<" gamma="<<gamma<<endl;
P = 1/(A*gamma);
x0 += zero;
}
void SetFalse(){exist=false; P=0;}
private:
double IntgA(double om0, double om1, double A0, double A1, double omega, double x0) const
{
if (!exist) return 0;
if (fabs(om1-om0)*100<gamma) return P*gamma*0.5*(A0+A1)*(om1-om0)/(sqr(0.5*(om0+om1)+omega-x0)+sqr(gamma));
double c0 = om0 + omega - x0;
double c1 = om1 + omega - x0;
double dA = (A1-A0)/(om1-om0);
if (abs(c0)>100*gamma && abs(c1)>100*gamma && c0*c1>0) return P*gamma*( (A0-dA*c0)*(1/c0-1/c1)+dA*log(c1/c0)+0.5*dA*(sqr(gamma/c1)-sqr(gamma/c0)) ); ///// HERE WAS A BUG!! Corrected Dec/6/2013.
if (abs(c0)>100*gamma && abs(c1)>100*gamma && c1-c0>199.9*gamma) return P*( (A0-dA*c0)*(M_PI+gamma*(1/c0-1/c1))+dA*gamma*log(abs(c1/c0))+0.5*dA*gamma*(sqr(gamma/c1)-sqr(gamma/c0)) ); ///// HERE WAS A BUG!! Corrected Dec/6/2013.
//if (abs(c0)>1 && abs(c1)>1) return P*gamma*(c1-c0)*0.5*(A1+A0)/(c1*c0); ///// HERE WAS A BUG!! Corrected Dec/6/2013.
double a0 = c0/gamma;
double a1 = c1/gamma;
double R;
if (fabs(gamma)<1e-30){
R= P*gamma*((A0-dA*c0)*(1/c0-1/c1)+dA*log(fabs(c1/c0)));
}else{
R = P*((A0-dA*c0)*(atan(a1)-atan(a0))+0.5*gamma*dA*log((1+sqr(a1))/(1+sqr(a0))));
}
if (isnan(R) || isinf(R)){
cerr<<"R is nan or inf "<<R<<" "<<om0<<" "<<om1<<" "<<A0<<" "<<A1<<" "<<omega<<" "<<x0<<" "<<c0<<" "<<c1<<endl;
cerr<<"to "<<(1+sqr(a1))<<" "<<(1+sqr(a0))<<" a0="<<a0<<" a1="<<a1<<" gamma="<<gamma<<" c0="<<c0<<" c1="<<c1<<" "<<atan(a1)-atan(a0)<<" "<<(A0-dA*c0)<<" "<<log((1+sqr(a1))/(1+sqr(a0)))<<endl;
}
return R;
}
public:
double IntgAp(double om0, double om1, double A0, double A1, double omega)const{
return IntgA(om0, om1, A0, A1, omega, x0);}
double IntgAm(double om0, double om1, double A0, double A1, double omega)const{
return IntgA(om0, om1, A0, A1, -omega, -x0);}
double IntgApLL(const sLorentz& l, double omega) const
{
return P*l.P*M_PI*(gamma+l.gamma)/(sqr(gamma+l.gamma)+sqr(x0-l.x0-omega));
}
double V(double x){ return P*gamma/(sqr(x-x0)+sqr(gamma));}
friend ostream& operator<<(ostream& stream, const sLorentz& s);
};
ostream& operator<<(ostream& stream, const sLorentz& s)
{
if (s.exist)
stream<<setw(15)<<s.x0<<" "<<setw(15)<<s.gamma<<" "<<setw(15)<<s.P<<" ";
return stream;
}
// Auxiliary self-energies and spectral functions
class Auxiliary{
const int Na, Nc, baths;
mesh1D om;
function1D<double> fe;
function1D<double> fedh;
function1D<double> logo;
function2D<double> Sigt;
function2D<double> Sigtn;
function2D<dcomplex> Sigc;
function2D<dcomplex> Sigcore;
function2D<double> Gt;
function2D<double> Gp;
function2D<double> Gm;
vector<function2D<double> > aAc;
function1D<double> Acx;
function1D<double> Acy;
function2D<double> Acp, Acm;
AvFun<double> aF;
function1D<double> Energy;
function1D<double> Probability;
mesh1D oml;
function2D<dcomplex> Deltam_ac, Deltap_ac;
function1D<double> mom_Deltam_ac, mom_Deltap_ac;
function1D<dcomplex> Sigtmp;
int mpos, m0, m1;
function2D<double> GtA1, GtA2;
vector<sLorentz> lorentzm, lorentzp;
public:
Auxiliary (int Na_, int Nc_, int baths_) : Na(Na_), Nc(Nc_), baths(baths_), aAc(2*baths), mom_Deltam_ac(baths), mom_Deltap_ac(baths),
lorentzm(Na), lorentzp(Na),Probability(Na){};
bool ReadSelfEnergy(const string& filename, const Par<double>& Ed, const Par<double>& T, const Par<double>& U, const mesh1D& ph_omd, const function2D<double>& ph_Ac);
void KramarsKronig();
double DeterminSpectralFunctions(double StartLambda, double EndLambda, double dLamdba, int followPeak);
void PrintOutMeanQ(double StartLambda, double EndLambda);
void PrintNorm(ostream& stream);
void Print(int l, string dir);
void Printn(int l);
void SetSignToZero(){Sigtn=0.0;Sigcore=0.0;}
void SetUpAverageAc(const mesh1D& omd, const mesh1D& momd, const function2D<double>& Ack, const function1D<double>& fed);
void CalcSigmab(const mesh1D& omd);
void CalcSigmaf(const mesh1D& omd);
double Difference();
double DeterminSelfEnergies(double alpha, int CmpDiff);
const mesh1D& omega() const {return om;}
double ferm(int i) const {return fe[i];}
const function2D<double>& _Gp() const {return Gp;}
const function2D<double>& _Gm() const {return Gm;}
void PrintSign();
double Q(double lambda);
double operator()(double lambda);
double minEnergy;
void PrintCore(const string& filename);
const function1D<double>& Energ() const{return Energy;}
const vector<sLorentz>& Lorentzm()const{return lorentzm;}
const vector<sLorentz>& Lorentzp()const{return lorentzp;}
void CreateSigma000(const mesh1D& omd, const function2D<double>& Ac);
private:
void Print_aAc(int l);
void Print_Qux(int l);
void Print_Sign(int l, int st, int en);
void PrintOutMeanQ(int M, double StartLambda, double EndLambda);
};
// Physical electron spectral function and suscpetibility
// Physical observables
class Physical{
public:
const int Na, Nc, baths;
mesh1D omd;
function2D<dcomplex> G00;
function2D<double> A00;
function1D<double> C00;
function1D<dcomplex> Chi;
function2D<double> A00c;
function2D<dcomplex> Sig;
private:
mesh1D momd;
function1D<double> fed;
function1D<double> logod;
function1D<double> th;
function2D<double> Ac;
function2D<dcomplex> Delta0;
vector<AvFun<double> > aF;
function2D<double> Gtx;
function2D<double> Cmp;
function1D<double> tG;
function1D<bool> Pexists;
public:
Physical(int Na_, int Nc_, int baths_);
bool ReadBathFunction(const string& filename, bool spectra);
void CalculateA00(const mesh1D& omega, const function2D<double>& Gp, const function2D<double>& Gm,
const function1D<double>& Energy, const vector<sLorentz>& lorentzm, const vector<sLorentz>& lorentzp);
void KramarsKronig();
void DeterminG00(double alpha,ostream& loging);
double Difference();
void Print(int l, string dir);
void Print0(const string& filename);
const mesh1D& omega() const {return omd;}
const mesh1D& momega() const {return momd;}
const function1D<double>& fe() const {return fed;}
const function2D<double>& Ac0() const {return Ac;}
void PrintA00(ostream& out);
void CalcSelfEnergy();
void MissingDoping(double start);
private:
void CalculateProducts(double u, double fu, const mesh1D& om, const function2D<double>& Gm);
bool ReadBeginning(const string& filename, istream& input, int& n, int& m, bool& begincomment, double& center);
};
void AverageFunction(const mesh1D& omx, double u, const mesh1D& eps, AvFun<double>& aF, functionb<double>& aAc)
{
apar ap;
cintpar pi;
tint position = omx.InitInterpLeft();
InterpLeft(eps[0]-u, omx, position, pi);
aF.InterpolateFirst(pi);
InterpLeft(eps[1]-u, omx, position, pi);
ap.SetUpCsFirst(u, eps);
aAc[0] = aF.InterpolateNext(pi, ap) * eps.Dh(0);
for (int j=1; j<eps.size()-1; j++){
InterpLeft(eps[j+1]-u, omx, position, pi);
ap.SetUpCs(u, j, eps, omx.Dh(pi.i));
aAc[j] = aF.InterpolateNext(pi, ap) * eps.Dh(j);
}
ap.SetUpCsLast(u, eps);
aAc[eps.size()-1] = aF.InterpolateLast(ap) * eps.Dh(eps.size()-1);
}
inline double product(const double* A, const double* G, int size)
{
double sum = 0;
for (int i=0; i<size; i++) sum += A[i]*G[i];
return sum;
}
void Auxiliary::SetUpAverageAc(const mesh1D& omd, const mesh1D& momd, const function2D<double>& Ack, const function1D<double>& fed)
{
int m = om.find_(0.0)+1;
Acx.resize(omd.size());
for (int b=0; b<baths; b++){
aAc[b].resize(om.size(),om.size());
for (int i=0; i<omd.size(); i++) Acx[i] = Ack[b][i]*(1-fed[i]);
aF.SetUp(Acx,omd);
for (int i=0; i<m; i++) AverageFunction(omd,om[i],om,aF,aAc[b][i]);
for (int i=0; i<omd.size(); i++) Acx[i] = Ack[b][i]*fed[i];
aF.SetUp(Acx,omd);
for (int i=m; i<om.size(); i++) AverageFunction(omd,om[i],om,aF,aAc[b][i]);
aAc[baths+b].resize(om.size(),om.size());
for (int i=0; i<momd.size(); i++) Acx[momd.size()-i-1] = Ack[b][i]*fed[i];
aF.SetUp(Acx,momd);
for (int i=0; i<m; i++) AverageFunction(momd,om[i],om,aF,aAc[baths+b][i]);
for (int i=0; i<momd.size(); i++) Acx[momd.size()-i-1] = Ack[b][i]*(1-fed[i]);
aF.SetUp(Acx,momd);
for (int i=m; i<om.size(); i++) AverageFunction(momd,om[i],om,aF,aAc[baths+b][i]);
}
// For core part need Delta in more extended range
Acy.resize(omd.size());
oml.resize(omd.size()+2*common::N_ac);
for (int i=0; i<common::N_ac; i++) oml[i] = omd[0]-(common::N_ac-i)*common::dom_ac;
for (int i=0; i<omd.size(); i++) oml[i+common::N_ac] = omd[i];
for (int i=0; i<common::N_ac; i++) oml[omd.size()+common::N_ac+i] = omd.last()+(i+1)*common::dom_ac;
oml.SetUp(omd.dcenter());
Deltam_ac.resize(baths,oml.size());
Deltap_ac.resize(baths,oml.size());
Acp.resize(baths,omd.size());
Acm.resize(baths,omd.size());
for (int b=0; b<baths; b++){
for (int i=0; i<omd.size(); i++){
Acm(b,i) = Ack[b][i]*fed[i];
Acp(b,i) = Ack[b][i]*(1-fed[i]);
}
int ofst=0;
#pragma omp parallel for
for (int i=0; i<common::N_ac; i++){
double Deltar = ::KramarsKronig(Acm[b], omd, oml[i], 0, 0.0);
Deltam_ac[b][i] = dcomplex(-M_PI*Deltar,0.0);
Deltar = ::KramarsKronig(Acp[b], omd, oml[i], 0, 0.0);
Deltap_ac[b][i] = dcomplex(-M_PI*Deltar,0.0);
}
ofst=common::N_ac;
#pragma omp parallel for
for (int i=0; i<omd.size(); i++){
double Deltar = ::KramarsKronig(Acm[b], omd, omd[i], i, Acm[b][i]);
Deltam_ac[b][ofst+i] = dcomplex(-M_PI*Deltar,-M_PI*Acm[b][i]);
Deltar = ::KramarsKronig(Acp[b], omd, omd[i], i, Acp[b][i]);
Deltap_ac[b][ofst+i] = dcomplex(-M_PI*Deltar,-M_PI*Acp[b][i]);
}
ofst=common::N_ac+omd.size();
#pragma omp parallel for
for (int i=0; i<common::N_ac; i++){
double Deltar = ::KramarsKronig(Acm[b], omd, oml[omd.size()+common::N_ac+i], omd.size()-1, 0.0);
Deltam_ac[b][ofst+i] = dcomplex(-M_PI*Deltar, 0.0);
Deltar = ::KramarsKronig(Acp[b], omd, oml[omd.size()+common::N_ac+i], omd.size()-1, 0.0);
Deltap_ac[b][ofst+i] = dcomplex(-M_PI*Deltar, 0.0);
}
double summ=0;
for (int i=0; i<omd.size(); i++) summ += Acm[b][i]*omd.Dh(i);
double sump=0;
for (int i=0; i<omd.size(); i++) sump += Acp[b][i]*omd.Dh(i);
mom_Deltam_ac[b] = summ;
mom_Deltap_ac[b] = sump;
}
}
void Auxiliary::CalcSigmab(const mesh1D& omd)
{
for (int b=0; b<baths; b++){
GtA1.Product(Gm,aAc[b],0,mpos); // Gm[f,eps]*Acfm[x,eps]
GtA2.Product(Gp,aAc[b],mpos,aAc[b].size_N()); // Gp[f,eps]*Acfp[x,eps]
if (common::SubtractLorentz){
#pragma omp parallel for
for (int j=0; j<Na; j++){
if (lorentzm[j].exist){
tint pos0=omd.size()-2, pos1=omd.size()-2;
double dlmin_x0 = -common::dlmin + lorentzm[j].x0;
double dlmin_x1 = common::dlmin + lorentzm[j].x0;
for (int i=0; i<mpos; i++){
int k0 = omd._find(dlmin_x0 - om[i], 0, pos0);
int k1 = omd._find(dlmin_x1 - om[i], 0, pos1);
double sum=0;
for (int k=k0; k<k1; k++)
sum += lorentzm[j].IntgAp(omd[k], omd[k+1], Acp(b,k), Acp(b,k+1), om[i]);
GtA1(j,i) += sum;
}
}
if (lorentzp[j].exist){
tint pos0=omd.size()-2, pos1=omd.size()-2;
double dlmin_x0 = -common::dlmin + lorentzp[j].x0;
double dlmin_x1 = common::dlmin + lorentzp[j].x0;
for (int i=mpos; i<om.size(); i++){
int k0 = omd._find(dlmin_x0 - om[i], 0, pos0);
int k1 = omd._find(dlmin_x1 - om[i], 0, pos1);
double sum = 0;
for (int k=k0; k<k1; k++)
sum += lorentzp[j].IntgAp(omd[k], omd[k+1], Acm(b,k), Acm(b,k+1), om[i]);
GtA2(j,i-mpos) += sum;
}
}
}
}
#pragma omp parallel for
for (int j=0; j<Na; j++){
for (map<int,double>::const_iterator l=common::sncab[j][b].begin(); l!=common::sncab[j][b].end(); l++){
int ind = l->first;
if (ind>=0 && ind<Na){
double prf = l->second/static_cast<double>(common::deg[j]);
for (int i=0; i<mpos; i++) Sigtn(j,i) += prf * GtA1(ind,i)/fe[i];
for (int i=mpos; i<om.size(); i++) Sigtn(j,i) += prf * GtA2(ind,i-mpos)/(1-fe[i]);
}
}
}
}
if (!common::acore) return;
for (int b=0; b<baths; b++){
for (int j=0; j<Na; j++){
for (map<int,double>::const_iterator l=common::sncab[j][b].begin(); l!=common::sncab[j][b].end(); l++){
int ind = l->first;
if (ind>=Na && ind<Na+Nc){
double prf = l->second/static_cast<double>(common::deg[j]);
tint position = oml.InitInterpRight();
for (int i=0; i<om.size(); i++){
double x = Energy[ind]-common::lambda0-om[i];
dcomplex Delta=0;
if (x>oml.last()) Delta = mom_Deltam_ac[b]/x;
else Delta = Deltam_ac[b](oml.InterpRight(x, position));
Sigcore[j][i] += prf*Delta;
}
}
}
}
}
}
void Auxiliary::CalcSigmaf(const mesh1D& omd)
{
for (int b=0; b<baths; b++){
GtA1.Product(Gm,aAc[baths+b],0,mpos);
GtA2.Product(Gp,aAc[baths+b],mpos,aAc[baths+b].size_N());
if (common::SubtractLorentz){
#pragma omp parallel for
for (int j=0; j<Na; j++){
if (lorentzm[j].exist){
tint pos0=0, pos1=0;
double dlmin_x0 = -common::dlmin - lorentzm[j].x0;
double dlmin_x1 = common::dlmin - lorentzm[j].x0;
for (int i=0; i<mpos; i++){
int k0 = omd.find_(dlmin_x0 + om[i], pos0);
int k1 = omd.find_(dlmin_x1 + om[i], pos1);
double sum = 0;
//for (int k=0; k<omd.size()-1; k++)
for (int k=k0; k<k1; k++)
sum += lorentzm[j].IntgAm(omd[k], omd[k+1], Acm(b,k), Acm(b,k+1), om[i]);
GtA1(j,i) += sum;
}
}
if (lorentzp[j].exist){
tint pos0=0, pos1=0;
double dlmin_x0 = -common::dlmin - lorentzp[j].x0;
double dlmin_x1 = common::dlmin - lorentzp[j].x0;
for (int i=mpos; i<om.size(); i++){
int k0 = omd.find_(dlmin_x0 + om[i], pos0);
int k1 = omd.find_(dlmin_x1 + om[i], pos1);
double sum = 0;
// for (int k=0; k<omd.size()-1; k++)
for (int k=k0; k<k1; k++)
sum += lorentzp[j].IntgAm(omd[k], omd[k+1], Acp(b,k), Acp(b,k+1), om[i]);
GtA2(j,i-mpos) += sum;
}
}
}
}
#pragma omp parallel for
for (int j=0; j<Na; j++){
for (map<int,double>::const_iterator l=common::sncaf[j][b].begin(); l!=common::sncaf[j][b].end(); l++){
int ind = l->first;
if (ind>=0 && ind<Na){
double prf = l->second/static_cast<double>(common::deg[j]);
for (int i=0; i<mpos; i++) Sigtn(j,i) += prf * GtA1(ind,i)/fe[i];
for (int i=mpos; i<om.size(); i++) Sigtn(j,i) += prf * GtA2(ind,i-mpos)/(1-fe[i]);
}
}
}
}
if (!common::acore) return;
for (int b=0; b<baths; b++){
for (int j=0; j<Na; j++){
for (map<int,double>::const_iterator l=common::sncaf[j][b].begin(); l!=common::sncaf[j][b].end(); l++){
int ind = l->first;
if (ind>=Na && ind<Na+Nc){
double prf = l->second/static_cast<double>(common::deg[j]);
tint position = oml.InitInterpLeft();
for (int i=0; i<om.size(); i++){
double x = om[i]-Energy[ind]+common::lambda0;
dcomplex Delta=0;
if (x<om[0]) Delta = mom_Deltap_ac[b]/x;
else Delta = Deltap_ac[b](oml.InterpLeft(x, position));
Sigcore[j][i] += prf*Delta;
}
}
}
}
}
}
void Auxiliary::CreateSigma000(const mesh1D& omd, const function2D<double>& Ac)
{// If inteligence guess for the pseudo-particles self-energy is not found,
// it creates a guess using atomic type of approximation.
Sigt=0;
for (int b=0; b<baths; b++){
for (int j=0; j<Na; j++){
for (map<int,double>::const_iterator l=common::sncab[j][b].begin(); l!=common::sncab[j][b].end(); l++){
int ind = l->first;
if (ind>=0 && ind<Na){
double Em = Energy[ind]-minEnergy;
double prf = l->second/static_cast<double>(common::deg[j]);
tint pos = omd.InitInterpRight();
for (int i=0; i<om.size(); i++){
double ff;
if (om[i]>0) ff = ferm_f((Em-om[i])/common::T)/(1-fe[i]);
else{
double eom = exp(om[i]/common::T);
ff = (eom+1.)/(eom+exp(Em/common::T));
}
Sigt(j,i) += -M_PI*prf*ff*Ac[b](omd.InterpRight(Em-om[i],pos));
}
}
}
for (map<int,double>::const_iterator l=common::sncaf[j][b].begin(); l!=common::sncaf[j][b].end(); l++){
int ind = l->first;
if (ind>=0 && ind<Na){
double Em = Energy[ind]-minEnergy;
double prf = l->second/static_cast<double>(common::deg[j]);
tint pos = omd.InitInterpLeft();
for (int i=0; i<om.size(); i++){
double ff;
if (om[i]>0) ff = ferm_f((Em-om[i])/common::T)/(1-fe[i]);
else{
double eom = exp(om[i]/common::T);
ff = (eom+1.)/(eom+exp(Em/common::T));
}
Sigt(j,i) += -M_PI*prf*ff*Ac[b](omd.InterpLeft(om[i]-Em,pos));
}
}
}
}
}
KramarsKronig();
}
inline ostream& common::printHead(ostream& stream)
{
stream<<"# ";
stream<<" nb="<<baths<<" ";
//stream<<" T="<<T<<" ntot="<<nd<<" U="<<U<<" lambda0="<<lambda0<<" ";
stream<<" T="<<T<<" ntot="<<nd<<" U="<<U<<" dFimpG="<<Fimp-TrLogGimp<<" Fimp="<<Fimp<<" Epot="<<Epot<<" TrLogGimp="<<TrLogGimp<<" lambda0="<<lambda0<<" ";
stream<<" Ns=[";
for (int i=0; i<baths-1; i++) stream<<Ns[i]<<",";
stream<<Ns[baths-1]<<"] ";
stream<<" Eimp=[";
for (int i=0; i<baths-1; i++) stream<<Ed[i]<<",";
stream<<Ed[baths-1]<<"] ";
stream<<" nf=[";
for (int i=0; i<baths-1; i++) stream<<nalpha[i]<<",";
stream<<nalpha[baths-1]<<"] ";
stream<<" md=[";
for (int i=0; i<baths-1; i++) stream<<miss_nd[i]<<",";
stream<<miss_nd[baths-1]<<"] ";
stream<<" moment=[";
for (int i=0; i<baths-1; i++) stream<<"["<<moment[i][0]<<","<<moment[i][1]<<"],";
stream<<"["<<moment[baths-1][0]<<","<<moment[baths-1][1]<<"]] ";
if (Sinfty.size()>0){
double aS=0; for (int i=0; i<baths; i++) aS += Sinfty[i]; aS/=baths;
stream<<" aSinfty="<<aS<<" ";
stream<<" Sinfty=(";
for (int i=0; i<baths-1; i++)stream<<Sinfty[i]<<",";
stream<<Sinfty[baths-1]<<") ";
}
return stream;
}
void RememberParams (int argc, char *argv[]){
ofstream param ((common::outdir+"/history.nca").c_str(), ios::app);
if (!param) cerr<<" Didn't suceeded to open params file!"<<(common::outdir+"/history.nca")<<endl;
for (int i=0; i<argc; i++) param << argv[i] << " ";
param << endl;
}
template <class T>
bool ReadValue(T& a, const std::string& variable, const std::string& str){
std::string::size_type pos = str.find(variable);
if (pos < std::string::npos){
std::string::size_type poseq = str.find("=",pos);
if (poseq<std::string::npos){
std::istringstream streambuff(std::string(str,poseq+1));
streambuff >> a;
}
return true;
}
return false;
}
bool Auxiliary::ReadSelfEnergy(const string& filename, const Par<double>& Ed, const Par<double>& T, const Par<double>& U, const mesh1D& ph_omd, const function2D<double>& ph_Ac){
ifstream inputf(filename.c_str());
istream input(inputf.rdbuf());
input.seekg(0,ios::beg);
if (!input) {
cerr << "Can't open input file: " << filename << endl;
return false;
}
// Is the input file started with comment?
bool begincomment = false;
int n = 0;
string str;
const double SpecNumber = -100000;
double T_ = SpecNumber, U_ = SpecNumber;
function1D<double> Ed_(baths);
Ed_ = SpecNumber;
double center = 0;
getline(input,str);
if (str.find('#')<string::npos){
begincomment = true;
for (int i=0; i<baths; i++) ReadValue(Ed_[i], common::Eds[i], str);
ReadValue(T_, "T", str);
ReadValue(U_, "U", str);
if (!ReadValue(center, "peakposition", str)) center=0;
} else n++;
if (!Ed.IsSet() && Ed_[0]!=SpecNumber) for (int i=0; i<baths; i++) common::Ed[i] = Ed_[i];
if (!T.IsSet() && T_!=SpecNumber) common::T = T_;
if (!U.IsSet() && U_!=SpecNumber) common::U = U_;
common::beta = 1./common::T;
Energy.resize(Na+Nc);
minEnergy=0;
// Calculates auxiliary Energies
for (int i=0; i<Na+Nc; i++){
Energy[i] = 0;
for (int j=0; j<baths; j++) Energy[i] += common::Ed[j]*common::Ms[i][j];
// Energy[i] += 0.5*common::Mtot[i]*(common::Mtot[i]-1)*(common::U-0.5*common::J);
// Energy[i] += common::J*common::sJc[i];
Energy[i] += 0.5*common::Mtot[i]*(common::Mtot[i]-1)*common::U;
Energy[i] += common::sJc[i];
if (Energy[i]<minEnergy) minEnergy = Energy[i];
}
clog<<"************* Parameters ****************"<<endl;
clog<<" U = "<<common::U<<endl;
for (int i=0; i<baths; i++)
clog<<" Ed"<<i<<" = "<<common::Ed[i]<<endl;
clog<<" T = "<<common::T<<endl;
for (int i=0; i<baths; i++)
clog<<" N"<<i<<" = "<<common::Ns[i]<<endl;
for (int i=0; i<Na+Nc; i++){
if (i<Na) clog<<" valence state"<<setw(2)<<left<<i<<right<<" = ";
else clog<<" core state"<<i<<" = ";
for (int j=0; j<baths; j++) clog<<setw(2)<<common::Ms[i][j];
clog<<" with Energy"<<setw(2)<<left<<i<<right<<" = "<<Energy[i]<<endl;
}
clog<<"*****************************************"<<endl;
// Computes the number of columns in file
if (!input) {
cerr << "ERROR: Wrong file format for Sigm" << endl;
return false;
}
getline(input,str); n++;
#ifdef _STRSTREAM
strstream oneline;
oneline << str <<ends;
#else
istringstream oneline(str);
#endif
int m=0; double t;
while (oneline){oneline>>t; m++;}
m--;
while (input){ getline(input,str); n++;}
n--;
clog << filename << ": Number of entries: "<< n <<endl;
clog << filename << ": Number of columns: "<< m <<endl;
clog << filename << ": Peak-position "<< center <<endl;
bool CreateDefault = false;
if (m<2*Na+1){
//cerr<<"ERROR: Not enough columns is input Sigma file. Exiting!"<<endl;
clog<<"WARRNING: Not enough columns is input self-energy for pseudoparticles.... Creating default!"<<endl;
CreateDefault = true;
}
inputf.seekg(0,ios::beg);
// clog<<"Premaknil na "<< inputf.tellg()<<endl;
if (begincomment) inputf.ignore(10000,'\n');
if (!inputf){ cerr<<"Reopening didn't suceeded!"<<endl; return false;}
om.resize(n);
Sigt.resize(Na,n);
Sigc.resize(Na,n);
int l=0;
double omega;
while (inputf>>omega && l<n){
om[l] = omega;
if (!CreateDefault){
for (int i=0; i<Na; i++){
double Sr, St;
inputf>>Sr;
inputf>>St;
Sigc(i,l) = dcomplex(Sr,-St);
Sigt(i,l) = -St;
}
}
getline(inputf, str);
l++;
}
inputf.close();
if (l<n) cerr<<"Something wrong by reading file "<<filename<<endl;
om.SetUp(center);
mpos = om.find_(0.0)+1;
m0 = om.find_(-common::SearchLorentz);
m1 = om.find_(common::SearchLorentz)+1;
GtA1.resize(Na,mpos);
GtA2.resize(Na,om.size()-mpos);
Sigcore.resize(Na,om.size());
Sigtn.resize(Na,om.size());
Gt.resize(Na,om.size());
Gp.resize(Na,om.size());
Gm.resize(Na,om.size());
fe.CalcFermOnMesh(common::beta, om);
logo.CalcLogOnMesh(om);
fedh.resize(om.size());
for (int i=0; i<om.size(); i++) fedh[i] = fe[i]*om.Dh(i);
if (CreateDefault){
CreateSigma000(ph_omd, ph_Ac);
}else{
for (int j=0; j<Na; j++){
for (int i=0; i<om.size(); i++)
Sigc(j,i) = dcomplex(Sigc(j,i).real(), Sigc(j,i).imag()*(1-fe[i]));
}
}
return true;
}
void Auxiliary::KramarsKronig()
{
for (int l=0; l<Na; l++){
for (int i=0; i<om.size(); i++) Sigc(l,i).imag() = Sigt(l,i)*(1-fe[i]);
Sigc[l].KramarsKronig(om, logo);
}
}
double Lambda(double E, const functionb<dcomplex>& Sigc, const functionb<double>& Sigx, const mesh1D& om)
{
// looking for lambda such that \widetilde{G} has maximum at zero frequency.
// Sufficient condition is that the derivative of 1/\widetilde{G} is zero at zero frequency.
// One gets a quadratic equation for lambda and thus two roots. Then one chooses the root that maximizes \widetilde{G}.
// If no root exists, than we take lambda that minimizes linear coeficient in the expansion of 1/\widetilde{G}.
// The latter equation is linear and one always gets unique solution.
intpar p = om.Interp(0.0); int i=p.i;
dcomplex cs = -E-Sigc(p);
dcomplex ds = (Sigc[i+1]-Sigc[i])*om.Delta(i);
double cr = cs.real();
double ci = cs.imag();
double dcr = 1-ds.real();
double dci = -ds.imag();
double dSigx = (Sigx[i+1]-Sigx[i])*om.Delta(i);
double x = Sigx[i]/dSigx;
double determinant2 = x*(x*dcr*dcr+2*ci*dci)-ci*ci;
// Minimum can not be at zero. Try to find lambda that minimizes the linear coefficient in the expansion of 1/G
// If 1/G = a + b omega + c omega^2 +... and the below determinant is smaller than zero, coefficient b can not be
// set to zero. Than return lambda that gives the smallest b.
if (determinant2<=0) return dcr*x-cr;
double d2 = -sqrt(determinant2);
double d1 = -cr + dcr*x;
double v1 = 1/(sqr(ci)+sqr(cr+d1+d2));
double v2 = 1/(sqr(ci)+sqr(cr+d1-d2));
cout<<"Lambda="<<d1+d2<<" "<<d1-d2<<" "<<v1<<" "<<v2<<endl;
if (fabs(v1)>fabs(v2)) return d1+d2;
else return d1-d2;
}
double Auxiliary::Q(double lambda)
{
double sumQ=0;
for (int j=0; j<Na; j++){
double mune = -Energy[j]+lambda;
sLorentz lorentz;
if (common::SubtractLorentz && j>=common::FirstLorentz && j<=common::LastLorentz){
double v0 = om[m0]+mune-Sigc(j,m0).real(), v=v0;
int ii=0;
for (ii=m0+1; ii<m1; ii++) {
v = om[ii]+mune-Sigc(j,ii).real();
if (sign(v)*sign(v0)<0) break;
}
double denom = om[ii]-om[ii-1]-Sigc(j,ii).real()+Sigc(j,ii-1).real();
if (denom==0) cout<<"denom="<<denom<<endl;
if (sign(v)*sign(v0)<0 && denom!=0){
double zero = om[ii-1]-(om[ii]-om[ii-1])*(om[ii-1]+mune-Sigc(j,ii-1).real())/(om[ii]-om[ii-1]-Sigc(j,ii).real()+Sigc(j,ii-1).real());
intpar ip(ii-1,(zero-om[ii-1])/(om[ii]-om[ii-1]));
double dom = om[ii]-om[ii-1];
dcomplex Sc = Sigc[j](ip);
double ratio = abs(Sc.imag()/dom);
if (ratio<common::LorentzMaxRatio){
double Sm = Sigt[j](ip)*fe(ip);
dcomplex dSc = (Sigc[j][ii]-Sigc[j][ii-1])/dom; //(om[ii]-om[ii-1]);
double dSm = (Sigt[j][ii]*fe[ii]-Sigt[j][ii-1]*fe[ii-1])/dom; //(om[ii]-om[ii-1]);
double Sc_im = Sc.imag();
if (fabs(Sc_im)<1e-20) Sc_im=-1e-20;
if (fabs(Sm)<1e-20) Sm=-1e-20;
if (fabs(Sc_im)>=1e-20 && fabs(Sm)>=1e-20){
lorentz.Set(zero, Sc_im, Sm, dSc.real(), dSc.imag(), dSm);
//cout<<"QFound zero "<<setw(2)<<left<<j<<right<<setw(10)<<zero<<" "<<lorentz<<endl;//setw(15)<<Sc<<" "<<setw(15)<<-St<<" ";
}
}
}
}
double sum=0, v;
for (int i=0; i<om.size(); i++){
v = fedh[i]*Sigt(j,i)/(sqr(om[i]+mune-Sigc(j,i).real())+sqr(Sigc(j,i).imag()));
if (lorentz.exist) v -= om.Dh(i)*lorentz.V(om[i]);
sum -= v;
}
sum -= lorentz.P*M_PI;
sumQ += sum*common::deg[j];
}
return (sumQ/M_PI);
}
inline double Auxiliary::operator()(double lambda)
{
double Q_ = Q(lambda);
return Q_-common::Q0;
}
void Auxiliary::PrintOutMeanQ(double StartLambda, double EndLambda)
{
double a0 = StartLambda;
int M = 100;
double da0 = (EndLambda-StartLambda)/M;
cout.precision(16);
for (int i=0; i<M; i++){
cout << a0 << setw(25) << operator()(a0) << endl;
a0 += da0;
}
}
double Auxiliary::DeterminSpectralFunctions(double StartLambda, double EndLambda, double dLambda, int followPeak)
{
double lambda0;
if (followPeak>=0 && followPeak<Na)
lambda0 = Lambda(Energy[followPeak], Sigc[followPeak], Sigt[followPeak], om);
else if (followPeak==-2){
lambda0 = minEnergy;
}else{
double a0 = StartLambda, b0 = 0;
int sign=0, nn=0;
while (!sign && nn++<100){
double pQ = operator()(a0);
while (!sign && a0<=b0) {
double sQ = operator()(a0+dLambda);
sign = pQ*sQ<0;
pQ = sQ;
if (!sign) a0 += dLambda;
}
if (!sign) dLambda /= 2.0;
}
if (nn>=100) {
cerr << "Can't find root for <Q>" << endl;
PrintOutMeanQ(StartLambda, EndLambda);
exit(1);
}
// loking for zero (lambda0)
lambda0 = zeroin(a0, a0+dLambda, *this, 1e-15*common::Q0);
}
common::lambda0 = lambda0;
clog << setprecision(16) << "; lambda = "<<lambda0<<" "<<lambda0-minEnergy<<endl;
double sumQ = 0, sumnd=0;
function1D<double> dQ(Na);
for (int j=0; j<Na; j++){
double mune = -Energy[j]+lambda0;
if (common::SubtractLorentz && j>=common::FirstLorentz && j<=common::LastLorentz){
double v = om[m0]+mune-Sigc(j,m0).real(), v0=v;
int ii=0;
for (ii=m0+1; ii<m1; ii++) {
v = om[ii]+mune-Sigc(j,ii).real();
if (sign(v)*sign(v0)<0) break;
}
bool found = false;
double denom = om[ii]-om[ii-1]-Sigc(j,ii).real()+Sigc(j,ii-1).real();
if (sign(v)*sign(v0)<0 && denom!=0){
double zero = om[ii-1]-(om[ii]-om[ii-1])*(om[ii-1]+mune-Sigc(j,ii-1).real())/(om[ii]-om[ii-1]-Sigc(j,ii).real()+Sigc(j,ii-1).real());
intpar ip(ii-1,(zero-om[ii-1])/(om[ii]-om[ii-1]));
double dom = om[ii]-om[ii-1];
dcomplex Sc = Sigc[j](ip);
double ratio = abs(Sc.imag()/dom);
//clog<<"ps"<<j<<" ratio="<<ratio<<endl;
if (ratio<common::LorentzMaxRatio){
double Sm = Sigt[j](ip)*fe(ip);
dcomplex dSc = (Sigc[j][ii]-Sigc[j][ii-1])/dom;
double dSm = (Sigt[j][ii]*fe[ii]-Sigt[j][ii-1]*fe[ii-1])/dom;
double Sc_im = Sc.imag();
if (fabs(Sc_im)<1e-20) Sc_im=-1e-20;
if (fabs(Sm)<1e-20) Sm=-1e-20;
if (fabs(Sc_im)>=1e-20 && fabs(Sm)>=1e-20){
found = true;
lorentzm[j].Set(zero, Sc_im, Sm, dSc.real(), dSc.imag(), dSm);
lorentzp[j].Set(zero, Sc_im, Sc_im, dSc.real(), dSc.imag(), dSc.imag());
//cout<<"Sc.im="<<Sc.imag()<<" Sm="<<Sm<<" dSc.r="<<dSc.real()<<" dSc.i="<<dSc.imag()<<" dSm="<<dSm<<endl;
//cout<<"zero="<<zero<<" ratio="<<ratio<<" Sm="<<Sm<<" dSm="<<dSm<<" Sc_im="<<Sc_im<<endl;
cout<<"Found lorentz at "<<setw(4)<<left<<j<<right<<setw(10)<<zero<<" lm="<<lorentzm[j]<<" lp="<<lorentzp[j]<<" r-"<<setw(15)<<ratio<<endl;
}
}
}
if (!found){
lorentzp[j].SetFalse();
lorentzm[j].SetFalse();
}
}
}
// // We want to make sure that only one integer occupacition is treated with lorentz
// // because we did not yet implement Lorentz*Lorentz
// int MaxMtot=0;
// for (int i=0; i<Na; i++) if (MaxMtot<common::Mtot[i]) MaxMtot = common::Mtot[i];
// function1D<int> lorex(MaxMtot+1);lorex=0;
// for (int j=0; j<Na; j++) if (lorentzm[j].exist ||lorentzp[j].exist) lorex[common::Mtot[j]]++;
// int imaxLorentz=0;
// for (int i=0; i<=MaxMtot; i++) if (lorex[i]>lorex[imaxLorentz]) imaxLorentz=i;
// for (int i=0; i<Na; i++){
// if (lorentzm[i].exist && common::Mtot[i]!=imaxLorentz) { cout<<"Lorentzm for "<<i<<" not accepted!"<<endl; lorentzm[i].SetFalse();}
// if (lorentzp[i].exist && common::Mtot[i]!=imaxLorentz) { cout<<"Lorentzp for "<<i<<" not accepted!"<<endl; lorentzp[i].SetFalse();}
// }
for (int j=0; j<Na; j++){
double mune = -Energy[j]+lambda0;
dQ[j]=0;
for (int i=0; i<om.size(); i++){
Gt(j,i) = Sigt(j,i)/(sqr(om[i]+mune-Sigc(j,i).real())+sqr(Sigc(j,i).imag()));
Gm(j,i) = fe[i]*Gt(j,i);
Gp(j,i) = (1-fe[i])*Gt(j,i);
if (lorentzm[j].exist) Gm(j,i) -= lorentzm[j].V(om[i]);
if (lorentzp[j].exist) Gp(j,i) -= lorentzp[j].V(om[i]);
dQ[j] -= Gm(j,i)*om.Dh(i);
}
dQ[j] -= lorentzm[j].P*M_PI;
dQ[j] *= common::deg[j]/M_PI;
sumQ += dQ[j];
sumnd += dQ[j]*common::Mtot[j];
}
clog<<" Q = "<<sumQ<<endl;
for (int j=0; j<Na; j++){
Probability[j] = dQ[j]/sumQ;
clog<<setprecision(16)<<" n"<<j<<"="<<dQ[j]/sumQ<<endl;
}
for (int b=0; b<baths; b++){
common::nalpha[b]=0;
for (int j=0; j<Na; j++) common::nalpha[b] += dQ[j]*common::Ms[j][b];
common::nalpha[b]/=sumQ;
}
common::Q = sumQ;
common::Fimp = common::lambda0-common::T * ::log(common::Q);
double Epot=0;
for (int j=0; j<Na; j++) Epot += Probability[j]*Energy[j];
double dEpot=0;
for (int b=0; b<baths; b++) dEpot += common::Ed[b]*common::nalpha[b];
common::Epot = Epot-dEpot;
clog<<" Fimp="<<common::Fimp<<" Epot="<<common::Epot<<" Epot+OneP="<<Epot<<endl;
// if (fabs(sumQ-common::Q0)>1e-10) cerr<<"Something wrong with Q "<<sumQ<<"!"<<endl;
clog<<" Q is here equal to "<<sumQ<<endl;
return sumnd/sumQ;
}
void Auxiliary::Print(int l, string dir="")
{
string filename;
if (l<0) filename = common::outdir+"/Sigma"+dir;
else filename = NameOfFile(common::outdir+"/Sigma", l);
ofstream out1(filename.c_str()); out1.precision(16);
common::printHead(out1)<<" peakposition="<<om.dcenter()<<endl;
for (int i=0; i<om.size(); i++){
out1<<setw(25)<<om[i];
for (int j=0; j<Na; j++) out1<<setw(25)<<Sigc(j,i).real()<<" "<<setw(25)<<-Sigt(j,i);
out1<<endl;
}
if (l<0) filename = common::outdir+"/Spec"+dir;
else filename = NameOfFile(common::outdir+dir+"/Spec", l);
ofstream out2(filename.c_str()); out2.precision(16);
common::printHead(out2)<<" peakposition="<<om.dcenter()<<endl;
for (int i=0; i<om.size(); i++){
out2<<setw(25)<<om[i];
for (int j=0; j<Na; j++) out2<<setw(25)<<-Gt(j,i);
for (int j=0; j<Na; j++) out2<<setw(25)<<-Gp(j,i);
for (int j=0; j<Na; j++) out2<<setw(25)<<-Gm(j,i);
out2<<endl;
}
}
void Auxiliary::Printn(int l)
{
string filename;
filename = NameOfFile(common::outdir+"/nSigma", l);
ofstream out1(filename.c_str()); out1.precision(16);
common::printHead(out1)<<" peakposition="<<om.dcenter()<<endl;
for (int i=0; i<om.size(); i++){
out1<<setw(25)<<om[i];
for (int j=0; j<Na; j++) out1<<setw(25)<<-Sigtn(j,i);
out1<<endl;
}
}
Physical::Physical(int Na_, int Nc_, int baths_) : Na(Na_), Nc(Nc_), baths(baths_), aF(Na)
{
Pexists.resize(Na);
for (int j=0; j<Na; j++){
Pexists[j]=false;
for (int b=0; b<baths; b++){
for (map<int,double>::const_iterator l=common::sncab[j][b].begin(); l!=common::sncab[j][b].end(); l++){
if (l->first >=0 && l->first < Na){
Pexists[j]=true;
break;
}
}
}
if (!Pexists[j] && common::cmp_susc){
for (map<int,double>::const_iterator l=common::suscb[j].begin(); l!=common::suscb[j].end(); l++)
if (l->first >=0 && l->first < Na){
Pexists[j]=true;
break;
}
}
}
}
bool Physical::ReadBeginning(const string& filename, istream& input, int& n, int& m, bool& begincomment, double& center)
{
if (!input) {
cerr << "Can't open input file: " << filename << endl;
return false;
}
// Is the input file started with comment?
begincomment = false;
n = 0;
string str;
getline(input,str);
if (str.find('#')<string::npos){
begincomment = true;
if (!ReadValue(center, "peakposition", str)) center=0;
} else n++;
// Computes the number of columns in file
if (!input) {
cerr << "ERROR: Wrong file format for Sigm" << endl;
return false;
}
getline(input,str); n++;
stringstream oneline;
oneline << str << ends;
m=0; double t;
while (oneline){oneline>>t; m++;}
m--;
while (input){ getline(input,str); n++;}
n--;
clog << filename << ": Number of entries: "<< n <<endl;
clog << filename << ": Number of columns: "<< m <<endl;
clog << filename << ": Peak-position "<< center <<endl;
input.seekg(0, ios::beg);
input.clear();
if (begincomment) getline(input, str);
return true;
}
bool Physical::ReadBathFunction(const string& filename, bool spectra=true) // spectra=true: only spectral function will be read not the retarded quantity
{
ifstream inputf(filename.c_str());
istream input(inputf.rdbuf());
input.seekg(0,ios::beg);
if (!input) {
cerr << "Can't open input file: " << filename << endl;
return false;
}
// Is the input file started with comment?
bool begincomment = false;
int n = 0;
string str;
double center=0;
getline(input,str);
if (str.find('#')<string::npos){
begincomment = true;
if (!ReadValue(center, "peakposition", str)) center=0;
} else n++;
// Computes the number of columns in file
if (!input) {
cerr << "ERROR: Wrong file format for " << filename << endl;
return false;
}
getline(input,str); n++;
#ifdef _STRSTREAM
strstream oneline;
oneline << str <<ends;
#else
istringstream oneline(str);
#endif
int m=0; double t;
while (oneline){oneline>>t; m++;}
m--;
while (input){ getline(input,str); n++;}
n--;
clog << filename << ": Number of entries: "<< n <<endl;
clog << filename << ": Number of columns: "<< m <<endl;
clog << filename << ": Peak-position "<< center <<endl;
int number_cols = baths+1;
if (!spectra) number_cols = 2*baths+1;
if (m<number_cols){
cerr<<"ERROR: Not enough columns in bath input file! Exiting..."<<endl;
return false;
}
inputf.seekg(0, ios::beg);
clog<<"Premaknil na "<< inputf.tellg()<<endl;
if (begincomment) inputf.ignore(1000,'\n');
if (!inputf){ cerr<<"Reopening didn't suceeded!"<<endl; return false;}
omd.resize(n);
momd.resize(n);
G00.resize(baths,n);
A00.resize(baths,n);
A00c.resize(baths,n);
Sig.resize(baths,n);
Ac.resize(baths,n);
Delta0.resize(baths,n);
if (common::cmp_susc){
C00.resize(n);
Chi.resize(n);
}
int l=0;
double omega;
while (inputf>>omega && l<n){
omd[l] = omega;
if (spectra)
for (int j=0; j<baths; j++) inputf>>Ac(j,l);
else{
for (int j=0; j<baths; j++) {
double dr, di;
inputf>>dr; inputf>>di;
Ac(j,l) = -di/M_PI;
Delta0(j,l) = dcomplex(dr,di);
}
}
getline(inputf, str);
momd[n-l-1] = -omd[l];
l++;
}
inputf.close();
if (l<n) cerr<<"Something wrong by reading file "<<filename<<endl;
omd.SetUp(center);
momd.SetUp(-center);
fed.CalcFermOnMesh(common::beta, omd);
th.CalcTanhOnMesh(common::beta, omd);
logod.CalcLogOnMesh(omd);
if (spectra){
for (int b=0; b<baths; b++){
for (int i=0; i<omd.size(); i++){
double Deltar = ::KramarsKronig(Ac[b], omd, omd[i], i, Ac[b][i]);
Delta0(b,i) = dcomplex(-M_PI*Deltar,-M_PI*Ac[b][i]);
}
}
}
return true;
}
void Physical::CalculateProducts(double u, double fu, const mesh1D& om, const function2D<double>& Gm)
{
apar ap;
cintpar pi;
tint position = om.InitInterpLeft();
InterpLeft(om[0]-u, om, position, pi);
#pragma omp parallel for
for (int i=0; i<Na; i++) if (Pexists[i]) aF[i].InterpolateFirst(pi);
InterpLeft(om[1]-u, om, position, pi);
ap.SetUpCsFirst(u, om);
#pragma omp parallel for
for (int i=0; i<Na; i++) if (Pexists[i]) Gtx(i,0) = aF[i].InterpolateNext(pi, ap) * om.Dh(0);
for (int j=1; j<om.size()-1; j++){
InterpLeft(om[j+1]-u, om, position, pi);
ap.SetUpCs(u, j, om, om.Dh(pi.i+1));
//#pragma omp parallel for
for (int i=0; i<Na; i++) if (Pexists[i]) Gtx(i,j) = aF[i].InterpolateNext(pi, ap) * om.Dh(j);
}
ap.SetUpCsLast(u, om);
#pragma omp parallel for
for (int i=0; i<Na; i++) if (Pexists[i]) Gtx(i,om.size()-1) = aF[i].InterpolateLast(ap) * om.Dh(om.size()-1);
Cmp.resize(Na,Na);
#pragma omp parallel for
for (int i=0; i<Na; i++){
for (int b=0; b<baths; b++){
for (map<int,double>::const_iterator l=common::sncab[i][b].begin(); l!=common::sncab[i][b].end(); l++){
int ind = l->first;
if (ind>=0 && ind<Na) Cmp(i,ind) = product(Gtx[i].MemPt(),Gm[ind].MemPt(),om.size())/fu;
}
}
if (common::cmp_susc){
for (map<int,double>::const_iterator l=common::suscb[i].begin(); l!=common::suscb[i].end(); l++){
int ind = l->first;
if (ind>=0 && ind<Na) Cmp(i,ind) = product(Gtx[i].MemPt(),Gm[ind].MemPt(),om.size())/fu;
}
}
}
}
void Physical::CalculateA00(const mesh1D& omega, const function2D<double>& Gp, const function2D<double>& Gm,
const function1D<double>& Energy,
const vector<sLorentz>& lorentzm, const vector<sLorentz>& lorentzp)
{
int m = omd.find_(0.0)+1;
Gtx.resize(Na, omega.size());
#pragma omp parallel for
for (int i=0; i<Na; i++) if (Pexists[i]) aF[i].SetUp(Gp[i],omega);
for (int i=0; i<m; i++){
CalculateProducts(omd[i], fed[i], omega, Gm);
#pragma omp parallel for
for (int b=0; b<baths; b++){
double sum=0;
for (int j=0; j<Na; j++)
for (map<int,double>::const_iterator l=common::sncab[j][b].begin(); l!=common::sncab[j][b].end(); l++){
int ind = l->first;
double prf = l->second/common::Ns[b];
if (ind>=0 && ind<Na) sum += prf*Cmp(j,ind);
}
A00(b,i) = sum/(M_PI*M_PI*common::Q);
}
if (common::cmp_susc){
double sum=0;
for (int j=0; j<Na; j++)
for (map<int,double>::const_iterator l=common::suscb[j].begin(); l!=common::suscb[j].end(); l++){
int ind = l->first;
double prf = l->second;
if (ind>=0 && ind<Na) sum += prf*Cmp(j,ind);
}
C00[i] = sum*th[i]/(M_PI*common::Q);
}
}
#pragma omp parallel for
for (int i=0; i<Na; i++) if (Pexists[i]) aF[i].SetUp(Gm[i],omega);
for (int i=m; i<omd.size(); i++){
CalculateProducts(omd[i], (1-fed[i]), omega, Gp);
#pragma omp parallel for
for (int b=0; b<baths; b++){
double sum=0;
for (int j=0; j<Na; j++)
for (map<int,double>::const_iterator l=common::sncab[j][b].begin(); l!=common::sncab[j][b].end(); l++){
int ind = l->first;
double prf = l->second/common::Ns[b];
if (ind>=0 && ind<Na) sum += prf*Cmp(j,ind);
}
A00(b,i) = sum/(M_PI*M_PI*common::Q);
}
if (common::cmp_susc){
double sum=0;
for (int j=0; j<Na; j++)
for (map<int,double>::const_iterator l=common::suscb[j].begin(); l!=common::suscb[j].end(); l++){
int ind = l->first;
double prf = l->second;
if (ind>=0 && ind<Na) sum += prf*Cmp(j,ind);
}
C00[i] = sum*th[i]/(M_PI*common::Q);
}
}
if (common::SubtractLorentz){
for (int b=0; b<baths; b++){
//cout<<"Starting parallel part"<<endl;
double* A00_private = new double[omd.size()];
for (int s=0; s<omd.size(); s++) A00_private[s]=0.0;
for (int i=0; i<Na; i++){
for (map<int,double>::const_iterator l=common::sncab[i][b].begin(); l!=common::sncab[i][b].end(); l++){
int ind = l->first;
if (ind>=0 && ind<Na){
double prf = (l->second/common::Ns[b])/(M_PI*M_PI)/common::Q;
if (lorentzm[ind].exist){
#pragma omp parallel for
for (int j=0; j<m; j++){
double sum=0;
for (int k=0; k<omega.size()-1; k++)
sum += lorentzm[ind].IntgAp(omega[k], omega[k+1], Gp(i,k), Gp(i,k+1), omd[j]);
//A00(b,j) += sum*prf/fed[j];
A00_private[j] += sum*prf/fed[j];
}
}
if (lorentzp[ind].exist){
#pragma omp parallel for
for (int j=m; j<omd.size(); j++){
double sum=0;
for (int k=0; k<omega.size()-1; k++)
sum += lorentzp[ind].IntgAp(omega[k], omega[k+1], Gm(i,k), Gm(i,k+1), omd[j]);
//A00(b,j) += sum*prf/(1-fed[j]);
A00_private[j] += sum*prf/(1-fed[j]);
}
}
if (lorentzp[i].exist){
#pragma omp parallel for
for (int j=0; j<m; j++){
double sum=0;
for (int k=0; k<omega.size()-1; k++)
sum += lorentzp[i].IntgAp(omega[k], omega[k+1], Gm(ind,k), Gm(ind,k+1), -omd[j]);
//A00(b,j) += sum*prf/fed[j];
A00_private[j] += sum*prf/fed[j];
}
}
if (lorentzm[i].exist){
#pragma omp parallel for
for (int j=m; j<omd.size(); j++){
double sum=0;
for (int k=0; k<omega.size()-1; k++)
sum += lorentzm[i].IntgAp(omega[k], omega[k+1], Gp(ind,k), Gp(ind,k+1), -omd[j]);
//A00(b,j) += sum*prf/(1-fed[j]);
A00_private[j] += sum*prf/(1-fed[j]);
}
}
if (lorentzm[ind].exist && lorentzp[i].exist)
#pragma omp parallel for
for (int j=0; j<m; j++){
//A00(b,j) += lorentzm[ind].IntgApLL(lorentzp[i], omd[j]) * prf/fed[j];
A00_private[j] += lorentzm[ind].IntgApLL(lorentzp[i], omd[j]) * prf/fed[j];
}
if (lorentzp[ind].exist && lorentzm[i].exist)
#pragma omp parallel for
for (int j=m; j<omd.size(); j++){
//A00(b,j) += lorentzp[ind].IntgApLL(lorentzm[i], omd[j]) * prf/(1-fed[j]);
A00_private[j] += lorentzp[ind].IntgApLL(lorentzm[i], omd[j]) * prf/(1-fed[j]);
}
}
}
}
for (int s=0; s<omd.size(); s++) A00(b,s) += A00_private[s];
delete[] A00_private;
//cout<<"Just ended parallel part"<<endl;
}
if (common::cmp_susc){
for (int i=0; i<Na; i++){
for (map<int,double>::const_iterator l=common::suscb[i].begin(); l!=common::suscb[i].end(); l++){
int ind = l->first;
if (ind>=0 && ind<Na){
double prf = (l->second)/(M_PI*common::Q);
if (lorentzm[ind].exist){
for (int j=0; j<m; j++){
double sum=0;
for (int k=0; k<omega.size()-1; k++)
sum += lorentzm[ind].IntgAp(omega[k], omega[k+1], Gp(i,k), Gp(i,k+1), omd[j]);
C00[j] += sum*prf*th[j]/fed[j];
}
}
if (lorentzp[ind].exist){
for (int j=m; j<omd.size(); j++){
double sum=0;
for (int k=0; k<omega.size()-1; k++)
sum += lorentzp[ind].IntgAp(omega[k], omega[k+1], Gm(i,k), Gm(i,k+1), omd[j]);
C00[j] += sum*prf*th[j]/(1-fed[j]);
}
}
if (lorentzp[i].exist){
for (int j=0; j<m; j++){
double sum=0;
for (int k=0; k<omega.size()-1; k++)
sum += lorentzp[i].IntgAp(omega[k], omega[k+1], Gm(ind,k), Gm(ind,k+1), -omd[j]);
C00[j] += sum*prf*th[j]/fed[j];
}
}
if (lorentzm[i].exist){
for (int j=m; j<omd.size(); j++){
double sum=0;
for (int k=0; k<omega.size()-1; k++)
sum += lorentzm[i].IntgAp(omega[k], omega[k+1], Gp(ind,k), Gp(ind,k+1), -omd[j]);
C00[j] += sum*prf*th[j]/(1-fed[j]);
}
}
if (lorentzm[ind].exist && lorentzp[i].exist)
for (int j=0; j<m; j++)
C00[j] += lorentzm[ind].IntgApLL(lorentzp[i], omd[j]) * prf * th[j]/fed[j];
if (lorentzp[ind].exist && lorentzm[i].exist)
for (int j=m; j<omd.size(); j++)
C00[j] += lorentzp[ind].IntgApLL(lorentzm[i], omd[j]) * prf * th[j]/(1-fed[j]);
}
}
}
}
}
if (common::pcore){
// core stuff
for (int b=0; b<baths; b++){
for (int i=0; i<omd.size(); i++){
double sum1=0;
for (int j=0; j<Na; j++){
for (map<int,double>::const_iterator l=common::sncab[j][b].begin(); l!=common::sncab[j][b].end(); l++){
if (l->first >= Na){
int ind = l->first;
double x = Energy[ind]-common::lambda0-omd[i];
double prf = l->second/common::Ns[b];
sum1 -= prf*Gm[j](omega.Interp(x))/common::Q/M_PI;
}
}
}
double sum2=0;
for (int j=Na; j<Na+Nc; j++){
for (map<int,double>::const_iterator l=common::sncab[j][b].begin(); l!=common::sncab[j][b].end(); l++){
if (l->first >= 0 && l->first<Na){
int ind = l->first;
double x = Energy[j]-common::lambda0+omd[i];
double prf = l->second/common::Ns[b];
sum2 -= prf*Gm[ind](omega.Interp(x))/common::Q/M_PI;
}
}
}
A00c(b,i) = sum1+sum2;
}
}
// Checking doping!
for (int b=0; b<baths; b++){
double suma = 0, sumc = 0;
for (int i=0; i<omd.size(); i++) {
suma += A00(b,i)*fed[i]*omd.Dh(i);
sumc += A00c(b,i)*fed[i]*omd.Dh(i);
}
suma *= common::Ns[b];
sumc *= common::Ns[b];
double miss_nd = common::nalpha[b]-(suma+sumc);
double core_fact = 1.;
if (sumc!=0 && common::renorm_core){
core_fact = (common::nalpha[b]-suma)/sumc;
if (core_fact<0) core_fact=0;
if (core_fact>10) core_fact = 10;
cout<<b<<" : "<<miss_nd<<" renormaliziang core part by "<<core_fact<<endl;
}
for (int i=0; i<omd.size(); i++) A00(b,i) += A00c(b,i)*core_fact;
if (common::renorm){
double suml=0, sumr=0;
for (int i=0; i<omd.size(); i++){
suml += A00(b,i)*fed[i]*omd.Dh(i);
sumr += A00(b,i)*(1-fed[i])*omd.Dh(i);
}
int izero = omd.find_(0.0);
double ml1=0, mr1=0;
for (int i=0; i<izero; i++) {
ml1 += omd[i]*A00(b,i)*fed[i]*omd.Dh(i);
mr1 += omd[i]*A00(b,i)*(1-fed[i])*omd.Dh(i);
}
double ml2=0, mr2=0;
for (int i=izero+1; i<omd.size(); i++) {
ml2 += omd[i]*A00(b,i)*fed[i]*omd.Dh(i);
mr2 += omd[i]*A00(b,i)*(1-fed[i])*omd.Dh(i);
}
double n0 = common::nalpha[b]/common::Ns[b];
double C = (-ml2 + ml2*n0 + mr2*n0 - mr2*suml + ml2*sumr)/(ml1*mr2-ml2*mr1);
double D = (ml1 - ml1*n0 - mr1*n0 + mr1*suml - ml1*sumr)/(ml1*mr2-ml2*mr1);
if (1+C*omd[0]<0) C = -1/omd[0];
if (1+D*omd.last()<0) D = -1/omd.last();
for (int i=0; i<izero; i++) A00(b,i) *= (1+C*omd[i]);
for (int i=izero+1; i<omd.size(); i++) A00(b,i) *= (1+D*omd[i]);
cout<<"Renormalizing A["<<b<<"] by "<<C<<", "<<D<<"at negative and positive frequency"<<endl;
}
}
}
// ofstream out("Aloc.imp"); out.precision(16);
// for (int i=0; i<omd.size(); i++){
// out<<setw(25)<<omd[i]<<" ";
// for (int b=0; b<baths; b++) out<<setw(25)<<A00(b,i)<<" ";
// out<<endl;
// }
}
inline void Physical::KramarsKronig()
{
for (int b=0; b<baths; b++) G00[b].KramarsKronig(omd,logod);
}
void Physical::CalcSelfEnergy()
{
for (int b=0; b<baths; b++){
for (int i=0; i<omd.size(); i++){
//double Deltar = ::KramarsKronig(Ac[b], omd, omd[i], i, Ac[b][i]);
//dcomplex Delta(-M_PI*Deltar,-M_PI*Ac[b][i]);
Sig[b][i] = omd[i]-common::Ed[b]-Delta0[b][i]-1/G00[b][i];
if (Sig[b][i].imag()>0) Sig[b][i].imag()=0.0;
}
}
if (common::cmp_susc){
for (int i=0; i<omd.size(); i++)
Chi[i] = dcomplex(::KramarsKronig(C00, omd, omd[i], i, C00[i]),C00[i]);
}
}
void Physical::Print(int n, string dir="")
{
string filename;
if (n<0) filename = common::outdir+"/A00"+dir;
else filename = common::outdir+NameOfFile("/A00",n,3);
ofstream out(filename.c_str()); out.precision(16);
common::printHead(out)<<" peakposition=" << omd.dcenter()<<endl;
for (int i=0; i<omd.size(); i++){
out <<setw(25)<<omd[i];
for (int b=0; b<baths; b++)
out<<setw(25)<<A00[b][i]<<setw(25)<<G00[b][i]<<setw(25)<<-Sig[b][i];
out<<endl;
}
if (n<0) filename = common::outdir+"/Susc"+dir;
else filename = common::outdir+NameOfFile("/Susc",n,3);
ofstream outs(filename.c_str()); outs.precision(16);
common::printHead(outs)<<" peakposition=" << omd.dcenter()<<endl;
for (int i=0; i<omd.size(); i++)
outs <<setw(25)<<omd[i]<<setw(25)<<Chi[i]<<endl;
}
void Physical::Print0(const string& filename)
{
ofstream out(filename.c_str()); out.precision(16);
common::printHead(out)<<" peakposition=" << omd.dcenter()<<endl;
for (int i=0; i<omd.size(); i++){
out <<setw(25)<<omd[i];
for (int b=0; b<baths; b++) out<<setw(25)<<A00[b][i];
for (int b=0; b<baths; b++) out<<setw(25)<<G00[b][i];
for (int b=0; b<baths; b++) out<<setw(25)<<-Sig[b][i];
out<<endl;
}
}
double Auxiliary::DeterminSelfEnergies(double alpha,int CmpDiff){
double beta=1-alpha;
Sigtmp.resize(om.size());
if (CmpDiff<0) CmpDiff = Na;
double diff=0, norm=0;
for (int j=0; j<Na; j++){
for (int i=0; i<om.size(); i++) if (Sigtn(j,i)>0) Sigtn(j,i)=0;
for (int i=0; i<om.size(); i++) Sigtmp[i].imag() = Sigtn(j,i)*(1-fe[i]);
Sigtmp.KramarsKronig(om, logo);
for (int i=0; i<om.size(); i++){
dcomplex Sigcn = Sigtmp[i] + Sigcore(j,i);
Sigtn(j,i) += Sigcore(j,i).imag();
if (j<CmpDiff){
diff += fabs(Sigtn(j,i)-Sigt(j,i));
norm += fabs(Sigt(j,i));
}
Sigt(j,i) = beta*Sigt(j,i)+alpha*Sigtn(j,i);
Sigc(j,i) = beta*Sigc(j,i)+alpha*Sigcn;
}
}
return diff/norm;
}
void Physical::DeterminG00(double alpha,ostream& loging)
{
double beta=1-alpha;
double alphapi=-alpha*M_PI;
for (int b=0; b<baths; b++){
for (int j=0; j<omd.size(); j++)
G00[b][j].imag()=beta*G00[b][j].imag()+alphapi*A00[b][j];
G00[b].KramarsKronig(omd,logod);
}
common::TrLogGimp=0.0;
for (int b=0; b<baths; b++){
double Ndf=0.0;
double dsum=0;
for (int j=0; j<omd.size(); j++){
dsum += -log(-G00[b][j]).imag()*fed[j]*omd.Dh(j)/M_PI;
Ndf += -G00[b][j].imag()*fed[j]*omd.Dh(j)/M_PI;
}
common::TrLogGimp += dsum*common::Ns[b];
Ndf *= common::Ns[b];
loging<<"Expected density:"<<common::nalpha[b]<<" numerical density:"<<Ndf<<endl;
}
loging<<"TrLogGimp="<<common::TrLogGimp<<endl;
}
void Auxiliary::PrintNorm(ostream& stream)
{
stream<<" Norm of Spectral functions: "<<endl<<" ";
stream.setf(ios::fixed);
for (int i=0; i<Na; i++){
double sum=0;
for (int j=0; j<om.size(); j++)
sum += Gp(i,j)*om.Dh(j);
sum += lorentzp[i].P*M_PI;
sum/=-M_PI;
double norm0=1;
stream<<setprecision(4)<<" ";
if (fabs(sum-norm0)<1e-2)
stream<<COLOR(GREEN,setw(2)<<i<<":"<<setw(8)<<sum)<<" ";
else if (fabs(sum-norm0)<1e-1)
stream<<COLOR(YELLOW,setw(2)<<i<<":"<<setw(8)<<sum)<<" ";
else
stream<<COLOR(PURPLE,setw(2)<<i<<":"<<setw(8)<<sum)<<" ";
if ((i+1)%6==0) stream<<endl<<" ";
}
stream<<endl;
for (int b=0; b<baths; b++){
stream<<setprecision(4)<<" "<<COLOR(BLUE,setw(2)<<b<<":"<<setw(8)<<common::nalpha[b])<<" ";
}
stream<<endl;
stream.unsetf(ios::fixed);
}
void Physical::PrintA00(ostream& out)
{
out.precision(16);
common::printHead(out)<<" peakposition=" << omd.dcenter()<<endl;
for (int i=0; i<omd.size(); i++){
out<<setw(25)<<omd[i];
for (int b=0; b<baths; b++)
out<<setw(25)<<A00[i];
out<<endl;
}
}
double Auxiliary::Difference(){
double diff=0, norm=0;
for (int j=0; j<Na; j++){
for (int i=0; i<om.size(); i++){
diff += fabs(Sigtn(j,i)-Sigt(j,i));
norm += 0.5*fabs(Sigtn(j,i)+Sigtn(j,i));
}
}
return diff/norm;
}
/******************* Used only for debugging **********************/
void Auxiliary::PrintSign()
{
for (int i=0; i<Na; i++){
ofstream out(NameOfFile("Sign",i,2).c_str());
out.precision(16);
for (int j=0; j<om.size(); j++)
out<<setw(25)<<om[j]<<setw(25)<<-Sigtn[i][j]<<endl;
}
}
void Auxiliary::Print_aAc(int l)
{
for (int i=0; i<aAc[0].size_N(); i++){
ofstream out(NameOfFile_("aAc",l,i,1,3).c_str());
out.precision(16);
for (int j=0; j<aAc[0].size_Nd(); j++){
out<<setw(25)<<om[j]<<setw(25)<<aAc[0][i][j]/om.Dh(j)<<endl;
}
}
}
/******************* New things ******************************/
void common::ParsInputFile(const string& filename)
{
ifstream input(filename.c_str());
string line;
getline(input,line);
input>>baths;
Ns.resize(baths);
for (int i=0; i<baths; i++) input>>Ns[i];
input>>Na;
input>>Nc;
getline(input,line); getline(input,line);
if (!input){ cerr<<filename<<" file not recognized. Error in first 3 lines!"<<endl; exit(1);}
deg.resize(Na+Nc);
Ms.resize(Na+Nc,baths);
Mtot.resize(Na+Nc);
sJc.resize(Na+Nc);
ncab.resize(Na+Nc, baths);
ncaf.resize(Na+Nc, baths);
prefactb.resize(Na+Nc, baths);
prefactf.resize(Na+Nc, baths);
prefactG.resize(Na+Nc, baths);
sncab.resize(Na+Nc);
sncaf.resize(Na+Nc);
for (int i=0; i<Na+Nc; i++) sncab[i].resize(baths);
for (int i=0; i<Na+Nc; i++) sncaf[i].resize(baths);
vector<int> Nncab(baths), Nncaf(baths);
for (int i=0; i<Na+Nc; i++){
getline(input, line);
if (!input){ cerr<<filename<<" file not recognized. Error in line number "<<i+3<<endl; exit(1);}
stringstream thisline(line);
int lc;
thisline>>lc;
for (int j=0; j<baths; j++) thisline>>Ms[i][j];
thisline>>Mtot[i]>>deg[i]>>sJc[i];
for (int j=0; j<baths; j++) thisline>>Nncab[j];
for (int j=0; j<baths; j++) thisline>>Nncaf[j];
string cross; double fct; int ind;
for (int j=0; j<baths; j++){
for (int k=0; k<Nncab[j]; k++){
thisline>>fct>>cross>>ind;
sncab[i][j][ind]=fct;
}
}
for (int j=0; j<baths; j++){
for (int k=0; k<Nncaf[j]; k++){
thisline>>fct>>cross>>ind;
sncaf[i][j][ind]=fct;
}
}
if (!input){ cerr<<filename<<" file not recognized. Error in line number "<<i+3<<endl; exit(1);}
}
getline(input, line);// comment
cmp_susc = false;
if (input){
suscb.resize(Na);
for (int i=0; i<Na; i++){
getline(input, line);
if (!input) goto exit_loop;
stringstream thisline(line);
int lc;
thisline>>lc;
int ndiagram;
thisline>>ndiagram;
string cross; double fct; int ind;
for (int j=0; j<ndiagram; j++){
thisline>>fct>>cross>>ind;
suscb[i][ind]=fct;
}
}
cmp_susc = true;
}
exit_loop:
PrintParsedData(cout);
totDeg = 0;
for (int i=0; i<Na; i++) totDeg += deg[i];
}
void common::PrintParsedData(ostream& stream)
{
stream<<baths<<" ";
for (int i=0; i<baths; i++) stream<<Ns[i]<<" ";
stream<<Na<<" "<<Nc<<endl;
for (int i=0; i<Na+Nc; i++){
stream<<setw(3)<<i<<" ";
if (i<Na) stream<<"v ";
else stream<<"c ";
for (int j=0; j<baths; j++) stream<<setw(10)<<Ms[i][j];
stream<<setw(4)<<Mtot[i]<<setw(5)<<deg[i]<<setw(6)<<sJc[i];
for (int b=0; b<baths; b++) stream<<setw(2)<<sncab[i][b].size()<<" ";
for (int b=0; b<baths; b++) stream<<setw(2)<<sncaf[i][b].size()<<" ";
for (int b=0; b<baths; b++)
for (map<int,double>::const_iterator l=sncab[i][b].begin(); l!=sncab[i][b].end(); l++)
stream<<setw(6)<<l->second<<" x "<<setw(4)<<left<<l->first<<right;
for (int b=0; b<baths; b++)
for (map<int,double>::const_iterator l=sncaf[i][b].begin(); l!=sncaf[i][b].end(); l++)
stream<<setw(6)<<l->second<<" x "<<setw(4)<<left<<l->first<<right;
stream<<endl;
}
if (!cmp_susc) return;
stream<<"Susceptibility digrams:"<<endl;
for (int i=0; i<Na; i++){
stream<<setw(3)<<i<<" ";
for (map<int,double>::const_iterator l=suscb[i].begin(); l!=suscb[i].end(); l++)
stream<<setw(6)<<l->second<<" x "<<setw(4)<<left<<l->first<<right;
stream<<endl;
}
}
void print(std::ostream& stream, const mesh1D& om, const function2D<dcomplex>& f, int width=20)
{
if (om.size()!=f.size_Nd()) std::cerr<<"Can't print objectc of different size!"<<std::endl;
for (int i=0; i<om.size(); i++){
stream <<std::setw(width)<<om[i];
for (int j=0; j<f.size_N(); j++) stream<<std::setw(width)<<f(j,i);
stream<<std::endl;
}
}
void Physical::MissingDoping(double start)
{
cout<<"Missing doping : ";
for (int b=0; b<baths; b++){
double sum = 0;
for (int i=0; i<omd.size(); i++) {
if (omd[i]>start) sum += G00[b][i].imag()*fed[i]*omd.Dh(i);
}
sum *= -common::Ns[b]/M_PI;
common::miss_nd[b] = common::nalpha[b]-sum;
cout<<b<<" : "<<common::miss_nd[b]<<" ";
}
cout<<endl;
common::Sinfty.resize(baths);
for (int b=0; b<baths; b++){
double sum0 = 0, sum1 = 0;
for (int i=0; i<omd.size(); i++) {
sum0 += A00(b,i)*omd.Dh(i);
sum1 += A00(b,i)*omd[i]*omd.Dh(i);
}
common::moment[b][0] = sum0;
common::moment[b][1] = sum1;
common::Sinfty[b] = sum1/sum0-common::Ed[b];
}
}
void Auxiliary::PrintCore(const string& filename)
{
ofstream out(filename.c_str());
for (int i=0; i<om.size(); i++){
out<<setw(20)<<om[i]<<" ";
for (int j=0; j<Na; j++){
out<<setw(20)<<Sigcore[j][i]<<" ";
}
out<<endl;
}
}
#endif
|
ams.c | /******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
#include "_hypre_parcsr_ls.h"
#include "float.h"
#include "ams.h"
#include "_hypre_utilities.hpp"
/*--------------------------------------------------------------------------
* hypre_ParCSRRelax
*
* Relaxation on the ParCSR matrix A with right-hand side f and
* initial guess u. Possible values for relax_type are:
*
* 1 = l1-scaled (or weighted) Jacobi
* 2 = l1-scaled block Gauss-Seidel/SSOR
* 3 = Kaczmarz
* 4 = truncated version of 2 (Remark 6.2 in smoothers paper)
* x = BoomerAMG relaxation with relax_type = |x|
* (16 = Cheby)
*
* The default value of relax_type is 2.
*--------------------------------------------------------------------------*/
#if defined(HYPRE_USING_CUDA)
struct l1_norm_op1 : public thrust::binary_function<HYPRE_Complex, HYPRE_Complex, HYPRE_Complex>
{
__host__ __device__
HYPRE_Complex operator()(HYPRE_Complex &x, HYPRE_Complex &y) const
{
return x <= 4.0/3.0 * y ? y : x;
}
};
#endif
HYPRE_Int hypre_ParCSRRelax(/* matrix to relax with */
hypre_ParCSRMatrix *A,
/* right-hand side */
hypre_ParVector *f,
/* relaxation type */
HYPRE_Int relax_type,
/* number of sweeps */
HYPRE_Int relax_times,
/* l1 norms of the rows of A */
HYPRE_Real *l1_norms,
/* damping coefficient (usually <= 1) */
HYPRE_Real relax_weight,
/* SOR parameter (usually in (0,2) */
HYPRE_Real omega,
/* for cheby smoothers */
HYPRE_Real max_eig_est,
HYPRE_Real min_eig_est,
HYPRE_Int cheby_order,
HYPRE_Real cheby_fraction,
/* initial/updated approximation */
hypre_ParVector *u,
/* temporary vector */
hypre_ParVector *v,
/* temporary vector */
hypre_ParVector *z)
{
HYPRE_Int sweep;
HYPRE_Complex *u_data = hypre_VectorData(hypre_ParVectorLocalVector(u));
HYPRE_Complex *f_data = hypre_VectorData(hypre_ParVectorLocalVector(f));
HYPRE_Complex *v_data = hypre_VectorData(hypre_ParVectorLocalVector(v));
for (sweep = 0; sweep < relax_times; sweep++)
{
if (relax_type == 1) /* l1-scaled Jacobi */
{
HYPRE_Int num_rows = hypre_ParCSRMatrixNumRows(A);
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_DEVICE_OPENMP)
HYPRE_Int sync_stream = hypre_HandleCudaComputeStreamSync(hypre_handle());
hypre_HandleCudaComputeStreamSync(hypre_handle()) = 0;
#endif
hypre_ParVectorCopy(f, v);
hypre_ParCSRMatrixMatvec(-relax_weight, A, u, relax_weight, v);
#if defined(HYPRE_USING_CUDA)
hypreDevice_IVAXPY(num_rows, l1_norms, v_data, u_data);
#else /* #if defined(HYPRE_USING_CUDA) */
HYPRE_Int i;
/* u += w D^{-1}(f - A u), where D_ii = ||A(i,:)||_1 */
#if defined(HYPRE_USING_DEVICE_OPENMP)
#pragma omp target teams distribute parallel for private(i) is_device_ptr(u_data,v_data,l1_norms)
#endif
for (i = 0; i < num_rows; i++)
{
u_data[i] += v_data[i] / l1_norms[i];
}
#endif /* #if defined(HYPRE_USING_CUDA) */
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_DEVICE_OPENMP)
hypre_HandleCudaComputeStreamSync(hypre_handle()) = sync_stream;
hypre_SyncCudaComputeStream(hypre_handle());
#endif
}
else if (relax_type == 2 || relax_type == 4) /* offd-l1-scaled block GS */
{
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_I = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_J = hypre_CSRMatrixJ(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *A_offd_I = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_J = hypre_CSRMatrixJ(A_offd);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int i, j;
HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd);
HYPRE_Real *u_offd_data = hypre_TAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST);
HYPRE_Real res;
HYPRE_Int num_procs;
hypre_MPI_Comm_size(hypre_ParCSRMatrixComm(A), &num_procs);
/* Copy off-diagonal values of u to the current processor */
if (num_procs > 1)
{
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
HYPRE_Int num_sends;
HYPRE_Real *u_buf_data;
hypre_ParCSRCommHandle *comm_handle;
HYPRE_Int index = 0, start;
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(A);
comm_pkg = hypre_ParCSRMatrixCommPkg(A);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
u_buf_data = hypre_TAlloc(HYPRE_Real,
hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST);
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++)
u_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate(1,comm_pkg,u_buf_data,u_offd_data);
hypre_ParCSRCommHandleDestroy(comm_handle);
hypre_TFree(u_buf_data, HYPRE_MEMORY_HOST);
}
if (relax_weight == 1.0 && omega == 1.0) /* symmetric Gauss-Seidel */
{
/* Forward local pass */
for (i = 0; i < num_rows; i++)
{
res = f_data[i];
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
res -= A_diag_data[j] * u_data[A_diag_J[j]];
if (num_cols_offd)
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
res -= A_offd_data[j] * u_offd_data[A_offd_J[j]];
u_data[i] += res / l1_norms[i];
}
/* Backward local pass */
for (i = num_rows-1; i > -1; i--)
{
res = f_data[i];
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
res -= A_diag_data[j] * u_data[A_diag_J[j]];
if (num_cols_offd)
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
res -= A_offd_data[j] * u_offd_data[A_offd_J[j]];
u_data[i] += res / l1_norms[i];
}
}
else if (relax_weight == 1.0) /* SSOR */
{
/* Forward local pass */
for (i = 0; i < num_rows; i++)
{
res = f_data[i];
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
res -= A_diag_data[j] * u_data[A_diag_J[j]];
if (num_cols_offd)
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
res -= A_offd_data[j] * u_offd_data[A_offd_J[j]];
u_data[i] += omega * res / l1_norms[i];
}
/* Backward local pass */
for (i = num_rows-1; i > -1; i--)
{
res = f_data[i];
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
res -= A_diag_data[j] * u_data[A_diag_J[j]];
if (num_cols_offd)
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
res -= A_offd_data[j] * u_offd_data[A_offd_J[j]];
u_data[i] += omega * res / l1_norms[i];
}
}
else /* scaled SSOR */
{
HYPRE_Real dif;
HYPRE_Real c1 = omega * relax_weight;
HYPRE_Real c2 = omega * (1.0 - relax_weight);
/* Forward local pass (save initial guess in v_data) */
for (i = 0; i < num_rows; i++)
{
dif = 0.0;
v_data[i] = u_data[i];
res = f_data[i];
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
{
res -= A_diag_data[j] * u_data[A_diag_J[j]];
if (A_diag_J[j] < i)
dif += A_diag_data[j] * (v_data[A_diag_J[j]] - u_data[A_diag_J[j]]);
}
if (num_cols_offd)
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
res -= A_offd_data[j] * u_offd_data[A_offd_J[j]];
u_data[i] += (c1 * res + c2 * dif) / l1_norms[i];
}
/* Backward local pass */
for (i = num_rows-1; i > -1; i--)
{
dif = 0.0;
res = f_data[i];
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
{
res -= A_diag_data[j] * u_data[A_diag_J[j]];
if (A_diag_J[j] > i)
dif += A_diag_data[j] * (v_data[A_diag_J[j]] - u_data[A_diag_J[j]]);
}
if (num_cols_offd)
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
res -= A_offd_data[j] * u_offd_data[A_offd_J[j]];
u_data[i] += (c1 * res + c2 * dif) / l1_norms[i];
}
}
hypre_TFree(u_offd_data, HYPRE_MEMORY_HOST);
}
else if (relax_type == 3) /* Kaczmarz */
{
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_I = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_J = hypre_CSRMatrixJ(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *A_offd_I = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_J = hypre_CSRMatrixJ(A_offd);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int i, j;
HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd);
HYPRE_Real *u_offd_data = hypre_TAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST);
HYPRE_Real res;
HYPRE_Int num_procs;
hypre_MPI_Comm_size(hypre_ParCSRMatrixComm(A), &num_procs);
/* Copy off-diagonal values of u to the current processor */
if (num_procs > 1)
{
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
HYPRE_Int num_sends;
HYPRE_Real *u_buf_data;
hypre_ParCSRCommHandle *comm_handle;
HYPRE_Int index = 0, start;
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(A);
comm_pkg = hypre_ParCSRMatrixCommPkg(A);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
u_buf_data = hypre_TAlloc(HYPRE_Real,
hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST);
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++)
u_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate(1,comm_pkg,u_buf_data,u_offd_data);
hypre_ParCSRCommHandleDestroy(comm_handle);
hypre_TFree(u_buf_data, HYPRE_MEMORY_HOST);
}
/* Forward local pass */
for (i = 0; i < num_rows; i++)
{
res = f_data[i];
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
res -= A_diag_data[j] * u_data[A_diag_J[j]];
if (num_cols_offd)
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
res -= A_offd_data[j] * u_offd_data[A_offd_J[j]];
res /= l1_norms[i];
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
u_data[A_diag_J[j]] += omega * res * A_diag_data[j];
}
/* Backward local pass */
for (i = num_rows-1; i > -1; i--)
{
res = f_data[i];
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
res -= A_diag_data[j] * u_data[A_diag_J[j]];
if (num_cols_offd)
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
res -= A_offd_data[j] * u_offd_data[A_offd_J[j]];
res /= l1_norms[i];
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
u_data[A_diag_J[j]] += omega * res * A_diag_data[j];
}
hypre_TFree(u_offd_data, HYPRE_MEMORY_HOST);
}
else /* call BoomerAMG relaxation */
{
if (relax_type == 16)
{
hypre_ParCSRRelax_Cheby(A,
f,
max_eig_est,
min_eig_est,
cheby_fraction, cheby_order, 1,
0, u, v, z);
}
else
{
hypre_BoomerAMGRelax(A, f, NULL, hypre_abs(relax_type), 0, relax_weight,
omega, l1_norms, u, v, z);
}
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_ParVectorInRangeOf
*
* Return a vector that belongs to the range of a given matrix.
*--------------------------------------------------------------------------*/
hypre_ParVector *hypre_ParVectorInRangeOf(hypre_ParCSRMatrix *A)
{
hypre_ParVector *x;
x = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumRows(A),
hypre_ParCSRMatrixRowStarts(A));
hypre_ParVectorInitialize(x);
hypre_ParVectorOwnsData(x) = 1;
hypre_ParVectorOwnsPartitioning(x) = 0;
return x;
}
/*--------------------------------------------------------------------------
* hypre_ParVectorInDomainOf
*
* Return a vector that belongs to the domain of a given matrix.
*--------------------------------------------------------------------------*/
hypre_ParVector *hypre_ParVectorInDomainOf(hypre_ParCSRMatrix *A)
{
hypre_ParVector *x;
x = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumCols(A),
hypre_ParCSRMatrixColStarts(A));
hypre_ParVectorInitialize(x);
hypre_ParVectorOwnsData(x) = 1;
hypre_ParVectorOwnsPartitioning(x) = 0;
return x;
}
/*--------------------------------------------------------------------------
* hypre_ParVectorBlockSplit
*
* Extract the dim sub-vectors x_0,...,x_{dim-1} composing a parallel
* block vector x. It is assumed that &x[i] = [x_0[i],...,x_{dim-1}[i]].
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_ParVectorBlockSplit(hypre_ParVector *x,
hypre_ParVector *x_[3],
HYPRE_Int dim)
{
HYPRE_Int i, d, size_;
HYPRE_Real *x_data, *x_data_[3];
size_ = hypre_VectorSize(hypre_ParVectorLocalVector(x_[0]));
x_data = hypre_VectorData(hypre_ParVectorLocalVector(x));
for (d = 0; d < dim; d++)
x_data_[d] = hypre_VectorData(hypre_ParVectorLocalVector(x_[d]));
for (i = 0; i < size_; i++)
for (d = 0; d < dim; d++)
x_data_[d][i] = x_data[dim*i+d];
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_ParVectorBlockGather
*
* Compose a parallel block vector x from dim given sub-vectors
* x_0,...,x_{dim-1}, such that &x[i] = [x_0[i],...,x_{dim-1}[i]].
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_ParVectorBlockGather(hypre_ParVector *x,
hypre_ParVector *x_[3],
HYPRE_Int dim)
{
HYPRE_Int i, d, size_;
HYPRE_Real *x_data, *x_data_[3];
size_ = hypre_VectorSize(hypre_ParVectorLocalVector(x_[0]));
x_data = hypre_VectorData(hypre_ParVectorLocalVector(x));
for (d = 0; d < dim; d++)
x_data_[d] = hypre_VectorData(hypre_ParVectorLocalVector(x_[d]));
for (i = 0; i < size_; i++)
for (d = 0; d < dim; d++)
x_data[dim*i+d] = x_data_[d][i];
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_BoomerAMGBlockSolve
*
* Apply the block-diagonal solver diag(B) to the system diag(A) x = b.
* Here B is a given BoomerAMG solver for A, while x and b are "block"
* parallel vectors.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_BoomerAMGBlockSolve(void *B,
hypre_ParCSRMatrix *A,
hypre_ParVector *b,
hypre_ParVector *x)
{
HYPRE_Int d, dim = 1;
hypre_ParVector *b_[3];
hypre_ParVector *x_[3];
dim = hypre_ParVectorGlobalSize(x) / hypre_ParCSRMatrixGlobalNumRows(A);
if (dim == 1)
{
hypre_BoomerAMGSolve(B, A, b, x);
return hypre_error_flag;
}
for (d = 0; d < dim; d++)
{
b_[d] = hypre_ParVectorInRangeOf(A);
x_[d] = hypre_ParVectorInRangeOf(A);
}
hypre_ParVectorBlockSplit(b, b_, dim);
hypre_ParVectorBlockSplit(x, x_, dim);
for (d = 0; d < dim; d++)
hypre_BoomerAMGSolve(B, A, b_[d], x_[d]);
hypre_ParVectorBlockGather(x, x_, dim);
for (d = 0; d < dim; d++)
{
hypre_ParVectorDestroy(b_[d]);
hypre_ParVectorDestroy(x_[d]);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_ParCSRMatrixFixZeroRows
*
* For every zero row in the matrix: set the diagonal element to 1.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_ParCSRMatrixFixZeroRows(hypre_ParCSRMatrix *A)
{
HYPRE_Int i, j;
HYPRE_Real l1_norm;
HYPRE_Int num_rows = hypre_ParCSRMatrixNumRows(A);
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Int *A_diag_I = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_J = hypre_CSRMatrixJ(A_diag);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *A_offd_I = hypre_CSRMatrixI(A_offd);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd);
/* a row will be considered zero if its l1 norm is less than eps */
HYPRE_Real eps = 0.0; /* DBL_EPSILON * 1e+4; */
for (i = 0; i < num_rows; i++)
{
l1_norm = 0.0;
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
l1_norm += fabs(A_diag_data[j]);
if (num_cols_offd)
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
l1_norm += fabs(A_offd_data[j]);
if (l1_norm <= eps)
{
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
if (A_diag_J[j] == i)
A_diag_data[j] = 1.0;
else
A_diag_data[j] = 0.0;
if (num_cols_offd)
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
A_offd_data[j] = 0.0;
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_ParCSRComputeL1Norms
*
* Compute the l1 norms of the rows of a given matrix, depending on
* the option parameter:
*
* option 1 = Compute the l1 norm of the rows
* option 2 = Compute the l1 norm of the (processor) off-diagonal
* part of the rows plus the diagonal of A
* option 3 = Compute the l2 norm^2 of the rows
* option 4 = Truncated version of option 2 based on Remark 6.2 in "Multigrid
* Smoothers for Ultra-Parallel Computing"
*
* The above computations are done in a CF manner, whenever the provided
* cf_marker is not NULL.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_ParCSRComputeL1Norms(hypre_ParCSRMatrix *A,
HYPRE_Int option,
HYPRE_Int *cf_marker,
HYPRE_Real **l1_norm_ptr)
{
HYPRE_Int i, j;
HYPRE_Int num_rows = hypre_ParCSRMatrixNumRows(A);
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd);
HYPRE_MemoryLocation memory_location_l1 = hypre_ParCSRMatrixMemoryLocation(A);
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( memory_location_l1 );
if (exec == HYPRE_EXEC_HOST)
{
HYPRE_Int num_threads = hypre_NumThreads();
if (num_threads > 1)
{
return hypre_ParCSRComputeL1NormsThreads(A, option, num_threads, cf_marker, l1_norm_ptr);
}
}
HYPRE_Real *l1_norm = hypre_TAlloc(HYPRE_Real, num_rows, memory_location_l1);
HYPRE_MemoryLocation memory_location_tmp = exec == HYPRE_EXEC_HOST ? HYPRE_MEMORY_HOST : HYPRE_MEMORY_DEVICE;
HYPRE_Real *diag_tmp = NULL;
HYPRE_Int *cf_marker_offd = NULL, *cf_marker_dev = NULL;
/* collect the cf marker data from other procs */
if (cf_marker != NULL)
{
HYPRE_Int index;
HYPRE_Int num_sends;
HYPRE_Int start;
HYPRE_Int *int_buf_data = NULL;
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle;
if (num_cols_offd)
{
cf_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd, memory_location_tmp);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
if (hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends))
{
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends),
HYPRE_MEMORY_HOST);
}
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
{
int_buf_data[index++] = cf_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
}
comm_handle = hypre_ParCSRCommHandleCreate_v2(11, comm_pkg, HYPRE_MEMORY_HOST, int_buf_data,
memory_location_tmp, cf_marker_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST);
if (exec == HYPRE_EXEC_DEVICE)
{
cf_marker_dev = hypre_TAlloc(HYPRE_Int, num_rows, HYPRE_MEMORY_DEVICE);
hypre_TMemcpy(cf_marker_dev, cf_marker, HYPRE_Int, num_rows, HYPRE_MEMORY_DEVICE, HYPRE_MEMORY_HOST);
}
else
{
cf_marker_dev = cf_marker;
}
}
if (option == 1)
{
/* Set the l1 norm of the diag part */
hypre_CSRMatrixComputeRowSum(A_diag, cf_marker_dev, cf_marker_dev, l1_norm, 1, 1.0, "set");
/* Add the l1 norm of the offd part */
if (num_cols_offd)
{
hypre_CSRMatrixComputeRowSum(A_offd, cf_marker_dev, cf_marker_offd, l1_norm, 1, 1.0, "add");
}
}
else if (option == 2)
{
/* Set the abs(diag) element */
hypre_CSRMatrixExtractDiagonal(A_diag, l1_norm, 1);
/* Add the l1 norm of the offd part */
if (num_cols_offd)
{
hypre_CSRMatrixComputeRowSum(A_offd, cf_marker_dev, cf_marker_offd, l1_norm, 1, 1.0, "add");
}
}
else if (option == 3)
{
/* Set the CF l2 norm of the diag part */
hypre_CSRMatrixComputeRowSum(A_diag, NULL, NULL, l1_norm, 2, 1.0, "set");
/* Add the CF l2 norm of the offd part */
if (num_cols_offd)
{
hypre_CSRMatrixComputeRowSum(A_offd, NULL, NULL, l1_norm, 2, 1.0, "add");
}
}
else if (option == 4)
{
/* Set the abs(diag) element */
hypre_CSRMatrixExtractDiagonal(A_diag, l1_norm, 1);
diag_tmp = hypre_TAlloc(HYPRE_Real, num_rows, memory_location_tmp);
hypre_TMemcpy(diag_tmp, l1_norm, HYPRE_Real, num_rows, memory_location_tmp, memory_location_l1);
/* Add the scaled l1 norm of the offd part */
if (num_cols_offd)
{
hypre_CSRMatrixComputeRowSum(A_offd, cf_marker_dev, cf_marker_offd, l1_norm, 1, 0.5, "add");
}
/* Truncate according to Remark 6.2 */
#if defined(HYPRE_USING_CUDA)
if (exec == HYPRE_EXEC_DEVICE)
{
HYPRE_THRUST_CALL( transform, l1_norm, l1_norm + num_rows, diag_tmp, l1_norm, l1_norm_op1() );
}
else
#endif
{
for (i = 0; i < num_rows; i++)
{
if (l1_norm[i] <= 4.0/3.0 * diag_tmp[i])
{
l1_norm[i] = diag_tmp[i];
}
}
}
}
else if (option == 5) /*stores diagonal of A for Jacobi using matvec, rlx 7 */
{
/* Set the diag element */
hypre_CSRMatrixExtractDiagonal(A_diag, l1_norm, 0);
#if defined(HYPRE_USING_CUDA)
if ( exec == HYPRE_EXEC_DEVICE)
{
thrust::identity<HYPRE_Complex> identity;
HYPRE_THRUST_CALL( replace_if, l1_norm, l1_norm + num_rows, thrust::not1(identity), 1.0 );
}
else
#endif
{
for (i = 0; i < num_rows; i++)
{
if (l1_norm[i] == 0.0)
{
l1_norm[i] = 1.0;
}
}
}
*l1_norm_ptr = l1_norm;
return hypre_error_flag;
}
/* Handle negative definite matrices */
if (!diag_tmp)
{
diag_tmp = hypre_TAlloc(HYPRE_Real, num_rows, memory_location_tmp);
}
/* Set the diag element */
hypre_CSRMatrixExtractDiagonal(A_diag, diag_tmp, 0);
#if defined(HYPRE_USING_CUDA)
if (exec == HYPRE_EXEC_DEVICE)
{
HYPRE_THRUST_CALL( transform_if, l1_norm, l1_norm + num_rows, diag_tmp, l1_norm, thrust::negate<HYPRE_Real>(),
is_negative<HYPRE_Real>() );
//bool any_zero = HYPRE_THRUST_CALL( any_of, l1_norm, l1_norm + num_rows, thrust::not1(thrust::identity<HYPRE_Complex>()) );
bool any_zero = 0.0 == HYPRE_THRUST_CALL( reduce, l1_norm, l1_norm + num_rows, 1.0, thrust::minimum<HYPRE_Real>() );
if ( any_zero )
{
hypre_error_in_arg(1);
}
}
else
#endif
{
for (i = 0; i < num_rows; i++)
{
if (diag_tmp[i] < 0.0)
{
l1_norm[i] = -l1_norm[i];
}
}
for (i = 0; i < num_rows; i++)
{
/* if (fabs(l1_norm[i]) < DBL_EPSILON) */
if (fabs(l1_norm[i]) == 0.0)
{
hypre_error_in_arg(1);
break;
}
}
}
if (exec == HYPRE_EXEC_DEVICE)
{
hypre_TFree(cf_marker_dev, HYPRE_MEMORY_DEVICE);
}
hypre_TFree(cf_marker_offd, memory_location_tmp);
hypre_TFree(diag_tmp, memory_location_tmp);
*l1_norm_ptr = l1_norm;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_ParCSRMatrixSetDiagRows
*
* For every row containing only a diagonal element: set it to d.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_ParCSRMatrixSetDiagRows(hypre_ParCSRMatrix *A, HYPRE_Real d)
{
HYPRE_Int i, j;
HYPRE_Int num_rows = hypre_ParCSRMatrixNumRows(A);
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Int *A_diag_I = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_J = hypre_CSRMatrixJ(A_diag);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *A_offd_I = hypre_CSRMatrixI(A_offd);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd);
for (i = 0; i < num_rows; i++)
{
j = A_diag_I[i];
if ((A_diag_I[i+1] == j+1) && (A_diag_J[j] == i) &&
(!num_cols_offd || (A_offd_I[i+1] == A_offd_I[i])))
{
A_diag_data[j] = d;
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSCreate
*
* Allocate the AMS solver structure.
*--------------------------------------------------------------------------*/
void * hypre_AMSCreate()
{
hypre_AMSData *ams_data;
ams_data = hypre_CTAlloc(hypre_AMSData, 1, HYPRE_MEMORY_HOST);
/* Default parameters */
ams_data -> dim = 3; /* 3D problem */
ams_data -> maxit = 20; /* perform at most 20 iterations */
ams_data -> tol = 1e-6; /* convergence tolerance */
ams_data -> print_level = 1; /* print residual norm at each step */
ams_data -> cycle_type = 1; /* a 3-level multiplicative solver */
ams_data -> A_relax_type = 2; /* offd-l1-scaled GS */
ams_data -> A_relax_times = 1; /* one relaxation sweep */
ams_data -> A_relax_weight = 1.0; /* damping parameter */
ams_data -> A_omega = 1.0; /* SSOR coefficient */
ams_data -> A_cheby_order = 2; /* Cheby: order (1 -4 are vaild) */
ams_data -> A_cheby_fraction = .3; /* Cheby: fraction of spectrum to smooth */
ams_data -> B_G_coarsen_type = 10; /* HMIS coarsening */
ams_data -> B_G_agg_levels = 1; /* Levels of aggressive coarsening */
ams_data -> B_G_relax_type = 3; /* hybrid G-S/Jacobi */
ams_data -> B_G_theta = 0.25; /* strength threshold */
ams_data -> B_G_interp_type = 0; /* interpolation type */
ams_data -> B_G_Pmax = 0; /* max nonzero elements in interp. rows */
ams_data -> B_Pi_coarsen_type = 10; /* HMIS coarsening */
ams_data -> B_Pi_agg_levels = 1; /* Levels of aggressive coarsening */
ams_data -> B_Pi_relax_type = 3; /* hybrid G-S/Jacobi */
ams_data -> B_Pi_theta = 0.25; /* strength threshold */
ams_data -> B_Pi_interp_type = 0; /* interpolation type */
ams_data -> B_Pi_Pmax = 0; /* max nonzero elements in interp. rows */
ams_data -> beta_is_zero = 0; /* the problem has a mass term */
/* By default, do l1-GS smoothing on the coarsest grid */
ams_data -> B_G_coarse_relax_type = 8;
ams_data -> B_Pi_coarse_relax_type = 8;
/* The rest of the fields are initialized using the Set functions */
ams_data -> A = NULL;
ams_data -> G = NULL;
ams_data -> A_G = NULL;
ams_data -> B_G = 0;
ams_data -> Pi = NULL;
ams_data -> A_Pi = NULL;
ams_data -> B_Pi = 0;
ams_data -> x = NULL;
ams_data -> y = NULL;
ams_data -> z = NULL;
ams_data -> Gx = NULL;
ams_data -> Gy = NULL;
ams_data -> Gz = NULL;
ams_data -> r0 = NULL;
ams_data -> g0 = NULL;
ams_data -> r1 = NULL;
ams_data -> g1 = NULL;
ams_data -> r2 = NULL;
ams_data -> g2 = NULL;
ams_data -> Pix = NULL;
ams_data -> Piy = NULL;
ams_data -> Piz = NULL;
ams_data -> A_Pix = NULL;
ams_data -> A_Piy = NULL;
ams_data -> A_Piz = NULL;
ams_data -> B_Pix = 0;
ams_data -> B_Piy = 0;
ams_data -> B_Piz = 0;
ams_data -> interior_nodes = NULL;
ams_data -> G0 = NULL;
ams_data -> A_G0 = NULL;
ams_data -> B_G0 = 0;
ams_data -> projection_frequency = 5;
ams_data -> A_l1_norms = NULL;
ams_data -> A_max_eig_est = 0;
ams_data -> A_min_eig_est = 0;
ams_data -> owns_Pi = 1;
ams_data -> owns_A_G = 0;
ams_data -> owns_A_Pi = 0;
return (void *) ams_data;
}
/*--------------------------------------------------------------------------
* hypre_AMSDestroy
*
* Deallocate the AMS solver structure. Note that the input data (given
* through the Set functions) is not destroyed.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSDestroy(void *solver)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
if (!ams_data)
{
hypre_error_in_arg(1);
return hypre_error_flag;
}
if (ams_data -> owns_A_G)
if (ams_data -> A_G)
hypre_ParCSRMatrixDestroy(ams_data -> A_G);
if (!ams_data -> beta_is_zero)
if (ams_data -> B_G)
HYPRE_BoomerAMGDestroy(ams_data -> B_G);
if (ams_data -> owns_Pi && ams_data -> Pi)
hypre_ParCSRMatrixDestroy(ams_data -> Pi);
if (ams_data -> owns_A_Pi)
if (ams_data -> A_Pi)
hypre_ParCSRMatrixDestroy(ams_data -> A_Pi);
if (ams_data -> B_Pi)
HYPRE_BoomerAMGDestroy(ams_data -> B_Pi);
if (ams_data -> owns_Pi && ams_data -> Pix)
hypre_ParCSRMatrixDestroy(ams_data -> Pix);
if (ams_data -> A_Pix)
hypre_ParCSRMatrixDestroy(ams_data -> A_Pix);
if (ams_data -> B_Pix)
HYPRE_BoomerAMGDestroy(ams_data -> B_Pix);
if (ams_data -> owns_Pi && ams_data -> Piy)
hypre_ParCSRMatrixDestroy(ams_data -> Piy);
if (ams_data -> A_Piy)
hypre_ParCSRMatrixDestroy(ams_data -> A_Piy);
if (ams_data -> B_Piy)
HYPRE_BoomerAMGDestroy(ams_data -> B_Piy);
if (ams_data -> owns_Pi && ams_data -> Piz)
hypre_ParCSRMatrixDestroy(ams_data -> Piz);
if (ams_data -> A_Piz)
hypre_ParCSRMatrixDestroy(ams_data -> A_Piz);
if (ams_data -> B_Piz)
HYPRE_BoomerAMGDestroy(ams_data -> B_Piz);
if (ams_data -> r0)
hypre_ParVectorDestroy(ams_data -> r0);
if (ams_data -> g0)
hypre_ParVectorDestroy(ams_data -> g0);
if (ams_data -> r1)
hypre_ParVectorDestroy(ams_data -> r1);
if (ams_data -> g1)
hypre_ParVectorDestroy(ams_data -> g1);
if (ams_data -> r2)
hypre_ParVectorDestroy(ams_data -> r2);
if (ams_data -> g2)
hypre_ParVectorDestroy(ams_data -> g2);
if (ams_data -> G0)
hypre_ParCSRMatrixDestroy(ams_data -> A);
if (ams_data -> G0)
hypre_ParCSRMatrixDestroy(ams_data -> G0);
if (ams_data -> A_G0)
hypre_ParCSRMatrixDestroy(ams_data -> A_G0);
if (ams_data -> B_G0)
HYPRE_BoomerAMGDestroy(ams_data -> B_G0);
hypre_SeqVectorDestroy(ams_data -> A_l1_norms);
/* G, x, y ,z, Gx, Gy and Gz are not destroyed */
if (ams_data)
{
hypre_TFree(ams_data, HYPRE_MEMORY_HOST);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetDimension
*
* Set problem dimension (2 or 3). By default we assume dim = 3.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetDimension(void *solver,
HYPRE_Int dim)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
if (dim != 2 && dim != 3)
hypre_error_in_arg(2);
ams_data -> dim = dim;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetDiscreteGradient
*
* Set the discrete gradient matrix G.
* This function should be called before hypre_AMSSetup()!
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetDiscreteGradient(void *solver,
hypre_ParCSRMatrix *G)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> G = G;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetCoordinateVectors
*
* Set the x, y and z coordinates of the vertices in the mesh.
*
* Either SetCoordinateVectors or SetEdgeConstantVectors should be
* called before hypre_AMSSetup()!
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetCoordinateVectors(void *solver,
hypre_ParVector *x,
hypre_ParVector *y,
hypre_ParVector *z)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> x = x;
ams_data -> y = y;
ams_data -> z = z;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetEdgeConstantVectors
*
* Set the vectors Gx, Gy and Gz which give the representations of
* the constant vector fields (1,0,0), (0,1,0) and (0,0,1) in the
* edge element basis.
*
* Either SetCoordinateVectors or SetEdgeConstantVectors should be
* called before hypre_AMSSetup()!
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetEdgeConstantVectors(void *solver,
hypre_ParVector *Gx,
hypre_ParVector *Gy,
hypre_ParVector *Gz)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> Gx = Gx;
ams_data -> Gy = Gy;
ams_data -> Gz = Gz;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetInterpolations
*
* Set the (components of) the Nedelec interpolation matrix Pi=[Pix,Piy,Piz].
*
* This function is generally intended to be used only for high-order Nedelec
* discretizations (in the lowest order case, Pi is constructed internally in
* AMS from the discreet gradient matrix and the coordinates of the vertices),
* though it can also be used in the lowest-order case or for other types of
* discretizations (e.g. ones based on the second family of Nedelec elements).
*
* By definition, Pi is the matrix representation of the linear operator that
* interpolates (high-order) vector nodal finite elements into the (high-order)
* Nedelec space. The component matrices are defined as Pix phi = Pi (phi,0,0)
* and similarly for Piy and Piz. Note that all these operators depend on the
* choice of the basis and degrees of freedom in the high-order spaces.
*
* The column numbering of Pi should be node-based, i.e. the x/y/z components of
* the first node (vertex or high-order dof) should be listed first, followed by
* the x/y/z components of the second node and so on (see the documentation of
* HYPRE_BoomerAMGSetDofFunc).
*
* If used, this function should be called before hypre_AMSSetup() and there is
* no need to provide the vertex coordinates. Furthermore, only one of the sets
* {Pi} and {Pix,Piy,Piz} needs to be specified (though it is OK to provide
* both). If Pix is NULL, then scalar Pi-based AMS cycles, i.e. those with
* cycle_type > 10, will be unavailable. Similarly, AMS cycles based on
* monolithic Pi (cycle_type < 10) require that Pi is not NULL.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetInterpolations(void *solver,
hypre_ParCSRMatrix *Pi,
hypre_ParCSRMatrix *Pix,
hypre_ParCSRMatrix *Piy,
hypre_ParCSRMatrix *Piz)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> Pi = Pi;
ams_data -> Pix = Pix;
ams_data -> Piy = Piy;
ams_data -> Piz = Piz;
ams_data -> owns_Pi = 0;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetAlphaPoissonMatrix
*
* Set the matrix corresponding to the Poisson problem with coefficient
* alpha (the curl-curl term coefficient in the Maxwell problem).
*
* If this function is called, the coarse space solver on the range
* of Pi^T is a block-diagonal version of A_Pi. If this function is not
* called, the coarse space solver on the range of Pi^T is constructed
* as Pi^T A Pi in hypre_AMSSetup().
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetAlphaPoissonMatrix(void *solver,
hypre_ParCSRMatrix *A_Pi)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> A_Pi = A_Pi;
/* Penalize the eliminated degrees of freedom */
hypre_ParCSRMatrixSetDiagRows(A_Pi, HYPRE_REAL_MAX);
/* Make sure that the first entry in each row is the diagonal one. */
/* hypre_CSRMatrixReorder(hypre_ParCSRMatrixDiag(A_Pi)); */
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetBetaPoissonMatrix
*
* Set the matrix corresponding to the Poisson problem with coefficient
* beta (the mass term coefficient in the Maxwell problem).
*
* This function call is optional - if not given, the Poisson matrix will
* be computed in hypre_AMSSetup(). If the given matrix is NULL, we assume
* that beta is 0 and use two-level (instead of three-level) methods.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetBetaPoissonMatrix(void *solver,
hypre_ParCSRMatrix *A_G)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> A_G = A_G;
if (!A_G)
ams_data -> beta_is_zero = 1;
else
{
/* Penalize the eliminated degrees of freedom */
hypre_ParCSRMatrixSetDiagRows(A_G, HYPRE_REAL_MAX);
/* Make sure that the first entry in each row is the diagonal one. */
/* hypre_CSRMatrixReorder(hypre_ParCSRMatrixDiag(A_G)); */
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetInteriorNodes
*
* Set the list of nodes which are interior to the zero-conductivity region.
* A node is interior if interior_nodes[i] == 1.0.
*
* Should be called before hypre_AMSSetup()!
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetInteriorNodes(void *solver,
hypre_ParVector *interior_nodes)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> interior_nodes = interior_nodes;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetProjectionFrequency
*
* How often to project the r.h.s. onto the compatible sub-space Ker(G0^T),
* when iterating with the solver.
*
* The default value is every 5th iteration.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetProjectionFrequency(void *solver,
HYPRE_Int projection_frequency)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> projection_frequency = projection_frequency;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetMaxIter
*
* Set the maximum number of iterations in the three-level method.
* The default value is 20. To use the AMS solver as a preconditioner,
* set maxit to 1, tol to 0.0 and print_level to 0.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetMaxIter(void *solver,
HYPRE_Int maxit)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> maxit = maxit;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetTol
*
* Set the convergence tolerance (if the method is used as a solver).
* The default value is 1e-6.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetTol(void *solver,
HYPRE_Real tol)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> tol = tol;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetCycleType
*
* Choose which three-level solver to use. Possible values are:
*
* 1 = 3-level multipl. solver (01210) <-- small solution time
* 2 = 3-level additive solver (0+1+2)
* 3 = 3-level multipl. solver (02120)
* 4 = 3-level additive solver (010+2)
* 5 = 3-level multipl. solver (0102010) <-- small solution time
* 6 = 3-level additive solver (1+020)
* 7 = 3-level multipl. solver (0201020) <-- small number of iterations
* 8 = 3-level additive solver (0(1+2)0) <-- small solution time
* 9 = 3-level multipl. solver (01210) with discrete divergence
* 11 = 5-level multipl. solver (013454310) <-- small solution time, memory
* 12 = 5-level additive solver (0+1+3+4+5)
* 13 = 5-level multipl. solver (034515430) <-- small solution time, memory
* 14 = 5-level additive solver (01(3+4+5)10)
* 20 = 2-level multipl. solver (0[12]0)
*
* 0 = a Hiptmair-like smoother (010)
*
* The default value is 1.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetCycleType(void *solver,
HYPRE_Int cycle_type)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> cycle_type = cycle_type;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetPrintLevel
*
* Control how much information is printed during the solution iterations.
* The defaut values is 1 (print residual norm at each step).
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetPrintLevel(void *solver,
HYPRE_Int print_level)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> print_level = print_level;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetSmoothingOptions
*
* Set relaxation parameters for A. Default values: 2, 1, 1.0, 1.0.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetSmoothingOptions(void *solver,
HYPRE_Int A_relax_type,
HYPRE_Int A_relax_times,
HYPRE_Real A_relax_weight,
HYPRE_Real A_omega)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> A_relax_type = A_relax_type;
ams_data -> A_relax_times = A_relax_times;
ams_data -> A_relax_weight = A_relax_weight;
ams_data -> A_omega = A_omega;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetChebySmoothingOptions
* AB: note: this could be added to the above,
* but I didn't want to change parameter list)
* Set parameters for chebyshev smoother for A. Default values: 2,.3.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetChebySmoothingOptions(void *solver,
HYPRE_Int A_cheby_order,
HYPRE_Int A_cheby_fraction)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> A_cheby_order = A_cheby_order;
ams_data -> A_cheby_fraction = A_cheby_fraction;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetAlphaAMGOptions
*
* Set AMG parameters for B_Pi. Default values: 10, 1, 3, 0.25, 0, 0.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetAlphaAMGOptions(void *solver,
HYPRE_Int B_Pi_coarsen_type,
HYPRE_Int B_Pi_agg_levels,
HYPRE_Int B_Pi_relax_type,
HYPRE_Real B_Pi_theta,
HYPRE_Int B_Pi_interp_type,
HYPRE_Int B_Pi_Pmax)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> B_Pi_coarsen_type = B_Pi_coarsen_type;
ams_data -> B_Pi_agg_levels = B_Pi_agg_levels;
ams_data -> B_Pi_relax_type = B_Pi_relax_type;
ams_data -> B_Pi_theta = B_Pi_theta;
ams_data -> B_Pi_interp_type = B_Pi_interp_type;
ams_data -> B_Pi_Pmax = B_Pi_Pmax;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetAlphaAMGCoarseRelaxType
*
* Set the AMG coarsest level relaxation for B_Pi. Default value: 8.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetAlphaAMGCoarseRelaxType(void *solver,
HYPRE_Int B_Pi_coarse_relax_type)
{
hypre_AMSData *ams_data = (hypre_AMSData *)solver;
ams_data -> B_Pi_coarse_relax_type = B_Pi_coarse_relax_type;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetBetaAMGOptions
*
* Set AMG parameters for B_G. Default values: 10, 1, 3, 0.25, 0, 0.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetBetaAMGOptions(void *solver,
HYPRE_Int B_G_coarsen_type,
HYPRE_Int B_G_agg_levels,
HYPRE_Int B_G_relax_type,
HYPRE_Real B_G_theta,
HYPRE_Int B_G_interp_type,
HYPRE_Int B_G_Pmax)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> B_G_coarsen_type = B_G_coarsen_type;
ams_data -> B_G_agg_levels = B_G_agg_levels;
ams_data -> B_G_relax_type = B_G_relax_type;
ams_data -> B_G_theta = B_G_theta;
ams_data -> B_G_interp_type = B_G_interp_type;
ams_data -> B_G_Pmax = B_G_Pmax;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetBetaAMGCoarseRelaxType
*
* Set the AMG coarsest level relaxation for B_G. Default value: 8.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetBetaAMGCoarseRelaxType(void *solver,
HYPRE_Int B_G_coarse_relax_type)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
ams_data -> B_G_coarse_relax_type = B_G_coarse_relax_type;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSComputePi
*
* Construct the Pi interpolation matrix, which maps the space of vector
* linear finite elements to the space of edge finite elements.
*
* The construction is based on the fact that Pi = [Pi_x, Pi_y, Pi_z],
* where each block has the same sparsity structure as G, and the entries
* can be computed from the vectors Gx, Gy, Gz.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSComputePi(hypre_ParCSRMatrix *A,
hypre_ParCSRMatrix *G,
hypre_ParVector *Gx,
hypre_ParVector *Gy,
hypre_ParVector *Gz,
HYPRE_Int dim,
hypre_ParCSRMatrix **Pi_ptr)
{
hypre_ParCSRMatrix *Pi;
/* Compute Pi = [Pi_x, Pi_y, Pi_z] */
{
HYPRE_Int i, j, d;
HYPRE_Real *Gx_data, *Gy_data, *Gz_data;
MPI_Comm comm = hypre_ParCSRMatrixComm(G);
HYPRE_BigInt global_num_rows = hypre_ParCSRMatrixGlobalNumRows(G);
HYPRE_BigInt global_num_cols = dim*hypre_ParCSRMatrixGlobalNumCols(G);
HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(G);
HYPRE_BigInt *col_starts;
HYPRE_Int col_starts_size;
HYPRE_Int num_cols_offd = dim*hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(G));
HYPRE_Int num_nonzeros_diag = dim*hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixDiag(G));
HYPRE_Int num_nonzeros_offd = dim*hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixOffd(G));
HYPRE_BigInt *col_starts_G = hypre_ParCSRMatrixColStarts(G);
#ifdef HYPRE_NO_GLOBAL_PARTITION
col_starts_size = 2;
#else
HYPRE_Int num_procs;
hypre_MPI_Comm_size(comm, &num_procs);
col_starts_size = num_procs+1;
#endif
col_starts = hypre_TAlloc(HYPRE_BigInt, col_starts_size, HYPRE_MEMORY_HOST);
for (i = 0; i < col_starts_size; i++)
col_starts[i] = (HYPRE_BigInt)dim * col_starts_G[i];
Pi = hypre_ParCSRMatrixCreate(comm,
global_num_rows,
global_num_cols,
row_starts,
col_starts,
num_cols_offd,
num_nonzeros_diag,
num_nonzeros_offd);
hypre_ParCSRMatrixOwnsData(Pi) = 1;
hypre_ParCSRMatrixOwnsRowStarts(Pi) = 0;
hypre_ParCSRMatrixOwnsColStarts(Pi) = 1;
hypre_ParCSRMatrixInitialize(Pi);
Gx_data = hypre_VectorData(hypre_ParVectorLocalVector(Gx));
Gy_data = hypre_VectorData(hypre_ParVectorLocalVector(Gy));
if (dim == 3)
Gz_data = hypre_VectorData(hypre_ParVectorLocalVector(Gz));
/* Fill-in the diagonal part */
{
hypre_CSRMatrix *G_diag = hypre_ParCSRMatrixDiag(G);
HYPRE_Int *G_diag_I = hypre_CSRMatrixI(G_diag);
HYPRE_Int *G_diag_J = hypre_CSRMatrixJ(G_diag);
HYPRE_Real *G_diag_data = hypre_CSRMatrixData(G_diag);
HYPRE_Int G_diag_nrows = hypre_CSRMatrixNumRows(G_diag);
HYPRE_Int G_diag_nnz = hypre_CSRMatrixNumNonzeros(G_diag);
hypre_CSRMatrix *Pi_diag = hypre_ParCSRMatrixDiag(Pi);
HYPRE_Int *Pi_diag_I = hypre_CSRMatrixI(Pi_diag);
HYPRE_Int *Pi_diag_J = hypre_CSRMatrixJ(Pi_diag);
HYPRE_Real *Pi_diag_data = hypre_CSRMatrixData(Pi_diag);
for (i = 0; i < G_diag_nrows+1; i++)
Pi_diag_I[i] = dim * G_diag_I[i];
for (i = 0; i < G_diag_nnz; i++)
for (d = 0; d < dim; d++)
Pi_diag_J[dim*i+d] = dim*G_diag_J[i]+d;
for (i = 0; i < G_diag_nrows; i++)
for (j = G_diag_I[i]; j < G_diag_I[i+1]; j++)
{
*Pi_diag_data++ = fabs(G_diag_data[j]) * 0.5 * Gx_data[i];
*Pi_diag_data++ = fabs(G_diag_data[j]) * 0.5 * Gy_data[i];
if (dim == 3)
*Pi_diag_data++ = fabs(G_diag_data[j]) * 0.5 * Gz_data[i];
}
}
/* Fill-in the off-diagonal part */
{
hypre_CSRMatrix *G_offd = hypre_ParCSRMatrixOffd(G);
HYPRE_Int *G_offd_I = hypre_CSRMatrixI(G_offd);
HYPRE_Int *G_offd_J = hypre_CSRMatrixJ(G_offd);
HYPRE_Real *G_offd_data = hypre_CSRMatrixData(G_offd);
HYPRE_Int G_offd_nrows = hypre_CSRMatrixNumRows(G_offd);
HYPRE_Int G_offd_ncols = hypre_CSRMatrixNumCols(G_offd);
HYPRE_Int G_offd_nnz = hypre_CSRMatrixNumNonzeros(G_offd);
hypre_CSRMatrix *Pi_offd = hypre_ParCSRMatrixOffd(Pi);
HYPRE_Int *Pi_offd_I = hypre_CSRMatrixI(Pi_offd);
HYPRE_Int *Pi_offd_J = hypre_CSRMatrixJ(Pi_offd);
HYPRE_Real *Pi_offd_data = hypre_CSRMatrixData(Pi_offd);
HYPRE_BigInt *G_cmap = hypre_ParCSRMatrixColMapOffd(G);
HYPRE_BigInt *Pi_cmap = hypre_ParCSRMatrixColMapOffd(Pi);
if (G_offd_ncols)
for (i = 0; i < G_offd_nrows+1; i++)
Pi_offd_I[i] = dim * G_offd_I[i];
for (i = 0; i < G_offd_nnz; i++)
for (d = 0; d < dim; d++)
Pi_offd_J[dim*i+d] = dim*G_offd_J[i]+d;
for (i = 0; i < G_offd_nrows; i++)
for (j = G_offd_I[i]; j < G_offd_I[i+1]; j++)
{
*Pi_offd_data++ = fabs(G_offd_data[j]) * 0.5 * Gx_data[i];
*Pi_offd_data++ = fabs(G_offd_data[j]) * 0.5 * Gy_data[i];
if (dim == 3)
*Pi_offd_data++ = fabs(G_offd_data[j]) * 0.5 * Gz_data[i];
}
for (i = 0; i < G_offd_ncols; i++)
for (d = 0; d < dim; d++)
Pi_cmap[dim*i+d] = (HYPRE_BigInt)dim*G_cmap[i]+(HYPRE_BigInt)d;
}
}
*Pi_ptr = Pi;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSComputePixyz
*
* Construct the components Pix, Piy, Piz of the interpolation matrix Pi,
* which maps the space of vector linear finite elements to the space of
* edge finite elements.
*
* The construction is based on the fact that each component has the same
* sparsity structure as G, and the entries can be computed from the vectors
* Gx, Gy, Gz.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSComputePixyz(hypre_ParCSRMatrix *A,
hypre_ParCSRMatrix *G,
hypre_ParVector *Gx,
hypre_ParVector *Gy,
hypre_ParVector *Gz,
HYPRE_Int dim,
hypre_ParCSRMatrix **Pix_ptr,
hypre_ParCSRMatrix **Piy_ptr,
hypre_ParCSRMatrix **Piz_ptr)
{
hypre_ParCSRMatrix *Pix, *Piy, *Piz;
/* Compute Pix, Piy, Piz */
{
HYPRE_Int i, j;
HYPRE_Real *Gx_data, *Gy_data, *Gz_data;
MPI_Comm comm = hypre_ParCSRMatrixComm(G);
HYPRE_BigInt global_num_rows = hypre_ParCSRMatrixGlobalNumRows(G);
HYPRE_BigInt global_num_cols = hypre_ParCSRMatrixGlobalNumCols(G);
HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(G);
HYPRE_BigInt *col_starts = hypre_ParCSRMatrixColStarts(G);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(G));
HYPRE_Int num_nonzeros_diag = hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixDiag(G));
HYPRE_Int num_nonzeros_offd = hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixOffd(G));
Pix = hypre_ParCSRMatrixCreate(comm,
global_num_rows,
global_num_cols,
row_starts,
col_starts,
num_cols_offd,
num_nonzeros_diag,
num_nonzeros_offd);
hypre_ParCSRMatrixOwnsData(Pix) = 1;
hypre_ParCSRMatrixOwnsRowStarts(Pix) = 0;
hypre_ParCSRMatrixOwnsColStarts(Pix) = 0;
hypre_ParCSRMatrixInitialize(Pix);
Piy = hypre_ParCSRMatrixCreate(comm,
global_num_rows,
global_num_cols,
row_starts,
col_starts,
num_cols_offd,
num_nonzeros_diag,
num_nonzeros_offd);
hypre_ParCSRMatrixOwnsData(Piy) = 1;
hypre_ParCSRMatrixOwnsRowStarts(Piy) = 0;
hypre_ParCSRMatrixOwnsColStarts(Piy) = 0;
hypre_ParCSRMatrixInitialize(Piy);
if (dim == 3)
{
Piz = hypre_ParCSRMatrixCreate(comm,
global_num_rows,
global_num_cols,
row_starts,
col_starts,
num_cols_offd,
num_nonzeros_diag,
num_nonzeros_offd);
hypre_ParCSRMatrixOwnsData(Piz) = 1;
hypre_ParCSRMatrixOwnsRowStarts(Piz) = 0;
hypre_ParCSRMatrixOwnsColStarts(Piz) = 0;
hypre_ParCSRMatrixInitialize(Piz);
}
Gx_data = hypre_VectorData(hypre_ParVectorLocalVector(Gx));
Gy_data = hypre_VectorData(hypre_ParVectorLocalVector(Gy));
if (dim == 3)
Gz_data = hypre_VectorData(hypre_ParVectorLocalVector(Gz));
/* Fill-in the diagonal part */
if (dim == 3)
{
hypre_CSRMatrix *G_diag = hypre_ParCSRMatrixDiag(G);
HYPRE_Int *G_diag_I = hypre_CSRMatrixI(G_diag);
HYPRE_Int *G_diag_J = hypre_CSRMatrixJ(G_diag);
HYPRE_Real *G_diag_data = hypre_CSRMatrixData(G_diag);
HYPRE_Int G_diag_nrows = hypre_CSRMatrixNumRows(G_diag);
HYPRE_Int G_diag_nnz = hypre_CSRMatrixNumNonzeros(G_diag);
hypre_CSRMatrix *Pix_diag = hypre_ParCSRMatrixDiag(Pix);
HYPRE_Int *Pix_diag_I = hypre_CSRMatrixI(Pix_diag);
HYPRE_Int *Pix_diag_J = hypre_CSRMatrixJ(Pix_diag);
HYPRE_Real *Pix_diag_data = hypre_CSRMatrixData(Pix_diag);
hypre_CSRMatrix *Piy_diag = hypre_ParCSRMatrixDiag(Piy);
HYPRE_Int *Piy_diag_I = hypre_CSRMatrixI(Piy_diag);
HYPRE_Int *Piy_diag_J = hypre_CSRMatrixJ(Piy_diag);
HYPRE_Real *Piy_diag_data = hypre_CSRMatrixData(Piy_diag);
hypre_CSRMatrix *Piz_diag = hypre_ParCSRMatrixDiag(Piz);
HYPRE_Int *Piz_diag_I = hypre_CSRMatrixI(Piz_diag);
HYPRE_Int *Piz_diag_J = hypre_CSRMatrixJ(Piz_diag);
HYPRE_Real *Piz_diag_data = hypre_CSRMatrixData(Piz_diag);
for (i = 0; i < G_diag_nrows+1; i++)
{
Pix_diag_I[i] = G_diag_I[i];
Piy_diag_I[i] = G_diag_I[i];
Piz_diag_I[i] = G_diag_I[i];
}
for (i = 0; i < G_diag_nnz; i++)
{
Pix_diag_J[i] = G_diag_J[i];
Piy_diag_J[i] = G_diag_J[i];
Piz_diag_J[i] = G_diag_J[i];
}
for (i = 0; i < G_diag_nrows; i++)
for (j = G_diag_I[i]; j < G_diag_I[i+1]; j++)
{
*Pix_diag_data++ = fabs(G_diag_data[j]) * 0.5 * Gx_data[i];
*Piy_diag_data++ = fabs(G_diag_data[j]) * 0.5 * Gy_data[i];
*Piz_diag_data++ = fabs(G_diag_data[j]) * 0.5 * Gz_data[i];
}
}
else
{
hypre_CSRMatrix *G_diag = hypre_ParCSRMatrixDiag(G);
HYPRE_Int *G_diag_I = hypre_CSRMatrixI(G_diag);
HYPRE_Int *G_diag_J = hypre_CSRMatrixJ(G_diag);
HYPRE_Real *G_diag_data = hypre_CSRMatrixData(G_diag);
HYPRE_Int G_diag_nrows = hypre_CSRMatrixNumRows(G_diag);
HYPRE_Int G_diag_nnz = hypre_CSRMatrixNumNonzeros(G_diag);
hypre_CSRMatrix *Pix_diag = hypre_ParCSRMatrixDiag(Pix);
HYPRE_Int *Pix_diag_I = hypre_CSRMatrixI(Pix_diag);
HYPRE_Int *Pix_diag_J = hypre_CSRMatrixJ(Pix_diag);
HYPRE_Real *Pix_diag_data = hypre_CSRMatrixData(Pix_diag);
hypre_CSRMatrix *Piy_diag = hypre_ParCSRMatrixDiag(Piy);
HYPRE_Int *Piy_diag_I = hypre_CSRMatrixI(Piy_diag);
HYPRE_Int *Piy_diag_J = hypre_CSRMatrixJ(Piy_diag);
HYPRE_Real *Piy_diag_data = hypre_CSRMatrixData(Piy_diag);
for (i = 0; i < G_diag_nrows+1; i++)
{
Pix_diag_I[i] = G_diag_I[i];
Piy_diag_I[i] = G_diag_I[i];
}
for (i = 0; i < G_diag_nnz; i++)
{
Pix_diag_J[i] = G_diag_J[i];
Piy_diag_J[i] = G_diag_J[i];
}
for (i = 0; i < G_diag_nrows; i++)
for (j = G_diag_I[i]; j < G_diag_I[i+1]; j++)
{
*Pix_diag_data++ = fabs(G_diag_data[j]) * 0.5 * Gx_data[i];
*Piy_diag_data++ = fabs(G_diag_data[j]) * 0.5 * Gy_data[i];
}
}
/* Fill-in the off-diagonal part */
if (dim == 3)
{
hypre_CSRMatrix *G_offd = hypre_ParCSRMatrixOffd(G);
HYPRE_Int *G_offd_I = hypre_CSRMatrixI(G_offd);
HYPRE_Int *G_offd_J = hypre_CSRMatrixJ(G_offd);
HYPRE_Real *G_offd_data = hypre_CSRMatrixData(G_offd);
HYPRE_Int G_offd_nrows = hypre_CSRMatrixNumRows(G_offd);
HYPRE_Int G_offd_ncols = hypre_CSRMatrixNumCols(G_offd);
HYPRE_Int G_offd_nnz = hypre_CSRMatrixNumNonzeros(G_offd);
hypre_CSRMatrix *Pix_offd = hypre_ParCSRMatrixOffd(Pix);
HYPRE_Int *Pix_offd_I = hypre_CSRMatrixI(Pix_offd);
HYPRE_Int *Pix_offd_J = hypre_CSRMatrixJ(Pix_offd);
HYPRE_Real *Pix_offd_data = hypre_CSRMatrixData(Pix_offd);
hypre_CSRMatrix *Piy_offd = hypre_ParCSRMatrixOffd(Piy);
HYPRE_Int *Piy_offd_I = hypre_CSRMatrixI(Piy_offd);
HYPRE_Int *Piy_offd_J = hypre_CSRMatrixJ(Piy_offd);
HYPRE_Real *Piy_offd_data = hypre_CSRMatrixData(Piy_offd);
hypre_CSRMatrix *Piz_offd = hypre_ParCSRMatrixOffd(Piz);
HYPRE_Int *Piz_offd_I = hypre_CSRMatrixI(Piz_offd);
HYPRE_Int *Piz_offd_J = hypre_CSRMatrixJ(Piz_offd);
HYPRE_Real *Piz_offd_data = hypre_CSRMatrixData(Piz_offd);
HYPRE_BigInt *G_cmap = hypre_ParCSRMatrixColMapOffd(G);
HYPRE_BigInt *Pix_cmap = hypre_ParCSRMatrixColMapOffd(Pix);
HYPRE_BigInt *Piy_cmap = hypre_ParCSRMatrixColMapOffd(Piy);
HYPRE_BigInt *Piz_cmap = hypre_ParCSRMatrixColMapOffd(Piz);
if (G_offd_ncols)
for (i = 0; i < G_offd_nrows+1; i++)
{
Pix_offd_I[i] = G_offd_I[i];
Piy_offd_I[i] = G_offd_I[i];
Piz_offd_I[i] = G_offd_I[i];
}
for (i = 0; i < G_offd_nnz; i++)
{
Pix_offd_J[i] = G_offd_J[i];
Piy_offd_J[i] = G_offd_J[i];
Piz_offd_J[i] = G_offd_J[i];
}
for (i = 0; i < G_offd_nrows; i++)
for (j = G_offd_I[i]; j < G_offd_I[i+1]; j++)
{
*Pix_offd_data++ = fabs(G_offd_data[j]) * 0.5 * Gx_data[i];
*Piy_offd_data++ = fabs(G_offd_data[j]) * 0.5 * Gy_data[i];
*Piz_offd_data++ = fabs(G_offd_data[j]) * 0.5 * Gz_data[i];
}
for (i = 0; i < G_offd_ncols; i++)
{
Pix_cmap[i] = G_cmap[i];
Piy_cmap[i] = G_cmap[i];
Piz_cmap[i] = G_cmap[i];
}
}
else
{
hypre_CSRMatrix *G_offd = hypre_ParCSRMatrixOffd(G);
HYPRE_Int *G_offd_I = hypre_CSRMatrixI(G_offd);
HYPRE_Int *G_offd_J = hypre_CSRMatrixJ(G_offd);
HYPRE_Real *G_offd_data = hypre_CSRMatrixData(G_offd);
HYPRE_Int G_offd_nrows = hypre_CSRMatrixNumRows(G_offd);
HYPRE_Int G_offd_ncols = hypre_CSRMatrixNumCols(G_offd);
HYPRE_Int G_offd_nnz = hypre_CSRMatrixNumNonzeros(G_offd);
hypre_CSRMatrix *Pix_offd = hypre_ParCSRMatrixOffd(Pix);
HYPRE_Int *Pix_offd_I = hypre_CSRMatrixI(Pix_offd);
HYPRE_Int *Pix_offd_J = hypre_CSRMatrixJ(Pix_offd);
HYPRE_Real *Pix_offd_data = hypre_CSRMatrixData(Pix_offd);
hypre_CSRMatrix *Piy_offd = hypre_ParCSRMatrixOffd(Piy);
HYPRE_Int *Piy_offd_I = hypre_CSRMatrixI(Piy_offd);
HYPRE_Int *Piy_offd_J = hypre_CSRMatrixJ(Piy_offd);
HYPRE_Real *Piy_offd_data = hypre_CSRMatrixData(Piy_offd);
HYPRE_BigInt *G_cmap = hypre_ParCSRMatrixColMapOffd(G);
HYPRE_BigInt *Pix_cmap = hypre_ParCSRMatrixColMapOffd(Pix);
HYPRE_BigInt *Piy_cmap = hypre_ParCSRMatrixColMapOffd(Piy);
if (G_offd_ncols)
for (i = 0; i < G_offd_nrows+1; i++)
{
Pix_offd_I[i] = G_offd_I[i];
Piy_offd_I[i] = G_offd_I[i];
}
for (i = 0; i < G_offd_nnz; i++)
{
Pix_offd_J[i] = G_offd_J[i];
Piy_offd_J[i] = G_offd_J[i];
}
for (i = 0; i < G_offd_nrows; i++)
for (j = G_offd_I[i]; j < G_offd_I[i+1]; j++)
{
*Pix_offd_data++ = fabs(G_offd_data[j]) * 0.5 * Gx_data[i];
*Piy_offd_data++ = fabs(G_offd_data[j]) * 0.5 * Gy_data[i];
}
for (i = 0; i < G_offd_ncols; i++)
{
Pix_cmap[i] = G_cmap[i];
Piy_cmap[i] = G_cmap[i];
}
}
}
*Pix_ptr = Pix;
*Piy_ptr = Piy;
if (dim == 3)
*Piz_ptr = Piz;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSComputeGPi
*
* Construct the matrix [G,Pi] which can be considered an interpolation
* matrix from S_h^4 (4 copies of the scalar linear finite element space)
* to the edge finite elements space.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSComputeGPi(hypre_ParCSRMatrix *A,
hypre_ParCSRMatrix *G,
hypre_ParVector *Gx,
hypre_ParVector *Gy,
hypre_ParVector *Gz,
HYPRE_Int dim,
hypre_ParCSRMatrix **GPi_ptr)
{
hypre_ParCSRMatrix *GPi;
/* Take into account G */
dim++;
/* Compute GPi = [Pi_x, Pi_y, Pi_z, G] */
{
HYPRE_Int i, j, d;
HYPRE_Real *Gx_data, *Gy_data, *Gz_data;
MPI_Comm comm = hypre_ParCSRMatrixComm(G);
HYPRE_BigInt global_num_rows = hypre_ParCSRMatrixGlobalNumRows(G);
HYPRE_BigInt global_num_cols = dim*hypre_ParCSRMatrixGlobalNumCols(G);
HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(G);
HYPRE_BigInt *col_starts;
HYPRE_Int col_starts_size;
HYPRE_Int num_cols_offd = dim*hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(G));
HYPRE_Int num_nonzeros_diag = dim*hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixDiag(G));
HYPRE_Int num_nonzeros_offd = dim*hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixOffd(G));
HYPRE_BigInt *col_starts_G = hypre_ParCSRMatrixColStarts(G);
#ifdef HYPRE_NO_GLOBAL_PARTITION
col_starts_size = 2;
#else
HYPRE_Int num_procs;
hypre_MPI_Comm_size(comm, &num_procs);
col_starts_size = num_procs+1;
#endif
col_starts = hypre_TAlloc(HYPRE_BigInt, col_starts_size, HYPRE_MEMORY_HOST);
for (i = 0; i < col_starts_size; i++)
col_starts[i] = (HYPRE_BigInt) dim * col_starts_G[i];
GPi = hypre_ParCSRMatrixCreate(comm,
global_num_rows,
global_num_cols,
row_starts,
col_starts,
num_cols_offd,
num_nonzeros_diag,
num_nonzeros_offd);
hypre_ParCSRMatrixOwnsData(GPi) = 1;
hypre_ParCSRMatrixOwnsRowStarts(GPi) = 0;
hypre_ParCSRMatrixOwnsColStarts(GPi) = 1;
hypre_ParCSRMatrixInitialize(GPi);
Gx_data = hypre_VectorData(hypre_ParVectorLocalVector(Gx));
Gy_data = hypre_VectorData(hypre_ParVectorLocalVector(Gy));
if (dim == 4)
Gz_data = hypre_VectorData(hypre_ParVectorLocalVector(Gz));
/* Fill-in the diagonal part */
{
hypre_CSRMatrix *G_diag = hypre_ParCSRMatrixDiag(G);
HYPRE_Int *G_diag_I = hypre_CSRMatrixI(G_diag);
HYPRE_Int *G_diag_J = hypre_CSRMatrixJ(G_diag);
HYPRE_Real *G_diag_data = hypre_CSRMatrixData(G_diag);
HYPRE_Int G_diag_nrows = hypre_CSRMatrixNumRows(G_diag);
HYPRE_Int G_diag_nnz = hypre_CSRMatrixNumNonzeros(G_diag);
hypre_CSRMatrix *GPi_diag = hypre_ParCSRMatrixDiag(GPi);
HYPRE_Int *GPi_diag_I = hypre_CSRMatrixI(GPi_diag);
HYPRE_Int *GPi_diag_J = hypre_CSRMatrixJ(GPi_diag);
HYPRE_Real *GPi_diag_data = hypre_CSRMatrixData(GPi_diag);
for (i = 0; i < G_diag_nrows+1; i++)
GPi_diag_I[i] = dim * G_diag_I[i];
for (i = 0; i < G_diag_nnz; i++)
for (d = 0; d < dim; d++)
GPi_diag_J[dim*i+d] = dim*G_diag_J[i]+d;
for (i = 0; i < G_diag_nrows; i++)
for (j = G_diag_I[i]; j < G_diag_I[i+1]; j++)
{
*GPi_diag_data++ = G_diag_data[j];
*GPi_diag_data++ = fabs(G_diag_data[j]) * 0.5 * Gx_data[i];
*GPi_diag_data++ = fabs(G_diag_data[j]) * 0.5 * Gy_data[i];
if (dim == 4)
*GPi_diag_data++ = fabs(G_diag_data[j]) * 0.5 * Gz_data[i];
}
}
/* Fill-in the off-diagonal part */
{
hypre_CSRMatrix *G_offd = hypre_ParCSRMatrixOffd(G);
HYPRE_Int *G_offd_I = hypre_CSRMatrixI(G_offd);
HYPRE_Int *G_offd_J = hypre_CSRMatrixJ(G_offd);
HYPRE_Real *G_offd_data = hypre_CSRMatrixData(G_offd);
HYPRE_Int G_offd_nrows = hypre_CSRMatrixNumRows(G_offd);
HYPRE_Int G_offd_ncols = hypre_CSRMatrixNumCols(G_offd);
HYPRE_Int G_offd_nnz = hypre_CSRMatrixNumNonzeros(G_offd);
hypre_CSRMatrix *GPi_offd = hypre_ParCSRMatrixOffd(GPi);
HYPRE_Int *GPi_offd_I = hypre_CSRMatrixI(GPi_offd);
HYPRE_Int *GPi_offd_J = hypre_CSRMatrixJ(GPi_offd);
HYPRE_Real *GPi_offd_data = hypre_CSRMatrixData(GPi_offd);
HYPRE_BigInt *G_cmap = hypre_ParCSRMatrixColMapOffd(G);
HYPRE_BigInt *GPi_cmap = hypre_ParCSRMatrixColMapOffd(GPi);
if (G_offd_ncols)
for (i = 0; i < G_offd_nrows+1; i++)
GPi_offd_I[i] = dim * G_offd_I[i];
for (i = 0; i < G_offd_nnz; i++)
for (d = 0; d < dim; d++)
GPi_offd_J[dim*i+d] = dim*G_offd_J[i]+d;
for (i = 0; i < G_offd_nrows; i++)
for (j = G_offd_I[i]; j < G_offd_I[i+1]; j++)
{
*GPi_offd_data++ = G_offd_data[j];
*GPi_offd_data++ = fabs(G_offd_data[j]) * 0.5 * Gx_data[i];
*GPi_offd_data++ = fabs(G_offd_data[j]) * 0.5 * Gy_data[i];
if (dim == 4)
*GPi_offd_data++ = fabs(G_offd_data[j]) * 0.5 * Gz_data[i];
}
for (i = 0; i < G_offd_ncols; i++)
for (d = 0; d < dim; d++)
GPi_cmap[dim*i+d] = dim*G_cmap[i]+d;
}
}
*GPi_ptr = GPi;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSetup
*
* Construct the AMS solver components.
*
* The following functions need to be called before hypre_AMSSetup():
* - hypre_AMSSetDimension() (if solving a 2D problem)
* - hypre_AMSSetDiscreteGradient()
* - hypre_AMSSetCoordinateVectors() or hypre_AMSSetEdgeConstantVectors
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSetup(void *solver,
hypre_ParCSRMatrix *A,
hypre_ParVector *b,
hypre_ParVector *x)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
HYPRE_Int input_info = 0;
ams_data -> A = A;
/* Modifications for problems with zero-conductivity regions */
if (ams_data -> interior_nodes)
{
hypre_ParCSRMatrix *G0t, *Aorig = A;
/* Make sure that multiple Setup()+Solve() give identical results */
ams_data -> solve_counter = 0;
/* Construct the discrete gradient matrix for the zero-conductivity region
by eliminating the zero-conductivity nodes from G^t. The range of G0
represents the kernel of A, i.e. the gradients of nodal basis functions
supported in zero-conductivity regions. */
hypre_ParCSRMatrixTranspose(ams_data -> G, &G0t, 1);
{
HYPRE_Int i, j;
HYPRE_Int nv = hypre_ParCSRMatrixNumCols(ams_data -> G);
hypre_CSRMatrix *G0td = hypre_ParCSRMatrixDiag(G0t);
HYPRE_Int *G0tdI = hypre_CSRMatrixI(G0td);
HYPRE_Real *G0tdA = hypre_CSRMatrixData(G0td);
hypre_CSRMatrix *G0to = hypre_ParCSRMatrixOffd(G0t);
HYPRE_Int *G0toI = hypre_CSRMatrixI(G0to);
HYPRE_Real *G0toA = hypre_CSRMatrixData(G0to);
HYPRE_Real *interior_nodes_data=hypre_VectorData(
hypre_ParVectorLocalVector((hypre_ParVector*) ams_data -> interior_nodes));
for (i = 0; i < nv; i++)
{
if (interior_nodes_data[i] != 1)
{
for (j = G0tdI[i]; j < G0tdI[i+1]; j++)
G0tdA[j] = 0.0;
if (G0toI)
for (j = G0toI[i]; j < G0toI[i+1]; j++)
G0toA[j] = 0.0;
}
}
}
hypre_ParCSRMatrixTranspose(G0t, & ams_data -> G0, 1);
/* Construct the subspace matrix A_G0 = G0^T G0 */
ams_data -> A_G0 = hypre_ParMatmul(G0t, ams_data -> G0);
hypre_ParCSRMatrixFixZeroRows(ams_data -> A_G0);
/* Create AMG solver for A_G0 */
HYPRE_BoomerAMGCreate(&ams_data -> B_G0);
HYPRE_BoomerAMGSetCoarsenType(ams_data -> B_G0, ams_data -> B_G_coarsen_type);
HYPRE_BoomerAMGSetAggNumLevels(ams_data -> B_G0, ams_data -> B_G_agg_levels);
HYPRE_BoomerAMGSetRelaxType(ams_data -> B_G0, ams_data -> B_G_relax_type);
HYPRE_BoomerAMGSetNumSweeps(ams_data -> B_G0, 1);
HYPRE_BoomerAMGSetMaxLevels(ams_data -> B_G0, 25);
HYPRE_BoomerAMGSetTol(ams_data -> B_G0, 0.0);
HYPRE_BoomerAMGSetMaxIter(ams_data -> B_G0, 3); /* use just a few V-cycles */
HYPRE_BoomerAMGSetStrongThreshold(ams_data -> B_G0, ams_data -> B_G_theta);
HYPRE_BoomerAMGSetInterpType(ams_data -> B_G0, ams_data -> B_G_interp_type);
HYPRE_BoomerAMGSetPMaxElmts(ams_data -> B_G0, ams_data -> B_G_Pmax);
HYPRE_BoomerAMGSetMinCoarseSize(ams_data -> B_G0, 2); /* don't coarsen to 0 */
/* Generally, don't use exact solve on the coarsest level (matrix may be singular) */
HYPRE_BoomerAMGSetCycleRelaxType(ams_data -> B_G0, ams_data -> B_G_coarse_relax_type, 3);
HYPRE_BoomerAMGSetup(ams_data -> B_G0,
(HYPRE_ParCSRMatrix)ams_data -> A_G0,
0, 0);
/* Construct the preconditioner for ams_data->A = A + G0 G0^T.
NOTE: this can be optimized significantly by taking into account that
the sparsity pattern of A is subset of the sparsity pattern of G0 G0^T */
{
hypre_ParCSRMatrix *A = hypre_ParMatmul(ams_data -> G0, G0t);
hypre_ParCSRMatrix *B = Aorig;
hypre_ParCSRMatrix **C_ptr = &ams_data -> A;
hypre_ParCSRMatrix *C;
HYPRE_Real factor, lfactor;
/* scale (penalize) G0 G0^T before adding it to the matrix */
{
HYPRE_Int i;
HYPRE_Int B_num_rows = hypre_CSRMatrixNumRows(hypre_ParCSRMatrixDiag(B));
HYPRE_Real *B_diag_data = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(B));
HYPRE_Real *B_offd_data = hypre_CSRMatrixData(hypre_ParCSRMatrixOffd(B));
HYPRE_Int *B_diag_i = hypre_CSRMatrixI(hypre_ParCSRMatrixDiag(B));
HYPRE_Int *B_offd_i = hypre_CSRMatrixI(hypre_ParCSRMatrixOffd(B));
lfactor = -1;
for (i = 0; i < B_diag_i[B_num_rows]; i++)
if (fabs(B_diag_data[i]) > lfactor)
lfactor = fabs(B_diag_data[i]);
for (i = 0; i < B_offd_i[B_num_rows]; i++)
if (fabs(B_offd_data[i]) > lfactor)
lfactor = fabs(B_offd_data[i]);
lfactor *= 1e-10; /* scaling factor: max|A_ij|*1e-10 */
hypre_MPI_Allreduce(&lfactor, &factor, 1, HYPRE_MPI_REAL, hypre_MPI_MAX,
hypre_ParCSRMatrixComm(A));
}
hypre_ParcsrAdd(factor, A, 1.0, B, &C);
/*hypre_CSRMatrix *A_local, *B_local, *C_local, *C_tmp;
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
HYPRE_BigInt global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A);
HYPRE_BigInt global_num_cols = hypre_ParCSRMatrixGlobalNumCols(A);
HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(A);
HYPRE_BigInt *col_starts = hypre_ParCSRMatrixColStarts(A);
HYPRE_Int A_num_cols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(A));
HYPRE_Int A_num_nonzeros_diag = hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixDiag(A));
HYPRE_Int A_num_nonzeros_offd = hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixOffd(A));
HYPRE_Int B_num_cols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(B));
HYPRE_Int B_num_nonzeros_diag = hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixDiag(B));
HYPRE_Int B_num_nonzeros_offd = hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixOffd(B));
A_local = hypre_MergeDiagAndOffd(A);
B_local = hypre_MergeDiagAndOffd(B);*/
/* scale (penalize) G0 G0^T before adding it to the matrix */
/*{
HYPRE_Int i, nnz = hypre_CSRMatrixNumNonzeros(A_local);
HYPRE_Real *data = hypre_CSRMatrixData(A_local);
HYPRE_Real *dataB = hypre_CSRMatrixData(B_local);
HYPRE_Int nnzB = hypre_CSRMatrixNumNonzeros(B_local);
HYPRE_Real factor, lfactor;
lfactor = -1;
for (i = 0; i < nnzB; i++)
if (fabs(dataB[i]) > lfactor)
lfactor = fabs(dataB[i]);
lfactor *= 1e-10;
hypre_MPI_Allreduce(&lfactor, &factor, 1, HYPRE_MPI_REAL, hypre_MPI_MAX,
hypre_ParCSRMatrixComm(A));
for (i = 0; i < nnz; i++)
data[i] *= factor;
}
C_tmp = hypre_CSRMatrixBigAdd(A_local, B_local);
C_local = hypre_CSRMatrixBigDeleteZeros(C_tmp,0.0);
if (C_local)
hypre_CSRMatrixDestroy(C_tmp);
else
C_local = C_tmp;
C = hypre_ParCSRMatrixCreate (comm,
global_num_rows,
global_num_cols,
row_starts,
col_starts,
A_num_cols_offd + B_num_cols_offd,
A_num_nonzeros_diag + B_num_nonzeros_diag,
A_num_nonzeros_offd + B_num_nonzeros_offd);
GenerateDiagAndOffd(C_local, C,
hypre_ParCSRMatrixFirstColDiag(A),
hypre_ParCSRMatrixLastColDiag(A));
hypre_ParCSRMatrixOwnsRowStarts(C) = 0;
hypre_ParCSRMatrixOwnsColStarts(C) = 1;
hypre_ParCSRMatrixOwnsColStarts(G0t) = 0;
hypre_CSRMatrixDestroy(A_local);
hypre_CSRMatrixDestroy(B_local);
hypre_CSRMatrixDestroy(C_local);
*/
hypre_ParCSRMatrixDestroy(A);
*C_ptr = C;
}
hypre_ParCSRMatrixDestroy(G0t);
}
/* Make sure that the first entry in each row is the diagonal one. */
/* hypre_CSRMatrixReorder(hypre_ParCSRMatrixDiag(ams_data -> A)); */
/* Compute the l1 norm of the rows of A */
if (ams_data -> A_relax_type >= 1 && ams_data -> A_relax_type <= 4)
{
HYPRE_Real *l1_norm_data = NULL;
hypre_ParCSRComputeL1Norms(ams_data -> A, ams_data -> A_relax_type, NULL, &l1_norm_data);
ams_data -> A_l1_norms = hypre_SeqVectorCreate(hypre_ParCSRMatrixNumRows(ams_data -> A));
hypre_VectorData(ams_data -> A_l1_norms) = l1_norm_data;
hypre_SeqVectorInitialize_v2(ams_data -> A_l1_norms, hypre_ParCSRMatrixMemoryLocation(ams_data -> A));
}
/* Chebyshev? */
if (ams_data -> A_relax_type == 16)
{
hypre_ParCSRMaxEigEstimateCG(ams_data->A, 1, 10,
&ams_data->A_max_eig_est,
&ams_data->A_min_eig_est);
}
/* If not given, compute Gx, Gy and Gz */
{
if (ams_data -> x != NULL && ams_data -> y != NULL &&
(ams_data -> dim == 2 || ams_data -> z != NULL))
input_info = 1;
if (ams_data -> Gx != NULL && ams_data -> Gy != NULL &&
(ams_data -> dim == 2 || ams_data -> Gz != NULL))
input_info = 2;
if (input_info == 1)
{
ams_data -> Gx = hypre_ParVectorInRangeOf(ams_data -> G);
hypre_ParCSRMatrixMatvec (1.0, ams_data -> G, ams_data -> x, 0.0, ams_data -> Gx);
ams_data -> Gy = hypre_ParVectorInRangeOf(ams_data -> G);
hypre_ParCSRMatrixMatvec (1.0, ams_data -> G, ams_data -> y, 0.0, ams_data -> Gy);
if (ams_data -> dim == 3)
{
ams_data -> Gz = hypre_ParVectorInRangeOf(ams_data -> G);
hypre_ParCSRMatrixMatvec (1.0, ams_data -> G, ams_data -> z, 0.0, ams_data -> Gz);
}
}
}
if (ams_data -> Pi == NULL && ams_data -> Pix == NULL)
{
if (ams_data -> cycle_type == 20)
/* Construct the combined interpolation matrix [G,Pi] */
hypre_AMSComputeGPi(ams_data -> A,
ams_data -> G,
ams_data -> Gx,
ams_data -> Gy,
ams_data -> Gz,
ams_data -> dim,
&ams_data -> Pi);
else if (ams_data -> cycle_type > 10)
/* Construct Pi{x,y,z} instead of Pi = [Pix,Piy,Piz] */
hypre_AMSComputePixyz(ams_data -> A,
ams_data -> G,
ams_data -> Gx,
ams_data -> Gy,
ams_data -> Gz,
ams_data -> dim,
&ams_data -> Pix,
&ams_data -> Piy,
&ams_data -> Piz);
else
/* Construct the Pi interpolation matrix */
hypre_AMSComputePi(ams_data -> A,
ams_data -> G,
ams_data -> Gx,
ams_data -> Gy,
ams_data -> Gz,
ams_data -> dim,
&ams_data -> Pi);
}
/* Keep Gx, Gy and Gz only if use the method with discrete divergence
stabilization (where we use them to compute the local mesh size). */
if (input_info == 1 && ams_data -> cycle_type != 9)
{
hypre_ParVectorDestroy(ams_data -> Gx);
hypre_ParVectorDestroy(ams_data -> Gy);
if (ams_data -> dim == 3)
hypre_ParVectorDestroy(ams_data -> Gz);
}
/* Create the AMG solver on the range of G^T */
if (!ams_data -> beta_is_zero && ams_data -> cycle_type != 20)
{
HYPRE_BoomerAMGCreate(&ams_data -> B_G);
HYPRE_BoomerAMGSetCoarsenType(ams_data -> B_G, ams_data -> B_G_coarsen_type);
HYPRE_BoomerAMGSetAggNumLevels(ams_data -> B_G, ams_data -> B_G_agg_levels);
HYPRE_BoomerAMGSetRelaxType(ams_data -> B_G, ams_data -> B_G_relax_type);
HYPRE_BoomerAMGSetNumSweeps(ams_data -> B_G, 1);
HYPRE_BoomerAMGSetMaxLevels(ams_data -> B_G, 25);
HYPRE_BoomerAMGSetTol(ams_data -> B_G, 0.0);
HYPRE_BoomerAMGSetMaxIter(ams_data -> B_G, 1);
HYPRE_BoomerAMGSetStrongThreshold(ams_data -> B_G, ams_data -> B_G_theta);
HYPRE_BoomerAMGSetInterpType(ams_data -> B_G, ams_data -> B_G_interp_type);
HYPRE_BoomerAMGSetPMaxElmts(ams_data -> B_G, ams_data -> B_G_Pmax);
HYPRE_BoomerAMGSetMinCoarseSize(ams_data -> B_G, 2); /* don't coarsen to 0 */
/* Generally, don't use exact solve on the coarsest level (matrix may be singular) */
HYPRE_BoomerAMGSetCycleRelaxType(ams_data -> B_G, ams_data -> B_G_coarse_relax_type, 3);
if (ams_data -> cycle_type == 0)
HYPRE_BoomerAMGSetMaxLevels(ams_data -> B_G, 2);
/* If not given, construct the coarse space matrix by RAP */
if (!ams_data -> A_G)
{
HYPRE_Int G_owned_col_starts;
if (!hypre_ParCSRMatrixCommPkg(ams_data -> G))
hypre_MatvecCommPkgCreate(ams_data -> G);
if (!hypre_ParCSRMatrixCommPkg(ams_data -> A))
hypre_MatvecCommPkgCreate(ams_data -> A);
G_owned_col_starts = hypre_ParCSRMatrixOwnsColStarts(ams_data -> G);
hypre_BoomerAMGBuildCoarseOperator(ams_data -> G,
ams_data -> A,
ams_data -> G,
&ams_data -> A_G);
/* Make sure that A_G has no zero rows (this can happen
if beta is zero in part of the domain). */
hypre_ParCSRMatrixFixZeroRows(ams_data -> A_G);
hypre_ParCSRMatrixOwnsColStarts(ams_data -> G) = G_owned_col_starts;
hypre_ParCSRMatrixOwnsRowStarts(ams_data -> A_G) = 0;
ams_data -> owns_A_G = 1;
}
HYPRE_BoomerAMGSetup(ams_data -> B_G,
(HYPRE_ParCSRMatrix)ams_data -> A_G,
0, 0);
}
if (ams_data -> cycle_type > 10 && ams_data -> cycle_type != 20)
/* Create the AMG solvers on the range of Pi{x,y,z}^T */
{
HYPRE_Int P_owned_col_starts;
HYPRE_BoomerAMGCreate(&ams_data -> B_Pix);
HYPRE_BoomerAMGSetCoarsenType(ams_data -> B_Pix, ams_data -> B_Pi_coarsen_type);
HYPRE_BoomerAMGSetAggNumLevels(ams_data -> B_Pix, ams_data -> B_Pi_agg_levels);
HYPRE_BoomerAMGSetRelaxType(ams_data -> B_Pix, ams_data -> B_Pi_relax_type);
HYPRE_BoomerAMGSetNumSweeps(ams_data -> B_Pix, 1);
HYPRE_BoomerAMGSetMaxLevels(ams_data -> B_Pix, 25);
HYPRE_BoomerAMGSetTol(ams_data -> B_Pix, 0.0);
HYPRE_BoomerAMGSetMaxIter(ams_data -> B_Pix, 1);
HYPRE_BoomerAMGSetStrongThreshold(ams_data -> B_Pix, ams_data -> B_Pi_theta);
HYPRE_BoomerAMGSetInterpType(ams_data -> B_Pix, ams_data -> B_Pi_interp_type);
HYPRE_BoomerAMGSetPMaxElmts(ams_data -> B_Pix, ams_data -> B_Pi_Pmax);
HYPRE_BoomerAMGSetMinCoarseSize(ams_data -> B_Pix, 2);
HYPRE_BoomerAMGCreate(&ams_data -> B_Piy);
HYPRE_BoomerAMGSetCoarsenType(ams_data -> B_Piy, ams_data -> B_Pi_coarsen_type);
HYPRE_BoomerAMGSetAggNumLevels(ams_data -> B_Piy, ams_data -> B_Pi_agg_levels);
HYPRE_BoomerAMGSetRelaxType(ams_data -> B_Piy, ams_data -> B_Pi_relax_type);
HYPRE_BoomerAMGSetNumSweeps(ams_data -> B_Piy, 1);
HYPRE_BoomerAMGSetMaxLevels(ams_data -> B_Piy, 25);
HYPRE_BoomerAMGSetTol(ams_data -> B_Piy, 0.0);
HYPRE_BoomerAMGSetMaxIter(ams_data -> B_Piy, 1);
HYPRE_BoomerAMGSetStrongThreshold(ams_data -> B_Piy, ams_data -> B_Pi_theta);
HYPRE_BoomerAMGSetInterpType(ams_data -> B_Piy, ams_data -> B_Pi_interp_type);
HYPRE_BoomerAMGSetPMaxElmts(ams_data -> B_Piy, ams_data -> B_Pi_Pmax);
HYPRE_BoomerAMGSetMinCoarseSize(ams_data -> B_Piy, 2);
HYPRE_BoomerAMGCreate(&ams_data -> B_Piz);
HYPRE_BoomerAMGSetCoarsenType(ams_data -> B_Piz, ams_data -> B_Pi_coarsen_type);
HYPRE_BoomerAMGSetAggNumLevels(ams_data -> B_Piz, ams_data -> B_Pi_agg_levels);
HYPRE_BoomerAMGSetRelaxType(ams_data -> B_Piz, ams_data -> B_Pi_relax_type);
HYPRE_BoomerAMGSetNumSweeps(ams_data -> B_Piz, 1);
HYPRE_BoomerAMGSetMaxLevels(ams_data -> B_Piz, 25);
HYPRE_BoomerAMGSetTol(ams_data -> B_Piz, 0.0);
HYPRE_BoomerAMGSetMaxIter(ams_data -> B_Piz, 1);
HYPRE_BoomerAMGSetStrongThreshold(ams_data -> B_Piz, ams_data -> B_Pi_theta);
HYPRE_BoomerAMGSetInterpType(ams_data -> B_Piz, ams_data -> B_Pi_interp_type);
HYPRE_BoomerAMGSetPMaxElmts(ams_data -> B_Piz, ams_data -> B_Pi_Pmax);
HYPRE_BoomerAMGSetMinCoarseSize(ams_data -> B_Piz, 2);
/* Generally, don't use exact solve on the coarsest level (matrices may be singular) */
HYPRE_BoomerAMGSetCycleRelaxType(ams_data -> B_Pix, ams_data -> B_Pi_coarse_relax_type, 3);
HYPRE_BoomerAMGSetCycleRelaxType(ams_data -> B_Piy, ams_data -> B_Pi_coarse_relax_type, 3);
HYPRE_BoomerAMGSetCycleRelaxType(ams_data -> B_Piz, ams_data -> B_Pi_coarse_relax_type, 3);
if (ams_data -> cycle_type == 0)
{
HYPRE_BoomerAMGSetMaxLevels(ams_data -> B_Pix, 2);
HYPRE_BoomerAMGSetMaxLevels(ams_data -> B_Piy, 2);
HYPRE_BoomerAMGSetMaxLevels(ams_data -> B_Piz, 2);
}
/* Construct the coarse space matrices by RAP */
if (!hypre_ParCSRMatrixCommPkg(ams_data -> Pix))
hypre_MatvecCommPkgCreate(ams_data -> Pix);
P_owned_col_starts = hypre_ParCSRMatrixOwnsColStarts(ams_data -> Pix);
hypre_BoomerAMGBuildCoarseOperator(ams_data -> Pix,
ams_data -> A,
ams_data -> Pix,
&ams_data -> A_Pix);
if (!P_owned_col_starts)
{
hypre_ParCSRMatrixOwnsRowStarts(ams_data -> A_Pix) = 0;
hypre_ParCSRMatrixOwnsColStarts(ams_data -> A_Pix) = 0;
}
/* Make sure that A_Pix has no zero rows (this can happen
for some kinds of boundary conditions with contact). */
hypre_ParCSRMatrixFixZeroRows(ams_data -> A_Pix);
HYPRE_BoomerAMGSetup(ams_data -> B_Pix,
(HYPRE_ParCSRMatrix)ams_data -> A_Pix,
0, 0);
if (!hypre_ParCSRMatrixCommPkg(ams_data -> Piy))
hypre_MatvecCommPkgCreate(ams_data -> Piy);
P_owned_col_starts = hypre_ParCSRMatrixOwnsColStarts(ams_data -> Piy);
hypre_BoomerAMGBuildCoarseOperator(ams_data -> Piy,
ams_data -> A,
ams_data -> Piy,
&ams_data -> A_Piy);
if (!P_owned_col_starts)
{
hypre_ParCSRMatrixOwnsRowStarts(ams_data -> A_Piy) = 0;
hypre_ParCSRMatrixOwnsColStarts(ams_data -> A_Piy) = 0;
}
/* Make sure that A_Piy has no zero rows (this can happen
for some kinds of boundary conditions with contact). */
hypre_ParCSRMatrixFixZeroRows(ams_data -> A_Piy);
HYPRE_BoomerAMGSetup(ams_data -> B_Piy,
(HYPRE_ParCSRMatrix)ams_data -> A_Piy,
0, 0);
if (ams_data -> Piz)
{
if (!hypre_ParCSRMatrixCommPkg(ams_data -> Piz))
hypre_MatvecCommPkgCreate(ams_data -> Piz);
P_owned_col_starts = hypre_ParCSRMatrixOwnsColStarts(ams_data -> Piz);
hypre_BoomerAMGBuildCoarseOperator(ams_data -> Piz,
ams_data -> A,
ams_data -> Piz,
&ams_data -> A_Piz);
if (!P_owned_col_starts)
{
hypre_ParCSRMatrixOwnsRowStarts(ams_data -> A_Piz) = 0;
hypre_ParCSRMatrixOwnsColStarts(ams_data -> A_Piz) = 0;
}
/* Make sure that A_Piz has no zero rows (this can happen
for some kinds of boundary conditions with contact). */
hypre_ParCSRMatrixFixZeroRows(ams_data -> A_Piz);
HYPRE_BoomerAMGSetup(ams_data -> B_Piz,
(HYPRE_ParCSRMatrix)ams_data -> A_Piz,
0, 0);
}
}
else
/* Create the AMG solver on the range of Pi^T */
{
HYPRE_BoomerAMGCreate(&ams_data -> B_Pi);
HYPRE_BoomerAMGSetCoarsenType(ams_data -> B_Pi, ams_data -> B_Pi_coarsen_type);
HYPRE_BoomerAMGSetAggNumLevels(ams_data -> B_Pi, ams_data -> B_Pi_agg_levels);
HYPRE_BoomerAMGSetRelaxType(ams_data -> B_Pi, ams_data -> B_Pi_relax_type);
HYPRE_BoomerAMGSetNumSweeps(ams_data -> B_Pi, 1);
HYPRE_BoomerAMGSetMaxLevels(ams_data -> B_Pi, 25);
HYPRE_BoomerAMGSetTol(ams_data -> B_Pi, 0.0);
HYPRE_BoomerAMGSetMaxIter(ams_data -> B_Pi, 1);
HYPRE_BoomerAMGSetStrongThreshold(ams_data -> B_Pi, ams_data -> B_Pi_theta);
HYPRE_BoomerAMGSetInterpType(ams_data -> B_Pi, ams_data -> B_Pi_interp_type);
HYPRE_BoomerAMGSetPMaxElmts(ams_data -> B_Pi, ams_data -> B_Pi_Pmax);
HYPRE_BoomerAMGSetMinCoarseSize(ams_data -> B_Pi, 2); /* don't coarsen to 0 */
/* Generally, don't use exact solve on the coarsest level (matrix may be singular) */
HYPRE_BoomerAMGSetCycleRelaxType(ams_data -> B_Pi, ams_data -> B_Pi_coarse_relax_type, 3);
if (ams_data -> cycle_type == 0)
HYPRE_BoomerAMGSetMaxLevels(ams_data -> B_Pi, 2);
/* If not given, construct the coarse space matrix by RAP and
notify BoomerAMG that this is a dim x dim block system. */
if (!ams_data -> A_Pi)
{
HYPRE_Int P_owned_col_starts = hypre_ParCSRMatrixOwnsColStarts(ams_data -> Pi);
if (!hypre_ParCSRMatrixCommPkg(ams_data -> Pi))
hypre_MatvecCommPkgCreate(ams_data -> Pi);
if (!hypre_ParCSRMatrixCommPkg(ams_data -> A))
hypre_MatvecCommPkgCreate(ams_data -> A);
if (ams_data -> cycle_type == 9)
{
/* Add a discrete divergence term to A before computing Pi^t A Pi */
{
hypre_ParCSRMatrix *Gt, *GGt, *ApGGt;
hypre_ParCSRMatrixTranspose(ams_data -> G, &Gt, 1);
hypre_ParCSRMatrixOwnsColStarts(Gt) = 0;
hypre_ParCSRMatrixOwnsRowStarts(Gt) = 0;
/* scale GGt by h^2 */
{
HYPRE_Real h2;
HYPRE_Int i, j, k, ne;
hypre_CSRMatrix *Gt_diag = hypre_ParCSRMatrixDiag(Gt);
HYPRE_Int Gt_num_rows = hypre_CSRMatrixNumRows(Gt_diag);
HYPRE_Int *Gt_diag_I = hypre_CSRMatrixI(Gt_diag);
HYPRE_Int *Gt_diag_J = hypre_CSRMatrixJ(Gt_diag);
HYPRE_Real *Gt_diag_data = hypre_CSRMatrixData(Gt_diag);
hypre_CSRMatrix *Gt_offd = hypre_ParCSRMatrixOffd(Gt);
HYPRE_Int *Gt_offd_I = hypre_CSRMatrixI(Gt_offd);
HYPRE_Real *Gt_offd_data = hypre_CSRMatrixData(Gt_offd);
HYPRE_Real *Gx_data = hypre_VectorData(hypre_ParVectorLocalVector(ams_data -> Gx));
HYPRE_Real *Gy_data = hypre_VectorData(hypre_ParVectorLocalVector(ams_data -> Gy));
HYPRE_Real *Gz_data = hypre_VectorData(hypre_ParVectorLocalVector(ams_data -> Gz));
for (i = 0; i < Gt_num_rows; i++)
{
/* determine the characteristic mesh size for vertex i */
h2 = 0.0;
ne = 0;
for (j = Gt_diag_I[i]; j < Gt_diag_I[i+1]; j++)
{
k = Gt_diag_J[j];
h2 += Gx_data[k]*Gx_data[k]+Gy_data[k]*Gy_data[k]+Gz_data[k]*Gz_data[k];
ne++;
}
if (ne != 0)
{
h2 /= ne;
for (j = Gt_diag_I[i]; j < Gt_diag_I[i+1]; j++)
Gt_diag_data[j] *= h2;
for (j = Gt_offd_I[i]; j < Gt_offd_I[i+1]; j++)
Gt_offd_data[j] *= h2;
}
}
}
/* we only needed Gx, Gy and Gz to compute the local mesh size */
if (input_info == 1)
{
hypre_ParVectorDestroy(ams_data -> Gx);
hypre_ParVectorDestroy(ams_data -> Gy);
if (ams_data -> dim == 3)
hypre_ParVectorDestroy(ams_data -> Gz);
}
GGt = hypre_ParMatmul(ams_data -> G, Gt);
hypre_ParCSRMatrixDestroy(Gt);
/* hypre_ParCSRMatrixAdd(GGt, A, &ams_data -> A); */
hypre_ParcsrAdd(1.0, GGt, 1.0, ams_data -> A, &ApGGt);
/*{
hypre_ParCSRMatrix *A = GGt;
hypre_ParCSRMatrix *B = ams_data -> A;
hypre_ParCSRMatrix **C_ptr = &ApGGt;
hypre_ParCSRMatrix *C;
hypre_CSRMatrix *A_local, *B_local, *C_local;
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
HYPRE_BigInt global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A);
HYPRE_BigInt global_num_cols = hypre_ParCSRMatrixGlobalNumCols(A);
HYPRE_BigInt *row_starts = hypre_ParCSRMatrixRowStarts(A);
HYPRE_BigInt *col_starts = hypre_ParCSRMatrixColStarts(A);
HYPRE_Int A_num_cols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(A));
HYPRE_Int A_num_nonzeros_diag = hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixDiag(A));
HYPRE_Int A_num_nonzeros_offd = hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixOffd(A));
HYPRE_Int B_num_cols_offd = hypre_CSRMatrixNumCols(hypre_ParCSRMatrixOffd(B));
HYPRE_Int B_num_nonzeros_diag = hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixDiag(B));
HYPRE_Int B_num_nonzeros_offd = hypre_CSRMatrixNumNonzeros(hypre_ParCSRMatrixOffd(B));
A_local = hypre_MergeDiagAndOffd(A);
B_local = hypre_MergeDiagAndOffd(B);
C_local = hypre_CSRMatrixBigAdd(A_local, B_local);
hypre_CSRMatrixBigJtoJ(C_local);
C = hypre_ParCSRMatrixCreate (comm,
global_num_rows,
global_num_cols,
row_starts,
col_starts,
A_num_cols_offd + B_num_cols_offd,
A_num_nonzeros_diag + B_num_nonzeros_diag,
A_num_nonzeros_offd + B_num_nonzeros_offd);
GenerateDiagAndOffd(C_local, C,
hypre_ParCSRMatrixFirstColDiag(A),
hypre_ParCSRMatrixLastColDiag(A));
hypre_ParCSRMatrixOwnsRowStarts(C) = 0;
hypre_ParCSRMatrixOwnsColStarts(C) = 0;
hypre_CSRMatrixDestroy(A_local);
hypre_CSRMatrixDestroy(B_local);
hypre_CSRMatrixDestroy(C_local);
*C_ptr = C;
}*/
hypre_ParCSRMatrixDestroy(GGt);
hypre_BoomerAMGBuildCoarseOperator(ams_data -> Pi,
ApGGt,
ams_data -> Pi,
&ams_data -> A_Pi);
}
}
else
{
hypre_BoomerAMGBuildCoarseOperator(ams_data -> Pi,
ams_data -> A,
ams_data -> Pi,
&ams_data -> A_Pi);
}
if (!P_owned_col_starts)
{
hypre_ParCSRMatrixOwnsRowStarts(ams_data -> A_Pi) = 0;
hypre_ParCSRMatrixOwnsColStarts(ams_data -> A_Pi) = 0;
}
ams_data -> owns_A_Pi = 1;
if (ams_data -> cycle_type != 20)
HYPRE_BoomerAMGSetNumFunctions(ams_data -> B_Pi, ams_data -> dim);
else
HYPRE_BoomerAMGSetNumFunctions(ams_data -> B_Pi, ams_data -> dim + 1);
/* HYPRE_BoomerAMGSetNodal(ams_data -> B_Pi, 1); */
}
/* Make sure that A_Pi has no zero rows (this can happen for
some kinds of boundary conditions with contact). */
hypre_ParCSRMatrixFixZeroRows(ams_data -> A_Pi);
HYPRE_BoomerAMGSetup(ams_data -> B_Pi,
(HYPRE_ParCSRMatrix)ams_data -> A_Pi,
0, 0);
}
/* Allocate temporary vectors */
ams_data -> r0 = hypre_ParVectorInRangeOf(ams_data -> A);
ams_data -> g0 = hypre_ParVectorInRangeOf(ams_data -> A);
if (ams_data -> A_G)
{
ams_data -> r1 = hypre_ParVectorInRangeOf(ams_data -> A_G);
ams_data -> g1 = hypre_ParVectorInRangeOf(ams_data -> A_G);
}
if (ams_data -> r1 == NULL && ams_data -> A_Pix)
{
ams_data -> r1 = hypre_ParVectorInRangeOf(ams_data -> A_Pix);
ams_data -> g1 = hypre_ParVectorInRangeOf(ams_data -> A_Pix);
}
if (ams_data -> Pi)
{
ams_data -> r2 = hypre_ParVectorInDomainOf(ams_data -> Pi);
ams_data -> g2 = hypre_ParVectorInDomainOf(ams_data -> Pi);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSSolve
*
* Solve the system A x = b.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSSolve(void *solver,
hypre_ParCSRMatrix *A,
hypre_ParVector *b,
hypre_ParVector *x)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
HYPRE_Int i, my_id = -1;
HYPRE_Real r0_norm, r_norm, b_norm, relative_resid = 0, old_resid;
char cycle[30];
hypre_ParCSRMatrix *Ai[5], *Pi[5];
HYPRE_Solver Bi[5];
HYPRE_PtrToSolverFcn HBi[5];
hypre_ParVector *ri[5], *gi[5];
hypre_ParVector *z = NULL;
Ai[0] = ams_data -> A_G; Pi[0] = ams_data -> G;
Ai[1] = ams_data -> A_Pi; Pi[1] = ams_data -> Pi;
Ai[2] = ams_data -> A_Pix; Pi[2] = ams_data -> Pix;
Ai[3] = ams_data -> A_Piy; Pi[3] = ams_data -> Piy;
Ai[4] = ams_data -> A_Piz; Pi[4] = ams_data -> Piz;
Bi[0] = ams_data -> B_G; HBi[0] = (HYPRE_PtrToSolverFcn) hypre_BoomerAMGSolve;
Bi[1] = ams_data -> B_Pi; HBi[1] = (HYPRE_PtrToSolverFcn) hypre_BoomerAMGBlockSolve;
Bi[2] = ams_data -> B_Pix; HBi[2] = (HYPRE_PtrToSolverFcn) hypre_BoomerAMGSolve;
Bi[3] = ams_data -> B_Piy; HBi[3] = (HYPRE_PtrToSolverFcn) hypre_BoomerAMGSolve;
Bi[4] = ams_data -> B_Piz; HBi[4] = (HYPRE_PtrToSolverFcn) hypre_BoomerAMGSolve;
ri[0] = ams_data -> r1; gi[0] = ams_data -> g1;
ri[1] = ams_data -> r2; gi[1] = ams_data -> g2;
ri[2] = ams_data -> r1; gi[2] = ams_data -> g1;
ri[3] = ams_data -> r1; gi[3] = ams_data -> g1;
ri[4] = ams_data -> r1; gi[4] = ams_data -> g1;
/* may need to create an additional temporary vector for relaxation */
if (hypre_NumThreads() > 1 || ams_data -> A_relax_type == 16)
{
z = hypre_ParVectorCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumRows(A),
hypre_ParCSRMatrixRowStarts(A));
hypre_ParVectorInitialize(z);
hypre_ParVectorSetPartitioningOwner(z,0);
}
if (ams_data -> print_level > 0)
hypre_MPI_Comm_rank(hypre_ParCSRMatrixComm(A), &my_id);
/* Compatible subspace projection for problems with zero-conductivity regions.
Note that this modifies the input (r.h.s.) vector b! */
if ( (ams_data -> B_G0) &&
(++ams_data->solve_counter % ( ams_data -> projection_frequency ) == 0) )
{
/* hypre_printf("Projecting onto the compatible subspace...\n"); */
hypre_AMSProjectOutGradients(ams_data, b);
}
if (ams_data -> beta_is_zero)
{
switch (ams_data -> cycle_type)
{
case 0:
hypre_sprintf(cycle,"%s","0");
break;
case 1:
case 3:
case 5:
case 7:
default:
hypre_sprintf(cycle,"%s","020");
break;
case 2:
case 4:
case 6:
case 8:
hypre_sprintf(cycle,"%s","(0+2)");
break;
case 11:
case 13:
hypre_sprintf(cycle,"%s","0345430");
break;
case 12:
hypre_sprintf(cycle,"%s","(0+3+4+5)");
break;
case 14:
hypre_sprintf(cycle,"%s","0(+3+4+5)0");
break;
}
}
else
{
switch (ams_data -> cycle_type)
{
case 0:
hypre_sprintf(cycle,"%s","010");
break;
case 1:
default:
hypre_sprintf(cycle,"%s","01210");
break;
case 2:
hypre_sprintf(cycle,"%s","(0+1+2)");
break;
case 3:
hypre_sprintf(cycle,"%s","02120");
break;
case 4:
hypre_sprintf(cycle,"%s","(010+2)");
break;
case 5:
hypre_sprintf(cycle,"%s","0102010");
break;
case 6:
hypre_sprintf(cycle,"%s","(020+1)");
break;
case 7:
hypre_sprintf(cycle,"%s","0201020");
break;
case 8:
hypre_sprintf(cycle,"%s","0(+1+2)0");
break;
case 9:
hypre_sprintf(cycle,"%s","01210");
break;
case 11:
hypre_sprintf(cycle,"%s","013454310");
break;
case 12:
hypre_sprintf(cycle,"%s","(0+1+3+4+5)");
break;
case 13:
hypre_sprintf(cycle,"%s","034515430");
break;
case 14:
hypre_sprintf(cycle,"%s","01(+3+4+5)10");
break;
case 20:
hypre_sprintf(cycle,"%s","020");
break;
}
}
for (i = 0; i < ams_data -> maxit; i++)
{
/* Compute initial residual norms */
if (ams_data -> maxit > 1 && i == 0)
{
hypre_ParVectorCopy(b, ams_data -> r0);
hypre_ParCSRMatrixMatvec(-1.0, ams_data -> A, x, 1.0, ams_data -> r0);
r_norm = sqrt(hypre_ParVectorInnerProd(ams_data -> r0,ams_data -> r0));
r0_norm = r_norm;
b_norm = sqrt(hypre_ParVectorInnerProd(b, b));
if (b_norm)
relative_resid = r_norm / b_norm;
else
relative_resid = r_norm;
if (my_id == 0 && ams_data -> print_level > 0)
{
hypre_printf(" relative\n");
hypre_printf(" residual factor residual\n");
hypre_printf(" -------- ------ --------\n");
hypre_printf(" Initial %e %e\n",
r_norm, relative_resid);
}
}
/* Apply the preconditioner */
hypre_ParCSRSubspacePrec(ams_data -> A,
ams_data -> A_relax_type,
ams_data -> A_relax_times,
ams_data -> A_l1_norms ? hypre_VectorData(ams_data -> A_l1_norms) : NULL,
ams_data -> A_relax_weight,
ams_data -> A_omega,
ams_data -> A_max_eig_est,
ams_data -> A_min_eig_est,
ams_data -> A_cheby_order,
ams_data -> A_cheby_fraction,
Ai, Bi, HBi, Pi, ri, gi,
b, x,
ams_data -> r0,
ams_data -> g0,
cycle,
z);
/* Compute new residual norms */
if (ams_data -> maxit > 1)
{
old_resid = r_norm;
hypre_ParVectorCopy(b, ams_data -> r0);
hypre_ParCSRMatrixMatvec(-1.0, ams_data -> A, x, 1.0, ams_data -> r0);
r_norm = sqrt(hypre_ParVectorInnerProd(ams_data -> r0,ams_data -> r0));
if (b_norm)
relative_resid = r_norm / b_norm;
else
relative_resid = r_norm;
if (my_id == 0 && ams_data -> print_level > 0)
hypre_printf(" Cycle %2d %e %f %e \n",
i+1, r_norm, r_norm / old_resid, relative_resid);
}
if (relative_resid < ams_data -> tol)
{
i++;
break;
}
}
if (my_id == 0 && ams_data -> print_level > 0 && ams_data -> maxit > 1)
hypre_printf("\n\n Average Convergence Factor = %f\n\n",
pow((r_norm/r0_norm),(1.0/(HYPRE_Real) i)));
ams_data -> num_iterations = i;
ams_data -> rel_resid_norm = relative_resid;
if (ams_data -> num_iterations == ams_data -> maxit && ams_data -> tol > 0.0)
hypre_error(HYPRE_ERROR_CONV);
if (z)
hypre_ParVectorDestroy(z);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_ParCSRSubspacePrec
*
* General subspace preconditioner for A0 y = x, based on ParCSR storage.
*
* P[i] and A[i] are the interpolation and coarse grid matrices for
* the (i+1)'th subspace. B[i] is an AMG solver for A[i]. r[i] and g[i]
* are temporary vectors. A0_* are the fine grid smoothing parameters.
*
* The default mode is multiplicative, '+' changes the next correction
* to additive, based on residual computed at '('.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_ParCSRSubspacePrec(/* fine space matrix */
hypre_ParCSRMatrix *A0,
/* relaxation parameters */
HYPRE_Int A0_relax_type,
HYPRE_Int A0_relax_times,
HYPRE_Real *A0_l1_norms,
HYPRE_Real A0_relax_weight,
HYPRE_Real A0_omega,
HYPRE_Real A0_max_eig_est,
HYPRE_Real A0_min_eig_est,
HYPRE_Int A0_cheby_order,
HYPRE_Real A0_cheby_fraction,
/* subspace matrices */
hypre_ParCSRMatrix **A,
/* subspace preconditioners */
HYPRE_Solver *B,
/* hypre solver functions for B */
HYPRE_PtrToSolverFcn *HB,
/* subspace interpolations */
hypre_ParCSRMatrix **P,
/* temporary subspace vectors */
hypre_ParVector **r,
hypre_ParVector **g,
/* right-hand side */
hypre_ParVector *x,
/* current approximation */
hypre_ParVector *y,
/* current residual */
hypre_ParVector *r0,
/* temporary vector */
hypre_ParVector *g0,
char *cycle,
/* temporary vector */
hypre_ParVector *z)
{
char *op;
HYPRE_Int use_saved_residual = 0;
for (op = cycle; *op != '\0'; op++)
{
/* do nothing */
if (*op == ')')
continue;
/* compute the residual: r = x - Ay */
else if (*op == '(')
{
hypre_ParVectorCopy(x,r0);
hypre_ParCSRMatrixMatvec(-1.0, A0, y, 1.0, r0);
}
/* switch to additive correction */
else if (*op == '+')
{
use_saved_residual = 1;
continue;
}
/* smooth: y += S (x - Ay) */
else if (*op == '0')
{
hypre_ParCSRRelax(A0, x,
A0_relax_type,
A0_relax_times,
A0_l1_norms,
A0_relax_weight,
A0_omega,
A0_max_eig_est,
A0_min_eig_est,
A0_cheby_order,
A0_cheby_fraction,
y, g0, z);
}
/* subspace correction: y += P B^{-1} P^t r */
else
{
HYPRE_Int i = *op - '1';
if (i < 0)
hypre_error_in_arg(16);
/* skip empty subspaces */
if (!A[i]) continue;
/* compute the residual? */
if (use_saved_residual)
{
use_saved_residual = 0;
hypre_ParCSRMatrixMatvecT(1.0, P[i], r0, 0.0, r[i]);
}
else
{
hypre_ParVectorCopy(x,g0);
hypre_ParCSRMatrixMatvec(-1.0, A0, y, 1.0, g0);
hypre_ParCSRMatrixMatvecT(1.0, P[i], g0, 0.0, r[i]);
}
hypre_ParVectorSetConstantValues(g[i], 0.0);
(*HB[i]) (B[i], (HYPRE_Matrix)A[i],
(HYPRE_Vector)r[i], (HYPRE_Vector)g[i]);
hypre_ParCSRMatrixMatvec(1.0, P[i], g[i], 0.0, g0);
hypre_ParVectorAxpy(1.0, g0, y);
}
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSGetNumIterations
*
* Get the number of AMS iterations.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSGetNumIterations(void *solver,
HYPRE_Int *num_iterations)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
*num_iterations = ams_data -> num_iterations;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSGetFinalRelativeResidualNorm
*
* Get the final relative residual norm in AMS.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSGetFinalRelativeResidualNorm(void *solver,
HYPRE_Real *rel_resid_norm)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
*rel_resid_norm = ams_data -> rel_resid_norm;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSProjectOutGradients
*
* For problems with zero-conductivity regions, project the vector onto the
* compatible subspace: x = (I - G0 (G0^t G0)^{-1} G0^T) x, where G0 is the
* discrete gradient restricted to the interior nodes of the regions with
* zero conductivity. This ensures that x is orthogonal to the gradients in
* the range of G0.
*
* This function is typically called after the solution iteration is complete,
* in order to facilitate the visualization of the computed field. Without it
* the values in the zero-conductivity regions contain kernel components.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSProjectOutGradients(void *solver,
hypre_ParVector *x)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
if (ams_data -> B_G0)
{
hypre_ParCSRMatrixMatvecT(1.0, ams_data -> G0, x, 0.0, ams_data -> r1);
hypre_ParVectorSetConstantValues(ams_data -> g1, 0.0);
hypre_BoomerAMGSolve(ams_data -> B_G0, ams_data -> A_G0, ams_data -> r1, ams_data -> g1);
hypre_ParCSRMatrixMatvec(1.0, ams_data -> G0, ams_data -> g1, 0.0, ams_data -> g0);
hypre_ParVectorAxpy(-1.0, ams_data -> g0, x);
}
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSConstructDiscreteGradient
*
* Construct and return the lowest-order discrete gradient matrix G, based on:
* - a matrix on the egdes (e.g. the stiffness matrix A)
* - a vector on the vertices (e.g. the x coordinates)
* - the array edge_vertex, which lists the global indexes of the
* vertices of the local edges.
*
* We assume that edge_vertex lists the edge vertices consecutively,
* and that the orientation of all edges is consistent. More specificaly:
* If edge_orientation = 1, the edges are already oriented.
* If edge_orientation = 2, the orientation of edge i depends only on the
* sign of edge_vertex[2*i+1] - edge_vertex[2*i].
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSConstructDiscreteGradient(hypre_ParCSRMatrix *A,
hypre_ParVector *x_coord,
HYPRE_BigInt *edge_vertex,
HYPRE_Int edge_orientation,
hypre_ParCSRMatrix **G_ptr)
{
hypre_ParCSRMatrix *G;
HYPRE_Int nedges;
nedges = hypre_ParCSRMatrixNumRows(A);
/* Construct the local part of G based on edge_vertex and the edge
and vertex partitionings from A and x_coord */
{
HYPRE_Int i, *I = hypre_CTAlloc(HYPRE_Int, nedges+1, HYPRE_MEMORY_HOST);
HYPRE_Int part_size;
HYPRE_BigInt *row_starts, *col_starts;
HYPRE_Real *data = hypre_CTAlloc(HYPRE_Real, 2*nedges, HYPRE_MEMORY_HOST);
hypre_CSRMatrix *local = hypre_CSRMatrixCreate (nedges,
hypre_ParVectorGlobalSize(x_coord),
2*nedges);
for (i = 0; i <= nedges; i++)
I[i] = 2*i;
if (edge_orientation == 1)
{
/* Assume that the edges are already oriented */
for (i = 0; i < 2*nedges; i+=2)
{
data[i] = -1.0;
data[i+1] = 1.0;
}
}
else if (edge_orientation == 2)
{
/* Assume that the edge orientation is based on the vertex indexes */
for (i = 0; i < 2*nedges; i+=2)
{
if (edge_vertex[i] < edge_vertex[i+1])
{
data[i] = -1.0;
data[i+1] = 1.0;
}
else
{
data[i] = 1.0;
data[i+1] = -1.0;
}
}
}
else
{
hypre_error_in_arg(4);
}
hypre_CSRMatrixI(local) = I;
hypre_CSRMatrixBigJ(local) = edge_vertex;
hypre_CSRMatrixData(local) = data;
hypre_CSRMatrixRownnz(local) = NULL;
hypre_CSRMatrixOwnsData(local) = 1;
hypre_CSRMatrixNumRownnz(local) = nedges;
/* Copy partitioning from A and x_coord (previously they were re-used) */
#ifdef HYPRE_NO_GLOBAL_PARTITION
part_size = 2;
#else
hypre_MPI_Comm_size(hypre_ParCSRMatrixComm(A), &part_size);
part_size++;
#endif
row_starts = hypre_TAlloc(HYPRE_BigInt, part_size, HYPRE_MEMORY_HOST);
col_starts = hypre_TAlloc(HYPRE_BigInt, part_size, HYPRE_MEMORY_HOST);
for (i = 0; i < part_size; i++)
{
row_starts[i] = hypre_ParCSRMatrixRowStarts(A)[i];
col_starts[i] = hypre_ParVectorPartitioning(x_coord)[i];
}
/* Generate the discrete gradient matrix */
G = hypre_ParCSRMatrixCreate(hypre_ParCSRMatrixComm(A),
hypre_ParCSRMatrixGlobalNumRows(A),
hypre_ParVectorGlobalSize(x_coord),
row_starts, col_starts, 0, 0, 0);
hypre_ParCSRMatrixOwnsRowStarts(G) = 1;
hypre_ParCSRMatrixOwnsColStarts(G) = 1;
hypre_CSRMatrixBigJtoJ(local);
GenerateDiagAndOffd(local, G,
hypre_ParVectorFirstIndex(x_coord),
hypre_ParVectorLastIndex(x_coord));
/* Account for empty rows in G. These may appear when A includes only
the interior (non-Dirichlet b.c.) edges. */
{
hypre_CSRMatrix *G_diag = hypre_ParCSRMatrixDiag(G);
G_diag->num_cols = hypre_VectorSize(hypre_ParVectorLocalVector(x_coord));
}
/* Free the local matrix */
hypre_CSRMatrixDestroy(local);
}
*G_ptr = G;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSFEISetup
*
* Construct an AMS solver object based on the following data:
*
* A - the edge element stiffness matrix
* num_vert - number of vertices (nodes) in the processor
* num_local_vert - number of vertices owned by the processor
* vert_number - global indexes of the vertices in the processor
* vert_coord - coordinates of the vertices in the processor
* num_edges - number of edges owned by the processor
* edge_vertex - the vertices of the edges owned by the processor.
* Vertices are in local numbering (the same as in
* vert_number), and edge orientation is always from
* the first to the second vertex.
*
* Here we distinguish between vertices that belong to elements in the
* current processor, and the subset of these vertices that is owned by
* the processor.
*
* This function is written specifically for input from the FEI and should
* be called before hypre_AMSSetup().
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSFEISetup(void *solver,
hypre_ParCSRMatrix *A,
hypre_ParVector *b,
hypre_ParVector *x,
HYPRE_Int num_vert,
HYPRE_Int num_local_vert,
HYPRE_BigInt *vert_number,
HYPRE_Real *vert_coord,
HYPRE_Int num_edges,
HYPRE_BigInt *edge_vertex)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
HYPRE_Int i, j;
hypre_ParCSRMatrix *G;
hypre_ParVector *x_coord, *y_coord, *z_coord;
HYPRE_Real *x_data, *y_data, *z_data;
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
HYPRE_BigInt *vert_part, num_global_vert;
HYPRE_BigInt vert_start, vert_end;
HYPRE_BigInt big_local_vert = (HYPRE_BigInt) num_local_vert;
/* Find the processor partitioning of the vertices */
#ifdef HYPRE_NO_GLOBAL_PARTITION
vert_part = hypre_TAlloc(HYPRE_BigInt, 2, HYPRE_MEMORY_HOST);
hypre_MPI_Scan(&big_local_vert, &vert_part[1], 1, HYPRE_MPI_BIG_INT, hypre_MPI_SUM, comm);
vert_part[0] = vert_part[1] - big_local_vert;
hypre_MPI_Allreduce(&big_local_vert, &num_global_vert, 1, HYPRE_MPI_BIG_INT, hypre_MPI_SUM, comm);
#else
HYPRE_Int num_procs;
hypre_MPI_Comm_size(comm, &num_procs);
vert_part = hypre_TAlloc(HYPRE_BigInt, num_procs+1, HYPRE_MEMORY_HOST);
hypre_MPI_Allgather(&big_local_vert, 1, HYPRE_MPI_BIG_INT, &vert_part[1], 1, HYPRE_MPI_BIG_INT, comm);
vert_part[0] = 0;
for (i = 0; i < num_procs; i++)
vert_part[i+1] += vert_part[i];
num_global_vert = vert_part[num_procs];
#endif
/* Construct hypre parallel vectors for the vertex coordinates */
x_coord = hypre_ParVectorCreate(comm, num_global_vert, vert_part);
hypre_ParVectorInitialize(x_coord);
hypre_ParVectorOwnsData(x_coord) = 1;
hypre_ParVectorOwnsPartitioning(x_coord) = 0;
x_data = hypre_VectorData(hypre_ParVectorLocalVector(x_coord));
y_coord = hypre_ParVectorCreate(comm, num_global_vert, vert_part);
hypre_ParVectorInitialize(y_coord);
hypre_ParVectorOwnsData(y_coord) = 1;
hypre_ParVectorOwnsPartitioning(y_coord) = 0;
y_data = hypre_VectorData(hypre_ParVectorLocalVector(y_coord));
z_coord = hypre_ParVectorCreate(comm, num_global_vert, vert_part);
hypre_ParVectorInitialize(z_coord);
hypre_ParVectorOwnsData(z_coord) = 1;
hypre_ParVectorOwnsPartitioning(z_coord) = 0;
z_data = hypre_VectorData(hypre_ParVectorLocalVector(z_coord));
vert_start = hypre_ParVectorFirstIndex(x_coord);
vert_end = hypre_ParVectorLastIndex(x_coord);
/* Save coordinates of locally owned vertices */
for (i = 0; i < num_vert; i++)
{
if (vert_number[i] >= vert_start && vert_number[i] <= vert_end)
{
j = (HYPRE_Int)(vert_number[i] - vert_start);
x_data[j] = vert_coord[3*i];
y_data[j] = vert_coord[3*i+1];
z_data[j] = vert_coord[3*i+2];
}
}
/* Change vertex numbers from local to global */
for (i = 0; i < 2*num_edges; i++)
edge_vertex[i] = vert_number[edge_vertex[i]];
/* Construct the local part of G based on edge_vertex */
{
/* HYPRE_Int num_edges = hypre_ParCSRMatrixNumRows(A); */
HYPRE_Int *I = hypre_CTAlloc(HYPRE_Int, num_edges+1, HYPRE_MEMORY_HOST);
HYPRE_Real *data = hypre_CTAlloc(HYPRE_Real, 2*num_edges, HYPRE_MEMORY_HOST);
hypre_CSRMatrix *local = hypre_CSRMatrixCreate (num_edges,
num_global_vert,
2*num_edges);
for (i = 0; i <= num_edges; i++)
I[i] = 2*i;
/* Assume that the edge orientation is based on the vertex indexes */
for (i = 0; i < 2*num_edges; i+=2)
{
data[i] = 1.0;
data[i+1] = -1.0;
}
hypre_CSRMatrixI(local) = I;
hypre_CSRMatrixBigJ(local) = edge_vertex;
hypre_CSRMatrixData(local) = data;
hypre_CSRMatrixRownnz(local) = NULL;
hypre_CSRMatrixOwnsData(local) = 1;
hypre_CSRMatrixNumRownnz(local) = num_edges;
G = hypre_ParCSRMatrixCreate(comm,
hypre_ParCSRMatrixGlobalNumRows(A),
num_global_vert,
hypre_ParCSRMatrixRowStarts(A),
vert_part,
0, 0, 0);
hypre_ParCSRMatrixOwnsRowStarts(G) = 0;
hypre_ParCSRMatrixOwnsColStarts(G) = 1;
hypre_CSRMatrixBigJtoJ(local);
GenerateDiagAndOffd(local, G, vert_start, vert_end);
//hypre_CSRMatrixJ(local) = NULL;
hypre_CSRMatrixDestroy(local);
}
ams_data -> G = G;
ams_data -> x = x_coord;
ams_data -> y = y_coord;
ams_data -> z = z_coord;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_AMSFEIDestroy
*
* Free the additional memory allocated in hypre_AMSFEISetup().
*
* This function is written specifically for input from the FEI and should
* be called before hypre_AMSDestroy().
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_AMSFEIDestroy(void *solver)
{
hypre_AMSData *ams_data = (hypre_AMSData *) solver;
if (ams_data -> G)
hypre_ParCSRMatrixDestroy(ams_data -> G);
if (ams_data -> x)
hypre_ParVectorDestroy(ams_data -> x);
if (ams_data -> y)
hypre_ParVectorDestroy(ams_data -> y);
if (ams_data -> z)
hypre_ParVectorDestroy(ams_data -> z);
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_ParCSRComputeL1Norms Threads
*
* Compute the l1 norms of the rows of a given matrix, depending on
* the option parameter:
*
* option 1 = Compute the l1 norm of the rows
* option 2 = Compute the l1 norm of the (processor) off-diagonal
* part of the rows plus the diagonal of A
* option 3 = Compute the l2 norm^2 of the rows
* option 4 = Truncated version of option 2 based on Remark 6.2 in "Multigrid
* Smoothers for Ultra-Parallel Computing"
*
* The above computations are done in a CF manner, whenever the provided
* cf_marker is not NULL.
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_ParCSRComputeL1NormsThreads(hypre_ParCSRMatrix *A,
HYPRE_Int option,
HYPRE_Int num_threads,
HYPRE_Int *cf_marker,
HYPRE_Real **l1_norm_ptr)
{
HYPRE_Int i, j, k;
HYPRE_Int num_rows = hypre_ParCSRMatrixNumRows(A);
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Int *A_diag_I = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_J = hypre_CSRMatrixJ(A_diag);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *A_offd_I = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_J = hypre_CSRMatrixJ(A_offd);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd);
HYPRE_Real diag;
HYPRE_Real *l1_norm = hypre_TAlloc(HYPRE_Real, num_rows, hypre_ParCSRMatrixMemoryLocation(A));
HYPRE_Int ii, ns, ne, rest, size;
HYPRE_Int *cf_marker_offd = NULL;
HYPRE_Int cf_diag;
/* collect the cf marker data from other procs */
if (cf_marker != NULL)
{
HYPRE_Int index;
HYPRE_Int num_sends;
HYPRE_Int start;
HYPRE_Int *int_buf_data = NULL;
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle;
if (num_cols_offd)
cf_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST);
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
if (hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends))
int_buf_data = hypre_CTAlloc(HYPRE_Int,
hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST);
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
{
int_buf_data[index++] = cf_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
}
comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data,
cf_marker_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST);
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,ii,j,k,ns,ne,rest,size,diag,cf_diag) HYPRE_SMP_SCHEDULE
#endif
for (k = 0; k < num_threads; k++)
{
size = num_rows/num_threads;
rest = num_rows - size*num_threads;
if (k < rest)
{
ns = k*size+k;
ne = (k+1)*size+k+1;
}
else
{
ns = k*size+rest;
ne = (k+1)*size+rest;
}
if (option == 1)
{
for (i = ns; i < ne; i++)
{
l1_norm[i] = 0.0;
if (cf_marker == NULL)
{
/* Add the l1 norm of the diag part of the ith row */
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
l1_norm[i] += fabs(A_diag_data[j]);
/* Add the l1 norm of the offd part of the ith row */
if (num_cols_offd)
{
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
l1_norm[i] += fabs(A_offd_data[j]);
}
}
else
{
cf_diag = cf_marker[i];
/* Add the CF l1 norm of the diag part of the ith row */
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
if (cf_diag == cf_marker[A_diag_J[j]])
l1_norm[i] += fabs(A_diag_data[j]);
/* Add the CF l1 norm of the offd part of the ith row */
if (num_cols_offd)
{
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
if (cf_diag == cf_marker_offd[A_offd_J[j]])
l1_norm[i] += fabs(A_offd_data[j]);
}
}
}
}
else if (option == 2)
{
for (i = ns; i < ne; i++)
{
l1_norm[i] = 0.0;
if (cf_marker == NULL)
{
/* Add the diagonal and the local off-thread part of the ith row */
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
{
ii = A_diag_J[j];
if (ii == i || ii < ns || ii >= ne)
l1_norm[i] += fabs(A_diag_data[j]);
}
/* Add the l1 norm of the offd part of the ith row */
if (num_cols_offd)
{
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
l1_norm[i] += fabs(A_offd_data[j]);
}
}
else
{
cf_diag = cf_marker[i];
/* Add the diagonal and the local off-thread part of the ith row */
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
{
ii = A_diag_J[j];
if ((ii == i || ii < ns || ii >= ne) &&
(cf_diag == cf_marker[A_diag_J[j]]))
l1_norm[i] += fabs(A_diag_data[j]);
}
/* Add the CF l1 norm of the offd part of the ith row */
if (num_cols_offd)
{
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
if (cf_diag == cf_marker_offd[A_offd_J[j]])
l1_norm[i] += fabs(A_offd_data[j]);
}
}
}
}
else if (option == 3)
{
for (i = ns; i < ne; i++)
{
l1_norm[i] = 0.0;
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
l1_norm[i] += A_diag_data[j] * A_diag_data[j];
if (num_cols_offd)
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
l1_norm[i] += A_offd_data[j] * A_offd_data[j];
}
}
else if (option == 4)
{
for (i = ns; i < ne; i++)
{
l1_norm[i] = 0.0;
if (cf_marker == NULL)
{
/* Add the diagonal and the local off-thread part of the ith row */
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
{
ii = A_diag_J[j];
if (ii == i || ii < ns || ii >= ne)
{
if (ii == i)
{
diag = fabs(A_diag_data[j]);
l1_norm[i] += fabs(A_diag_data[j]);
}
else
l1_norm[i] += 0.5*fabs(A_diag_data[j]);
}
}
/* Add the l1 norm of the offd part of the ith row */
if (num_cols_offd)
{
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
l1_norm[i] += 0.5*fabs(A_offd_data[j]);
}
}
else
{
cf_diag = cf_marker[i];
/* Add the diagonal and the local off-thread part of the ith row */
for (j = A_diag_I[i]; j < A_diag_I[i+1]; j++)
{
ii = A_diag_J[j];
if ((ii == i || ii < ns || ii >= ne) &&
(cf_diag == cf_marker[A_diag_J[j]]))
{
if (ii == i)
{
diag = fabs(A_diag_data[j]);
l1_norm[i] += fabs(A_diag_data[j]);
}
else
l1_norm[i] += 0.5*fabs(A_diag_data[j]);
}
}
/* Add the CF l1 norm of the offd part of the ith row */
if (num_cols_offd)
{
for (j = A_offd_I[i]; j < A_offd_I[i+1]; j++)
if (cf_diag == cf_marker_offd[A_offd_J[j]])
l1_norm[i] += 0.5*fabs(A_offd_data[j]);
}
}
/* Truncate according to Remark 6.2 */
if (l1_norm[i] <= 4.0/3.0*diag)
l1_norm[i] = diag;
}
}
else if (option == 5) /*stores diagonal of A for Jacobi using matvec, rlx 7 */
{
/* Set the diag element */
for (i = ns; i < ne; i++)
{
l1_norm[i] = A_diag_data[A_diag_I[i]];
if (l1_norm[i] == 0) l1_norm[i] = 1.0;
}
}
if (option < 5)
{
/* Handle negative definite matrices */
for (i = ns; i < ne; i++)
if (A_diag_data[A_diag_I[i]] < 0)
l1_norm[i] = -l1_norm[i];
for (i = ns; i < ne; i++)
/* if (fabs(l1_norm[i]) < DBL_EPSILON) */
if (fabs(l1_norm[i]) == 0.0)
{
hypre_error_in_arg(1);
break;
}
}
}
hypre_TFree(cf_marker_offd, HYPRE_MEMORY_HOST);
*l1_norm_ptr = l1_norm;
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* hypre_ParCSRRelaxThreads
* 1 = l1-scaled Jacobi
* 2 = l1-scaled block Gauss-Seidel/SSOR
*--------------------------------------------------------------------------*/
HYPRE_Int hypre_ParCSRRelaxThreads(hypre_ParCSRMatrix *A,
hypre_ParVector *f,
HYPRE_Int relax_type,
HYPRE_Int relax_times,
HYPRE_Real *l1_norms,
HYPRE_Real relax_weight,
HYPRE_Real omega,
hypre_ParVector *u,
hypre_ParVector *Vtemp,
hypre_ParVector *z)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle;
HYPRE_Int n = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd);
hypre_Vector *u_local = hypre_ParVectorLocalVector(u);
HYPRE_Real *u_data = hypre_VectorData(u_local);
hypre_Vector *f_local = hypre_ParVectorLocalVector(f);
HYPRE_Real *f_data = hypre_VectorData(f_local);
hypre_Vector *Vtemp_local = hypre_ParVectorLocalVector(Vtemp);
HYPRE_Real *Vtemp_data = hypre_VectorData(Vtemp_local);
HYPRE_Real *Vext_data;
HYPRE_Real *v_buf_data;
HYPRE_Real *tmp_data;
HYPRE_Int i, j;
HYPRE_Int ii, jj;
HYPRE_Int ns, ne, size, rest;
HYPRE_Int relax_error = 0;
HYPRE_Int num_sends;
HYPRE_Int index, start;
HYPRE_Int num_procs, num_threads, my_id;
HYPRE_Real zero = 0.0;
HYPRE_Real res, res2;
hypre_MPI_Comm_size(comm,&num_procs);
hypre_MPI_Comm_rank(comm,&my_id);
num_threads = hypre_NumThreads();
/* only allow jacobi and GS */
if (relax_type > 2)
relax_type = 2;
/*-----------------------------------------------------------------
* Copy current approximation into temporary vector.
*-----------------------------------------------------------------*/
if (num_procs > 1)
{
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
v_buf_data = hypre_CTAlloc(HYPRE_Real,
hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST);
Vext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST);
if (num_cols_offd)
{
A_offd_j = hypre_CSRMatrixJ(A_offd);
A_offd_data = hypre_CSRMatrixData(A_offd);
}
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++)
v_buf_data[index++]
= u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, v_buf_data,
Vext_data);
/*-----------------------------------------------------------------
* Copy current approximation into temporary vector.
*-----------------------------------------------------------------*/
hypre_ParCSRCommHandleDestroy(comm_handle);
comm_handle = NULL;
}
if (relax_type == 1) /* Jacobi */
{
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n; i++)
{
Vtemp_data[i] = u_data[i];
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n; i++)
{
/*-----------------------------------------------------------
* If diagonal is nonzero, relax point i; otherwise, skip it.
*-----------------------------------------------------------*/
if (A_diag_data[A_diag_i[i]] != zero)
{
res = f_data[i];
for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++)
{
ii = A_diag_j[jj];
res -= A_diag_data[jj] * Vtemp_data[ii];
}
for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++)
{
ii = A_offd_j[jj];
res -= A_offd_data[jj] * Vext_data[ii];
}
u_data[i] += (relax_weight*res)/l1_norms[i];
}
}
}
else if (relax_type == 2) /* GS */
{
if (relax_weight == 1 && omega == 1)
{
tmp_data = hypre_CTAlloc(HYPRE_Real, n, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n; i++)
tmp_data[i] = u_data[i];
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
size = n/num_threads;
rest = n - size*num_threads;
if (j < rest)
{
ns = j*size+j;
ne = (j+1)*size+j+1;
}
else
{
ns = j*size+rest;
ne = (j+1)*size+rest;
}
for (i = ns; i < ne; i++) /* interior points first */
{
/*-----------------------------------------------------------
* If diagonal is nonzero, relax point i; otherwise, skip it.
*-----------------------------------------------------------*/
if (A_diag_data[A_diag_i[i]] != zero)
{
res = f_data[i];
for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++)
{
ii = A_diag_j[jj];
if (ii >= ns && ii < ne)
{
res -= A_diag_data[jj] * u_data[ii];
}
else
res -= A_diag_data[jj] * tmp_data[ii];
}
for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++)
{
ii = A_offd_j[jj];
res -= A_offd_data[jj] * Vext_data[ii];
}
u_data[i] += res / l1_norms[i];
}
}
for (i = ne-1; i > ns-1; i--) /* interior points first */
{
/*-----------------------------------------------------------
* If diagonal is nonzero, relax point i; otherwise, skip it.
*-----------------------------------------------------------*/
if (A_diag_data[A_diag_i[i]] != zero)
{
res = f_data[i];
for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++)
{
ii = A_diag_j[jj];
if (ii >= ns && ii < ne)
{
res -= A_diag_data[jj] * u_data[ii];
}
else
res -= A_diag_data[jj] * tmp_data[ii];
}
for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++)
{
ii = A_offd_j[jj];
res -= A_offd_data[jj] * Vext_data[ii];
}
u_data[i] += res / l1_norms[i];
}
}
}
hypre_TFree(tmp_data, HYPRE_MEMORY_HOST);
}
else
{
HYPRE_Real c1 = omega*relax_weight;
HYPRE_Real c2 = omega*(1.0-relax_weight);
tmp_data = hypre_CTAlloc(HYPRE_Real, n, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n; i++)
{
tmp_data[i] = u_data[i];
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,ii,j,jj,ns,ne,res,rest,size) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
size = n/num_threads;
rest = n - size*num_threads;
if (j < rest)
{
ns = j*size+j;
ne = (j+1)*size+j+1;
}
else
{
ns = j*size+rest;
ne = (j+1)*size+rest;
}
for (i = ns; i < ne; i++) /* interior points first */
{
/*-----------------------------------------------------------
* If diagonal is nonzero, relax point i; otherwise, skip it.
*-----------------------------------------------------------*/
if (A_diag_data[A_diag_i[i]] != zero)
{
res2 = 0.0;
res = f_data[i];
Vtemp_data[i] = u_data[i];
for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++)
{
ii = A_diag_j[jj];
if (ii >= ns && ii < ne)
{
res -= A_diag_data[jj] * u_data[ii];
if (ii < i)
res2 += A_diag_data[jj] * (Vtemp_data[ii] - u_data[ii]);
}
else
res -= A_diag_data[jj] * tmp_data[ii];
}
for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++)
{
ii = A_offd_j[jj];
res -= A_offd_data[jj] * Vext_data[ii];
}
u_data[i] += (c1*res + c2*res2) / l1_norms[i];
}
}
for (i = ne-1; i > ns-1; i--) /* interior points first */
{
/*-----------------------------------------------------------
* If diagonal is nonzero, relax point i; otherwise, skip it.
*-----------------------------------------------------------*/
if (A_diag_data[A_diag_i[i]] != zero)
{
res2 = 0.0;
res = f_data[i];
for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++)
{
ii = A_diag_j[jj];
if (ii >= ns && ii < ne)
{
res -= A_diag_data[jj] * u_data[ii];
if (ii > i)
res2 += A_diag_data[jj] * (Vtemp_data[ii] - u_data[ii]);
}
else
res -= A_diag_data[jj] * tmp_data[ii];
}
for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++)
{
ii = A_offd_j[jj];
res -= A_offd_data[jj] * Vext_data[ii];
}
u_data[i] += (c1*res + c2*res2) / l1_norms[i];
}
}
}
hypre_TFree(tmp_data, HYPRE_MEMORY_HOST);
}
} /* end of Jacobi or G.S. */
if (num_procs > 1)
{
hypre_TFree(Vext_data, HYPRE_MEMORY_HOST);
hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST);
}
return(relax_error);
}
|
GB_unaryop__abs_int8_fp32.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__abs_int8_fp32
// op(A') function: GB_tran__abs_int8_fp32
// C type: int8_t
// A type: float
// cast: int8_t cij ; GB_CAST_SIGNED(cij,aij,8)
// unaryop: cij = GB_IABS (aij)
#define GB_ATYPE \
float
#define GB_CTYPE \
int8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IABS (x) ;
// casting
#define GB_CASTING(z, x) \
int8_t z ; GB_CAST_SIGNED(z,x,8) ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ABS || GxB_NO_INT8 || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_int8_fp32
(
int8_t *restrict Cx,
const float *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__abs_int8_fp32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_binop__islt_int8.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__islt_int8)
// A.*B function (eWiseMult): GB (_AemultB_08__islt_int8)
// A.*B function (eWiseMult): GB (_AemultB_02__islt_int8)
// A.*B function (eWiseMult): GB (_AemultB_04__islt_int8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__islt_int8)
// A*D function (colscale): GB (_AxD__islt_int8)
// D*A function (rowscale): GB (_DxB__islt_int8)
// C+=B function (dense accum): GB (_Cdense_accumB__islt_int8)
// C+=b function (dense accum): GB (_Cdense_accumb__islt_int8)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__islt_int8)
// C=scalar+B GB (_bind1st__islt_int8)
// C=scalar+B' GB (_bind1st_tran__islt_int8)
// C=A+scalar GB (_bind2nd__islt_int8)
// C=A'+scalar GB (_bind2nd_tran__islt_int8)
// C type: int8_t
// A type: int8_t
// A pattern? 0
// B type: int8_t
// B pattern? 0
// BinaryOp: cij = (aij < bij)
#define GB_ATYPE \
int8_t
#define GB_BTYPE \
int8_t
#define GB_CTYPE \
int8_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) \
int8_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) \
int8_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) \
int8_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x < y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ISLT || GxB_NO_INT8 || GxB_NO_ISLT_INT8)
//------------------------------------------------------------------------------
// 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__islt_int8)
(
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__islt_int8)
(
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__islt_int8)
(
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 int8_t
int8_t bwork = (*((int8_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__islt_int8)
(
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
int8_t *restrict Cx = (int8_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__islt_int8)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int8_t *restrict Cx = (int8_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__islt_int8)
(
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) ;
int8_t alpha_scalar ;
int8_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int8_t *) alpha_scalar_in)) ;
beta_scalar = (*((int8_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__islt_int8)
(
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__islt_int8)
(
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__islt_int8)
(
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__islt_int8)
(
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__islt_int8)
(
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
int8_t *Cx = (int8_t *) Cx_output ;
int8_t x = (*((int8_t *) x_input)) ;
int8_t *Bx = (int8_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 ;
int8_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__islt_int8)
(
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 ;
int8_t *Cx = (int8_t *) Cx_output ;
int8_t *Ax = (int8_t *) Ax_input ;
int8_t y = (*((int8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int8_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) \
{ \
int8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x < aij) ; \
}
GrB_Info GB (_bind1st_tran__islt_int8)
(
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 \
int8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int8_t x = (*((const int8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int8_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) \
{ \
int8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij < y) ; \
}
GrB_Info GB (_bind2nd_tran__islt_int8)
(
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
int8_t y = (*((const int8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
pr29965-1.c | /* PR middle-end/29965 */
/* Test that OpenMP construct bodies which never return don't cause ICEs. */
/* { dg-do compile } */
/* { dg-options "-O2 -fopenmp" } */
extern void baz (void) __attribute__ ((noreturn));
static inline void
foo (void)
{
#pragma omp parallel
for (;;)
;
}
static inline void
bar (void)
{
#pragma omp parallel
baz ();
}
void
foo1 (void)
{
foo ();
}
void
foo2 (void)
{
foo ();
}
void
bar1 (void)
{
bar ();
}
void
bar2 (void)
{
bar ();
}
|
simd-function_0.c | /* { dg-lto-do link } */
/* { dg-require-effective-target vect_simd_clones } */
/* { dg-require-effective-target avx2 } */
/* { dg-lto-options { { -fopenmp-simd -O3 -ffast-math -mavx2 -flto -flto-partition=max } } } */
#define SIZE 4096
float x[SIZE];
#pragma omp declare simd
float
__attribute__ ((noinline))
my_mul (float x, float y) {
return x * y;
}
__attribute__ ((noinline))
int foo ()
{
int i = 0;
#pragma omp simd safelen (16)
for (i = 0; i < SIZE; i++)
x[i] = my_mul ((float)i, 9932.3323);
return (int)x[0];
}
int main ()
{
int i = 0;
for (i = 0; i < SIZE; i++)
x[i] = my_mul ((float) i, 9932.3323);
foo ();
return (int)x[0];
}
|
sparse_msg_interp.c | /*BHEADER**********************************************************************
* Copyright (c) 2008, Lawrence Livermore National Security, LLC.
* Produced at the Lawrence Livermore National Laboratory.
* This file is part of HYPRE. See file COPYRIGHT for details.
*
* HYPRE is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License (as published by the Free
* Software Foundation) version 2.1 dated February 1999.
*
* $Revision$
***********************************************************************EHEADER*/
#include "_hypre_struct_ls.h"
/*--------------------------------------------------------------------------
* hypre_SparseMSGInterpData data structure
*--------------------------------------------------------------------------*/
typedef struct
{
hypre_StructMatrix *P;
hypre_ComputePkg *compute_pkg;
hypre_Index cindex;
hypre_Index findex;
hypre_Index stride;
hypre_Index strideP;
HYPRE_Int time_index;
} hypre_SparseMSGInterpData;
/*--------------------------------------------------------------------------
* hypre_SparseMSGInterpCreate
*--------------------------------------------------------------------------*/
void *
hypre_SparseMSGInterpCreate( )
{
hypre_SparseMSGInterpData *interp_data;
interp_data = hypre_CTAlloc(hypre_SparseMSGInterpData, 1);
(interp_data -> time_index) = hypre_InitializeTiming("SparseMSGInterp");
return (void *) interp_data;
}
/*--------------------------------------------------------------------------
* hypre_SparseMSGInterpSetup
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_SparseMSGInterpSetup( void *interp_vdata,
hypre_StructMatrix *P,
hypre_StructVector *xc,
hypre_StructVector *e,
hypre_Index cindex,
hypre_Index findex,
hypre_Index stride,
hypre_Index strideP )
{
hypre_SparseMSGInterpData *interp_data = (hypre_SparseMSGInterpData *)interp_vdata;
hypre_StructGrid *grid;
hypre_StructStencil *stencil;
hypre_ComputeInfo *compute_info;
hypre_ComputePkg *compute_pkg;
HYPRE_Int ierr = 0;
/*----------------------------------------------------------
* Set up the compute package
*----------------------------------------------------------*/
grid = hypre_StructVectorGrid(e);
stencil = hypre_StructMatrixStencil(P);
hypre_CreateComputeInfo(grid, stencil, &compute_info);
hypre_ComputeInfoProjectSend(compute_info, cindex, stride);
hypre_ComputeInfoProjectRecv(compute_info, cindex, stride);
hypre_ComputeInfoProjectComp(compute_info, findex, stride);
hypre_ComputePkgCreate(compute_info, hypre_StructVectorDataSpace(e), 1,
grid, &compute_pkg);
/*----------------------------------------------------------
* Set up the interp data structure
*----------------------------------------------------------*/
(interp_data -> P) = hypre_StructMatrixRef(P);
(interp_data -> compute_pkg) = compute_pkg;
hypre_CopyIndex(cindex, (interp_data -> cindex));
hypre_CopyIndex(findex, (interp_data -> findex));
hypre_CopyIndex(stride, (interp_data -> stride));
hypre_CopyIndex(strideP, (interp_data -> strideP));
return ierr;
}
/*--------------------------------------------------------------------------
* hypre_SparseMSGInterp:
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_SparseMSGInterp( void *interp_vdata,
hypre_StructMatrix *P,
hypre_StructVector *xc,
hypre_StructVector *e )
{
HYPRE_Int ierr = 0;
hypre_SparseMSGInterpData *interp_data = (hypre_SparseMSGInterpData *)interp_vdata;
hypre_ComputePkg *compute_pkg;
hypre_IndexRef cindex;
hypre_IndexRef findex;
hypre_IndexRef stride;
hypre_IndexRef strideP;
hypre_StructGrid *fgrid;
HYPRE_Int *fgrid_ids;
hypre_StructGrid *cgrid;
hypre_BoxArray *cgrid_boxes;
HYPRE_Int *cgrid_ids;
hypre_CommHandle *comm_handle;
hypre_BoxArrayArray *compute_box_aa;
hypre_BoxArray *compute_box_a;
hypre_Box *compute_box;
hypre_Box *P_dbox;
hypre_Box *xc_dbox;
hypre_Box *e_dbox;
HYPRE_Int Pi;
HYPRE_Int xci;
HYPRE_Int ei;
HYPRE_Real *Pp0, *Pp1;
HYPRE_Real *xcp;
HYPRE_Real *ep, *ep0, *ep1;
hypre_Index loop_size;
hypre_Index start;
hypre_Index startc;
hypre_Index startP;
hypre_Index stridec;
hypre_StructStencil *stencil;
hypre_Index *stencil_shape;
HYPRE_Int compute_i, fi, ci, j;
/*-----------------------------------------------------------------------
* Initialize some things
*-----------------------------------------------------------------------*/
hypre_BeginTiming(interp_data -> time_index);
compute_pkg = (interp_data -> compute_pkg);
cindex = (interp_data -> cindex);
findex = (interp_data -> findex);
stride = (interp_data -> stride);
strideP = (interp_data -> strideP);
stencil = hypre_StructMatrixStencil(P);
stencil_shape = hypre_StructStencilShape(stencil);
hypre_SetIndex3(stridec, 1, 1, 1);
/*-----------------------------------------------------------------------
* Compute e at coarse points (injection)
*-----------------------------------------------------------------------*/
fgrid = hypre_StructVectorGrid(e);
fgrid_ids = hypre_StructGridIDs(fgrid);
cgrid = hypre_StructVectorGrid(xc);
cgrid_boxes = hypre_StructGridBoxes(cgrid);
cgrid_ids = hypre_StructGridIDs(cgrid);
fi = 0;
hypre_ForBoxI(ci, cgrid_boxes)
{
while (fgrid_ids[fi] != cgrid_ids[ci])
{
fi++;
}
compute_box = hypre_BoxArrayBox(cgrid_boxes, ci);
hypre_CopyIndex(hypre_BoxIMin(compute_box), startc);
hypre_StructMapCoarseToFine(startc, cindex, stride, start);
e_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(e), fi);
xc_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(xc), ci);
ep = hypre_StructVectorBoxData(e, fi);
xcp = hypre_StructVectorBoxData(xc, ci);
hypre_BoxGetSize(compute_box, loop_size);
hypre_BoxLoop2Begin(hypre_StructMatrixNDim(P), loop_size,
e_dbox, start, stride, ei,
xc_dbox, startc, stridec, xci);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(HYPRE_BOX_PRIVATE,ei,xci) HYPRE_SMP_SCHEDULE
#endif
hypre_BoxLoop2For(ei, xci)
{
ep[ei] = xcp[xci];
}
hypre_BoxLoop2End(ei, xci);
}
/*-----------------------------------------------------------------------
* Compute e at fine points
*-----------------------------------------------------------------------*/
for (compute_i = 0; compute_i < 2; compute_i++)
{
switch(compute_i)
{
case 0:
{
ep = hypre_StructVectorData(e);
hypre_InitializeIndtComputations(compute_pkg, ep, &comm_handle);
compute_box_aa = hypre_ComputePkgIndtBoxes(compute_pkg);
}
break;
case 1:
{
hypre_FinalizeIndtComputations(comm_handle);
compute_box_aa = hypre_ComputePkgDeptBoxes(compute_pkg);
}
break;
}
hypre_ForBoxArrayI(fi, compute_box_aa)
{
compute_box_a = hypre_BoxArrayArrayBoxArray(compute_box_aa, fi);
P_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(P), fi);
e_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(e), fi);
Pp0 = hypre_StructMatrixBoxData(P, fi, 0);
Pp1 = hypre_StructMatrixBoxData(P, fi, 1);
ep = hypre_StructVectorBoxData(e, fi);
ep0 = ep + hypre_BoxOffsetDistance(e_dbox, stencil_shape[0]);
ep1 = ep + hypre_BoxOffsetDistance(e_dbox, stencil_shape[1]);
hypre_ForBoxI(j, compute_box_a)
{
compute_box = hypre_BoxArrayBox(compute_box_a, j);
hypre_CopyIndex(hypre_BoxIMin(compute_box), start);
hypre_StructMapFineToCoarse(start, findex, stride, startc);
hypre_StructMapCoarseToFine(startc, cindex, strideP, startP);
hypre_BoxGetStrideSize(compute_box, stride, loop_size);
hypre_BoxLoop2Begin(hypre_StructMatrixNDim(P), loop_size,
P_dbox, startP, strideP, Pi,
e_dbox, start, stride, ei);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(HYPRE_BOX_PRIVATE,Pi,ei) HYPRE_SMP_SCHEDULE
#endif
hypre_BoxLoop2For(Pi, ei)
{
ep[ei] = (Pp0[Pi] * ep0[ei] +
Pp1[Pi] * ep1[ei]);
}
hypre_BoxLoop2End(Pi, ei);
}
}
}
/*-----------------------------------------------------------------------
* Return
*-----------------------------------------------------------------------*/
hypre_IncFLOPCount(3*hypre_StructVectorGlobalSize(xc));
hypre_EndTiming(interp_data -> time_index);
return ierr;
}
/*--------------------------------------------------------------------------
* hypre_SparseMSGInterpDestroy
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_SparseMSGInterpDestroy( void *interp_vdata )
{
HYPRE_Int ierr = 0;
hypre_SparseMSGInterpData *interp_data = (hypre_SparseMSGInterpData *)interp_vdata;
if (interp_data)
{
hypre_StructMatrixDestroy(interp_data -> P);
hypre_ComputePkgDestroy(interp_data -> compute_pkg);
hypre_FinalizeTiming(interp_data -> time_index);
hypre_TFree(interp_data);
}
return ierr;
}
|
bincrs_func.c | #define _XOPEN_SOURCE 500
#include <stdlib.h>
#include <stdio.h>
#include "ghost/util.h"
#include "ghost/bincrs.h"
#include "ghost/machine.h"
#include "ghost/locality.h"
static inline uint32_t bswap_32(uint32_t val)
{
return ((val & (uint32_t)0x000000ffUL) << 24)
| ((val & (uint32_t)0x0000ff00UL) << 8)
| ((val & (uint32_t)0x00ff0000UL) >> 8)
| ((val & (uint32_t)0xff000000UL) >> 24);
}
static inline uint64_t bswap_64(uint64_t val)
{
return ((val & (uint64_t)0x00000000000000ffULL) << 56)
| ((val & (uint64_t)0x000000000000ff00ULL) << 40)
| ((val & (uint64_t)0x0000000000ff0000ULL) << 24)
| ((val & (uint64_t)0x00000000ff000000ULL) << 8)
| ((val & (uint64_t)0x000000ff00000000ULL) >> 8)
| ((val & (uint64_t)0x0000ff0000000000ULL) >> 24)
| ((val & (uint64_t)0x00ff000000000000ULL) >> 40)
| ((val & (uint64_t)0xff00000000000000ULL) >> 56);
}
#define SWAPREQ(header) (header.endianess == GHOST_BINCRS_LITTLE_ENDIAN)?ghost_machine_bigendian()?1:0:ghost_machine_bigendian()?0:1
int ghost_sparsemat_rowfunc_bincrs(ghost_gidx row, ghost_lidx *rowlen, ghost_gidx *col, void *val, void *arg)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_INITIALIZATION|GHOST_FUNCTYPE_IO);
static ghost_gidx *colInd = NULL, *globalRowPtr = NULL, *rowPtr = NULL;
static char *values = NULL;
static size_t dtsize = 0;
static ghost_gidx firstrow = 0;
static ghost_lidx nrows = 0;
if (row == GHOST_SPARSEMAT_ROWFUNC_BINCRS_ROW_GETDIM) {
ghost_bincrs_header_t header;
ghost_sparsemat_rowfunc_file_initargs args =
*(ghost_sparsemat_rowfunc_file_initargs *)arg;
char *filename = args.filename;
ghost_bincrs_header_read(&header,filename);
col[0] = header.nrows;
col[1] = header.ncols;
if(rowlen) *rowlen = header.datatype;
} else if (row == GHOST_SPARSEMAT_ROWFUNC_INIT) {
ghost_sparsemat_rowfunc_file_initargs args =
*(ghost_sparsemat_rowfunc_file_initargs *)arg;
char *filename = args.filename;
ghost_datatype matdt = args.dt;
ghost_datatype_size(&dtsize,matdt);
ghost_bincrs_header_t header;
ghost_bincrs_header_read(&header,filename);
FILE *f;
ghost_gidx i;
size_t ret;
if ((f = fopen64(filename,"r")) == NULL) {
GHOST_ERROR_LOG("fopen with %s failed!",filename);
return 1;
}
if ((ghost_datatype)(header.datatype) != matdt) {
GHOST_ERROR_LOG("Value casting not implemented! Adjust your sparsemat datatype to match the file!");
return 1;
}
if (header.symmetry != GHOST_BINCRS_SYMM_GENERAL) {
GHOST_ERROR_LOG("Only general matrices supported at the moment!");
return 1;
}
if (fseeko(f,GHOST_BINCRS_SIZE_HEADER,SEEK_SET)) {
GHOST_ERROR_LOG("Seek failed");
return GHOST_ERR_IO;
}
int me;
ghost_sparsemat *mat = args.mat;
ghost_rank(&me,mat->context->mpicomm);
firstrow = mat->context->row_map->goffs[me];
nrows = mat->context->row_map->ldim[me];
ghost_malloc((void **)&rowPtr,(nrows + 1) * sizeof(ghost_gidx));
if (fseeko(f,firstrow*GHOST_BINCRS_SIZE_RPT_EL,SEEK_CUR)) {
GHOST_ERROR_LOG("Seek failed");
return GHOST_ERR_IO;
}
if ((ret = fread(rowPtr, GHOST_BINCRS_SIZE_RPT_EL, nrows+1,f)) != (size_t)(nrows+1)){
GHOST_ERROR_LOG("fread failed: %s (%zu)",strerror(errno),ret);
return GHOST_ERR_IO;
}
ghost_lidx nnz = (ghost_lidx)(rowPtr[nrows]-rowPtr[0]);
ghost_malloc((void **)&colInd,nnz * sizeof(ghost_gidx));
ghost_malloc((void **)&values,nnz * dtsize);
#pragma omp parallel for
for(i=0; i < nrows; ++i){
values[rowPtr[i]-rowPtr[0]] = 0;
colInd[rowPtr[i]-rowPtr[0]] = 0;
}
if (fseeko(f,GHOST_BINCRS_SIZE_HEADER+(header.nrows+1)*GHOST_BINCRS_SIZE_RPT_EL+rowPtr[0]*GHOST_BINCRS_SIZE_COL_EL,SEEK_SET)) {
GHOST_ERROR_LOG("Seek failed");
return GHOST_ERR_IO;
}
if ((ret = fread(colInd, GHOST_BINCRS_SIZE_COL_EL, nnz,f)) != (size_t)(nnz)){
GHOST_ERROR_LOG("fread failed: %s (%zu)",strerror(errno),ret);
return GHOST_ERR_IO;
}
if (fseeko(f,GHOST_BINCRS_SIZE_HEADER+(header.nrows+1)*GHOST_BINCRS_SIZE_RPT_EL+header.nnz*GHOST_BINCRS_SIZE_COL_EL+rowPtr[0]*dtsize,SEEK_SET)) {
GHOST_ERROR_LOG("Seek failed");
return GHOST_ERR_IO;
}
if ((ret = fread(values, dtsize, nnz,f)) != (size_t)(nnz)){
GHOST_ERROR_LOG("fread failed: %s (%zu)",strerror(errno),ret);
return GHOST_ERR_IO;
}
fclose(f);
} else if (row == GHOST_SPARSEMAT_ROWFUNC_FINALIZE) {
free(colInd);
free(rowPtr);
free(globalRowPtr);
free(values);
} else {
*rowlen = rowPtr[row-firstrow+1]-rowPtr[row-firstrow];
memcpy(col,&colInd[rowPtr[row-firstrow]-rowPtr[0]],(*rowlen)*sizeof(ghost_gidx));
memcpy(val,&values[(rowPtr[row-firstrow]-rowPtr[0])*dtsize],(*rowlen)*dtsize);
}
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_INITIALIZATION|GHOST_FUNCTYPE_IO);
return 0;
}
ghost_error ghost_bincrs_header_read(ghost_bincrs_header_t *header, char *matrixPath)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_UTIL|GHOST_FUNCTYPE_IO);
FILE* file;
long filesize;
int swapReq = 0;
size_t ret;
GHOST_DEBUG_LOG(1,"Reading header from %s",matrixPath);
if ((file = fopen(matrixPath, "rb"))==NULL){
GHOST_ERROR_LOG("Could not open binary CRS file %s: %s",matrixPath,strerror(errno));
return GHOST_ERR_IO;
}
fseek(file,0L,SEEK_END);
filesize = ftell(file);
fseek(file,0L,SEEK_SET);
if ((ret = fread(&header->endianess, 4, 1, file)) != (size_t)1) {
GHOST_ERROR_LOG("fread failed: %s (%zu)",strerror(errno),ret);
return GHOST_ERR_IO;
}
if (header->endianess == GHOST_BINCRS_LITTLE_ENDIAN && ghost_machine_bigendian()) {
GHOST_DEBUG_LOG(1,"Need to convert from little to big endian.");
swapReq = 1;
} else if (header->endianess != GHOST_BINCRS_LITTLE_ENDIAN && !ghost_machine_bigendian()) {
GHOST_DEBUG_LOG(1,"Need to convert from big to little endian.");
swapReq = 1;
} else {
GHOST_DEBUG_LOG(1,"OK, file and library have same endianess.");
}
if ((ret = fread(&header->version, 4, 1, file)) != (size_t)1) {
GHOST_ERROR_LOG("fread failed: %s (%zu)",strerror(errno),ret);
return GHOST_ERR_IO;
}
if (swapReq) header->version = bswap_32(header->version);
if ((ret = fread(&header->base, 4, 1, file)) != (size_t)1) {
GHOST_ERROR_LOG("fread failed: %s (%zu)",strerror(errno),ret);
return GHOST_ERR_IO;
}
if (swapReq) header->base = bswap_32(header->base);
if ((ret = fread(&header->symmetry, 4, 1, file)) != (size_t)1) {
GHOST_ERROR_LOG("fread failed: %s (%zu)",strerror(errno),ret);
return GHOST_ERR_IO;
}
if (swapReq) header->symmetry = bswap_32(header->symmetry);
if ((ret = fread(&header->datatype, 4, 1, file)) != (size_t)1) {
GHOST_ERROR_LOG("fread failed: %s (%zu)",strerror(errno),ret);
return GHOST_ERR_IO;
}
if (swapReq) header->datatype = bswap_32(header->datatype);
if ((ret = fread(&header->nrows, 8, 1, file)) != (size_t)1) {
GHOST_ERROR_LOG("fread failed: %s (%zu)",strerror(errno),ret);
return GHOST_ERR_IO;
}
if (swapReq) header->nrows = bswap_64(header->nrows);
if ((ret = fread(&header->ncols, 8, 1, file)) != (size_t)1) {
GHOST_ERROR_LOG("fread failed: %s (%zu)",strerror(errno),ret);
return GHOST_ERR_IO;
}
if (swapReq) header->ncols = bswap_64(header->ncols);
if ((ret = fread(&header->nnz, 8, 1, file)) != (size_t)1) {
GHOST_ERROR_LOG("fread failed: %s (%zu)",strerror(errno),ret);
return GHOST_ERR_IO;
}
if (swapReq) header->nnz = bswap_64(header->nnz);
size_t valSize;
GHOST_CALL_RETURN(ghost_datatype_size(&valSize,(ghost_datatype)header->datatype));
long rightFilesize = GHOST_BINCRS_SIZE_HEADER +
(long)(header->nrows+1) * GHOST_BINCRS_SIZE_RPT_EL +
(long)header->nnz * GHOST_BINCRS_SIZE_COL_EL +
(long)header->nnz * valSize;
if (filesize != rightFilesize) {
GHOST_ERROR_LOG("File has invalid size! (is: %ld, should be: %ld)",filesize, rightFilesize);
return GHOST_ERR_IO;
}
fclose(file);
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_UTIL|GHOST_FUNCTYPE_IO);
return GHOST_SUCCESS;
}
|
DRB011-minusminus-orig-yes.c | /*
Copyright (C) 1991-2018 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it andor
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http:www.gnu.org/licenses/>.
*/
/*
This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it.
*/
/*
glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default.
*/
/*
wchar_t uses Unicode 10.0.0. Version 10.0 of the Unicode Standard is
synchronized with ISOIEC 10646:2017, fifth edition, plus
the following additions from Amendment 1 to the fifth edition:
- 56 emoji characters
- 285 hentaigana
- 3 additional Zanabazar Square characters
*/
/*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov,
schordan1@llnl.gov, karlin1@llnl.gov)
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https:github.comLLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
The -- operation on numNodes2 is not protected, causing data race.
Data race pair: numNodes2@74:7 vs. numNodes2@74:7
*/
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char * argv[])
{
int i;
int len = 100;
int numNodes = len, numNodes2 = 0;
int x[100];
/* initialize x[] */
int _ret_val_0;
#pragma cetus private(i)
#pragma loop name main#0
#pragma cetus parallel
#pragma omp parallel for private(i)
for (i=0; i<len; i ++ )
{
if ((i%2)==0)
{
x[i]=5;
}
else
{
x[i]=( - 5);
}
}
#pragma cetus private(i)
#pragma loop name main#1
#pragma cetus reduction(+: numNodes2)
#pragma cetus parallel
#pragma omp parallel for private(i) reduction(+: numNodes2)
for (i=(numNodes-1); i>( - 1); -- i)
{
if (x[i]<=0)
{
numNodes2 -- ;
}
}
printf("numNodes2 = %d\n", numNodes2);
_ret_val_0=0;
return _ret_val_0;
}
|
isx_omp.c | /*
Copyright (c) 2015, 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.
*/
#define HCLIB_VERSION
#define _POSIX_C_SOURCE 199309L
#include <shmem.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <math.h>
#include <string.h>
#include <unistd.h> // sleep()
#include <sys/stat.h>
#include <stdint.h>
#include "params.h"
#include "isx.h"
#include "timer.h"
#include "pcg_basic.h"
#include <omp.h>
#define ROOT_PE 0
#define INTS_PER_CACHE_LINE (128 / sizeof(int))
#define ISX_PROFILING
// Needed for shmem collective operations
int pWrk[_SHMEM_REDUCE_MIN_WRKDATA_SIZE];
double dWrk[_SHMEM_REDUCE_SYNC_SIZE];
long long int llWrk[_SHMEM_REDUCE_MIN_WRKDATA_SIZE];
long pSync[_SHMEM_REDUCE_SYNC_SIZE];
uint64_t NUM_PES; // Number of parallel workers
uint64_t TOTAL_KEYS; // Total number of keys across all PEs
uint64_t NUM_KEYS_PER_PE; // Number of keys generated on each PE
uint64_t NUM_BUCKETS; // The number of buckets in the bucket sort
uint64_t BUCKET_WIDTH; // The size of each bucket
uint64_t MAX_KEY_VAL; // The maximum possible generated key value
volatile int whose_turn;
long long int receive_offset = 0;
long long int my_bucket_size = 0;
static int num_threads = -1;
#define SHMEM_BARRIER_AT_START { timer_start(&timers[TIMER_BARRIER_START]); shmem_barrier_all(); timer_stop(&timers[TIMER_BARRIER_START]); }
#define SHMEM_BARRIER_AT_EXCHANGE { timer_start(&timers[TIMER_BARRIER_EXCHANGE]); shmem_barrier_all(); timer_stop(&timers[TIMER_BARRIER_EXCHANGE]); }
#define SHMEM_BARRIER_AT_END { timer_start(&timers[TIMER_BARRIER_END]); shmem_barrier_all(); timer_stop(&timers[TIMER_BARRIER_END]); }
// #define EXTRA_STATS
#ifdef EXTRA_STATS
float avg_time=0, avg_time_all2all = 0;
#endif
#ifdef EDISON_DATASET
#define KEY_BUFFER_SIZE ((1uLL<<31uLL))
#elif defined(DAVINCI_DATASET)
#define KEY_BUFFER_SIZE ((1uLL<<29uLL))
#else
#error No cluster specified
#endif
// The receive array for the All2All exchange
// KEY_TYPE my_bucket_keys[KEY_BUFFER_SIZE];
KEY_TYPE *my_bucket_keys;
#ifdef PERMUTE
int * permute_array;
#endif
static unsigned long long current_time_ns() {
#ifdef __MACH__
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
unsigned long long s = 1000000000ULL * (unsigned long long)mts.tv_sec;
return (unsigned long long)mts.tv_nsec + s;
#else
struct timespec t ={0,0};
clock_gettime(CLOCK_MONOTONIC, &t);
unsigned long long s = 1000000000ULL * (unsigned long long)t.tv_sec;
return (((unsigned long long)t.tv_nsec)) + s;
#endif
}
int main(const int argc, char ** argv)
{
shmem_init();
#pragma omp parallel
#pragma omp single
num_threads = omp_get_num_threads();
my_bucket_keys = (KEY_TYPE *)shmem_malloc(KEY_BUFFER_SIZE * sizeof(KEY_TYPE));
assert(my_bucket_keys);
#ifdef EXTRA_STATS
_timer_t total_time;
if(shmem_my_pe() == 0) {
printf("\n-----\nmkdir timedrun fake\n\n");
timer_start(&total_time);
}
#endif
init_shmem_sync_array(pSync);
char * log_file = parse_params(argc, argv);
int err = bucket_sort();
log_times(log_file);
#ifdef EXTRA_STATS
if(shmem_my_pe() == 0) {
just_timer_stop(&total_time);
double tTime = ( total_time.stop.tv_sec - total_time.start.tv_sec ) + ( total_time.stop.tv_nsec - total_time.start.tv_nsec )/1E9;
avg_time *= 1000;
avg_time_all2all *= 1000;
printf("\n============================ MMTk Statistics Totals ============================\n");
if(NUM_ITERATIONS == 1) { //TODO: fix time calculation below for more number of iterations
printf("time.mu\tt.ATA_KEYS\tt.MAKE_INPUT\tt.COUNT_BUCKET_SIZES\tt.BUCKETIZE\tt.COMPUTE_OFFSETS\tt.LOCAL_SORT\tBARRIER_AT_START\tBARRIER_AT_EXCHANGE\tBARRIER_AT_END\tnWorkers\tnPEs\n");
double TIMES[TIMER_NTIMERS];
memset(TIMES, 0x00, sizeof(double) * TIMER_NTIMERS);
for(int i=0; i<NUM_PES; i++) {
for(int t = 0; t < TIMER_NTIMERS; ++t){
if(timers[t].all_times != NULL){
TIMES[t] += timers[t].all_times[i];
}
}
}
for(int t = 0; t < TIMER_NTIMERS; ++t){
printf("%.3f\t", (TIMES[t]/NUM_PES)*1000);
}
printf("1\t%d\n",NUM_PES);
printf("Total time: %.3f\n",(TIMES[0]/NUM_PES)*1000);
}
else {
printf("time.mu\ttimeAll2All\tnWorkers\tnPEs\n");
printf("%.3f\t%.3f\t1\t%d\n",avg_time,avg_time_all2all,NUM_PES);
printf("Total time: %.3f\n",avg_time);
}
printf("------------------------------ End MMTk Statistics -----------------------------\n");
printf("===== TEST PASSED in %.3f msec =====\n",(tTime*1000));
}
#endif
shmem_finalize();
return 0;
}
// Parses all of the command line input and definitions in params.h
// to set all necessary runtime values and options
static char * parse_params(const int argc, char ** argv)
{
if(argc != 3)
{
if( shmem_my_pe() == 0){
printf("Usage: \n");
printf(" ./%s <total num keys(strong) | keys per pe(weak)> <log_file>\n",argv[0]);
}
// shmem_finalize();
exit(1);
}
NUM_PES = (uint64_t) shmem_n_pes();
MAX_KEY_VAL = DEFAULT_MAX_KEY;
NUM_BUCKETS = NUM_PES;
BUCKET_WIDTH = (uint64_t) ceil((double)MAX_KEY_VAL/NUM_BUCKETS);
char * log_file = argv[2];
char scaling_msg[64];
switch(SCALING_OPTION){
case STRONG:
{
TOTAL_KEYS = (uint64_t) atoi(argv[1]);
NUM_KEYS_PER_PE = (uint64_t) ceil((double)TOTAL_KEYS/NUM_PES);
sprintf(scaling_msg,"STRONG");
break;
}
case WEAK:
{
NUM_KEYS_PER_PE = (uint64_t) (atoi(argv[1]));
sprintf(scaling_msg,"WEAK");
break;
}
case WEAK_ISOBUCKET:
{
NUM_KEYS_PER_PE = (uint64_t) (atoi(argv[1]));
BUCKET_WIDTH = ISO_BUCKET_WIDTH;
MAX_KEY_VAL = (uint64_t) (NUM_PES * BUCKET_WIDTH);
sprintf(scaling_msg,"WEAK_ISOBUCKET");
break;
}
default:
{
if(shmem_my_pe() == 0){
printf("Invalid scaling option! See params.h to define the scaling option.\n");
}
// shmem_finalize();
exit(1);
break;
}
}
assert(MAX_KEY_VAL > 0);
assert(NUM_KEYS_PER_PE > 0);
assert(NUM_PES > 0);
assert(MAX_KEY_VAL > NUM_PES);
assert(NUM_BUCKETS > 0);
assert(BUCKET_WIDTH > 0);
if(shmem_my_pe() == 0){
printf("ISx v%1d.%1d\n",MAJOR_VERSION_NUMBER,MINOR_VERSION_NUMBER);
#ifdef PERMUTE
printf("Random Permute Used in ATA.\n");
#endif
printf(" Number of Keys per PE: %" PRIu64 "\n", NUM_KEYS_PER_PE);
printf(" Max Key Value: %" PRIu64 "\n", MAX_KEY_VAL);
printf(" Bucket Width: %" PRIu64 "\n", BUCKET_WIDTH);
printf(" Number of Iterations: %u\n", NUM_ITERATIONS);
printf(" Number of PEs: %" PRIu64 "\n", NUM_PES);
printf(" Worker threads per PE: %d\n", omp_get_max_threads());
printf(" %s Scaling!\n",scaling_msg);
}
return log_file;
}
/*
* The primary compute function for the bucket sort
* Executes the sum of NUM_ITERATIONS + BURN_IN iterations, as defined in params.h
* Only iterations after the BURN_IN iterations are timed
* Only the final iteration calls the verification function
*/
static int bucket_sort(void)
{
int err = 0;
init_timers(NUM_ITERATIONS);
#ifdef PERMUTE
create_permutation_array();
#endif
for(uint64_t i = 0; i < (NUM_ITERATIONS + BURN_IN); ++i)
{
// Reset timers after burn in
if(i == BURN_IN){
init_timers(NUM_ITERATIONS);
}
SHMEM_BARRIER_AT_START;
timer_start(&timers[TIMER_TOTAL]);
KEY_TYPE * my_keys = make_input();
int **bucket_counts_per_chunk;
int * local_bucket_sizes = count_local_bucket_sizes(my_keys,
&bucket_counts_per_chunk);
int * send_offsets;
int * local_bucket_offsets = compute_local_bucket_offsets(local_bucket_sizes,
&send_offsets);
KEY_TYPE * my_local_bucketed_keys = bucketize_local_keys(my_keys,
local_bucket_offsets, bucket_counts_per_chunk);
KEY_TYPE * my_bucket_keys = exchange_keys(send_offsets,
local_bucket_sizes,
my_local_bucketed_keys);
my_bucket_size = receive_offset;
int * my_local_key_counts = count_local_keys(my_bucket_keys);
SHMEM_BARRIER_AT_END;
timer_stop(&timers[TIMER_TOTAL]);
// Only the last iteration is verified
if(i == NUM_ITERATIONS) {
err = verify_results(my_local_key_counts, my_bucket_keys);
}
// Reset receive_offset used in exchange_keys
receive_offset = 0;
free(my_local_bucketed_keys);
free(my_keys);
free(local_bucket_sizes);
free(local_bucket_offsets);
free(send_offsets);
free(my_local_key_counts);
for (int i = 0; i < num_threads; i++) {
free(bucket_counts_per_chunk[i]);
}
free(bucket_counts_per_chunk);
shmem_barrier_all();
}
return err;
}
/*
* Generates uniformly random keys [0, MAX_KEY_VAL] on each rank using the time and rank
* number as a seed. NUM_KEYS_PER_PE are generated in each PE, into the locally
* allocated my_keys buffer.
*/
static KEY_TYPE * make_input(void)
{
timer_start(&timers[TIMER_INPUT]);
KEY_TYPE * const my_keys = (KEY_TYPE *)malloc(NUM_KEYS_PER_PE *
sizeof(KEY_TYPE));
assert(my_keys);
#ifdef ISX_PROFILING
unsigned long long start = current_time_ns();
#endif
#pragma omp parallel
{
const int i = omp_get_thread_num();
pcg32_random_t rng = seed_my_rank(i);
uint64_t chunk_size = (NUM_KEYS_PER_PE + num_threads - 1) / num_threads;
uint64_t start_chunk = i * chunk_size;
uint64_t end_chunk = (i + 1) * chunk_size;
if (end_chunk > NUM_KEYS_PER_PE) end_chunk = NUM_KEYS_PER_PE;
for(uint64_t ii = start_chunk; ii < end_chunk; ++ii) {
my_keys[ii] = pcg32_boundedrand_r(&rng, MAX_KEY_VAL);
}
}
#ifdef ISX_PROFILING
unsigned long long end = current_time_ns();
if (shmem_my_pe() == 0)
printf("Making input took %llu ns\n", end - start);
#endif
timer_stop(&timers[TIMER_INPUT]);
#ifdef DEBUG
wait_my_turn();
char msg[1024];
const int my_rank = shmem_my_pe();
// const int my_rank = ::shmem_my_pe();
sprintf(msg,"Rank %d: Initial Keys: ", my_rank);
for(uint64_t i = 0; i < NUM_KEYS_PER_PE; ++i){
if(i < PRINT_MAX)
sprintf(msg + strlen(msg),"%d ", my_keys[i]);
}
sprintf(msg + strlen(msg),"\n");
printf("%s",msg);
fflush(stdout);
my_turn_complete();
#endif
return my_keys;
}
/*
* Computes the size of each bucket by iterating all keys and incrementing
* their corresponding bucket's size
*/
static int * count_local_bucket_sizes(KEY_TYPE const * const my_keys,
int ***bucket_counts_per_chunk_out)
{
int * const local_bucket_sizes = (int *)calloc(NUM_BUCKETS, sizeof(int));
assert(local_bucket_sizes);
timer_start(&timers[TIMER_BCOUNT]);
#ifdef ISX_PROFILING
unsigned long long start = current_time_ns();
#endif
int **bucket_counts_per_chunk = (int **)malloc(num_threads * sizeof(int *));
#pragma omp parallel
{
const int i = omp_get_thread_num();
/**
* Parallelized across the my_keys buffer of locally generated keys to
* sort, allocate a thread-local buffer called bucket_sizes. For each
* thread, that thread's bucket_sizes buffer stores a partial count of the
* number of keys in each bucket for the subset of my_keys that the thread
* iterated over.
*/
int *bucket_sizes = NULL;
if (NUM_BUCKETS >= INTS_PER_CACHE_LINE) {
bucket_sizes = (int *)calloc(NUM_BUCKETS, sizeof(int));
} else {
bucket_sizes = (int *)calloc(INTS_PER_CACHE_LINE, sizeof(int));
}
uint64_t chunk_size = (NUM_KEYS_PER_PE + num_threads - 1) / num_threads;
uint64_t start_chunk = i * chunk_size;
uint64_t end_chunk = (i + 1) * chunk_size;
if (end_chunk > NUM_KEYS_PER_PE) end_chunk = NUM_KEYS_PER_PE;
for (uint64_t ii = start_chunk; ii < end_chunk; ++ii) {
const uint32_t bucket_index = my_keys[ii] / BUCKET_WIDTH;
bucket_sizes[bucket_index]++;
}
bucket_counts_per_chunk[i] = bucket_sizes;
}
/**
* Reduce the partial counts from each thread into local_bucket_sizes.
*/
for (int i = 0; i < num_threads; i++) {
int *worker_bucket_sizes = bucket_counts_per_chunk[i];
#pragma omp simd
for (unsigned b = 0; b < NUM_BUCKETS; b++) {
local_bucket_sizes[b] += worker_bucket_sizes[b];
}
// free(worker_bucket_sizes);
}
*bucket_counts_per_chunk_out = bucket_counts_per_chunk;
// free(bucket_counts_per_chunk);
#ifdef ISX_PROFILING
unsigned long long end = current_time_ns();
if (shmem_my_pe() == 0)
printf("Counting local bucket sizes took %llu ns\n", end - start);
#endif
timer_stop(&timers[TIMER_BCOUNT]);
#ifdef DEBUG
wait_my_turn();
char msg[1024];
const int my_rank = shmem_my_pe();
// const int my_rank = ::shmem_my_pe();
sprintf(msg,"Rank %d: local bucket sizes: ", my_rank);
for(uint64_t i = 0; i < NUM_BUCKETS; ++i){
if(i < PRINT_MAX)
sprintf(msg + strlen(msg),"%d ", local_bucket_sizes[i]);
}
sprintf(msg + strlen(msg),"\n");
printf("%s",msg);
fflush(stdout);
my_turn_complete();
#endif
return local_bucket_sizes;
}
/*
* Computes the prefix scan of the bucket sizes to determine the starting locations
* of each bucket in the local bucketed array
* Stores a copy of the bucket offsets for use in exchanging keys because the
* original bucket_offsets array is modified in the bucketize function
*/
static int * compute_local_bucket_offsets(int const * const local_bucket_sizes,
int ** send_offsets)
{
int * const local_bucket_offsets = (int *)malloc(NUM_BUCKETS * sizeof(int));
assert(local_bucket_offsets);
timer_start(&timers[TIMER_BOFFSET]);
(*send_offsets) = (int *)malloc(NUM_BUCKETS * sizeof(int));
assert(*send_offsets);
local_bucket_offsets[0] = 0;
(*send_offsets)[0] = 0;
int temp = 0;
for(uint64_t i = 1; i < NUM_BUCKETS; i++){
temp = local_bucket_offsets[i-1] + local_bucket_sizes[i-1];
local_bucket_offsets[i] = temp;
(*send_offsets)[i] = temp;
}
timer_stop(&timers[TIMER_BOFFSET]);
#ifdef DEBUG
wait_my_turn();
char msg[1024];
const int my_rank = shmem_my_pe();
// const int my_rank = ::shmem_my_pe();
sprintf(msg,"Rank %d: local bucket offsets: ", my_rank);
for(uint64_t i = 0; i < NUM_BUCKETS; ++i){
if(i < PRINT_MAX)
sprintf(msg + strlen(msg),"%d ", local_bucket_offsets[i]);
}
sprintf(msg + strlen(msg),"\n");
printf("%s",msg);
fflush(stdout);
my_turn_complete();
#endif
return local_bucket_offsets;
}
/*
* Places local keys into their corresponding local bucket.
* The contents of each bucket are not sorted.
*/
static KEY_TYPE * bucketize_local_keys(KEY_TYPE const * const my_keys,
int * const local_bucket_offsets,
int **bucket_counts_per_chunk)
{
KEY_TYPE * const my_local_bucketed_keys = (KEY_TYPE *)malloc(
NUM_KEYS_PER_PE * sizeof(KEY_TYPE));
assert(my_local_bucketed_keys);
timer_start(&timers[TIMER_BUCKETIZE]);
#ifdef ISX_PROFILING
unsigned long long start = current_time_ns();
#endif
if (num_threads == 1) {
for(uint64_t i = 0; i < NUM_KEYS_PER_PE; ++i){
const KEY_TYPE key = my_keys[i];
const uint32_t bucket_index = key / BUCKET_WIDTH;
uint32_t index;
assert(local_bucket_offsets[bucket_index] >= 0);
index = local_bucket_offsets[bucket_index]++;
assert(index < NUM_KEYS_PER_PE);
my_local_bucketed_keys[index] = key;
}
} else {
int *chunk_bucket_offsets = (int *)malloc(NUM_BUCKETS * num_threads *
sizeof(int));
// #pragma omp parallel for schedule(static)
for (uint64_t b = 0; b < NUM_BUCKETS; b++) {
chunk_bucket_offsets[b * num_threads + 0] = local_bucket_offsets[b];
for (int w = 1; w < num_threads; w++) {
chunk_bucket_offsets[b * num_threads + w] =
chunk_bucket_offsets[b * num_threads + w - 1] +
bucket_counts_per_chunk[w - 1][b];
}
}
#pragma omp parallel
{
const int c = omp_get_thread_num();
uint64_t chunk_size = (NUM_KEYS_PER_PE + num_threads - 1) / num_threads;
uint64_t start_chunk = c * chunk_size;
uint64_t end_chunk = (c + 1) * chunk_size;
if (end_chunk > NUM_KEYS_PER_PE) end_chunk = NUM_KEYS_PER_PE;
int *tmp = NULL;
if (NUM_BUCKETS < INTS_PER_CACHE_LINE) {
tmp = (int *)malloc(INTS_PER_CACHE_LINE * sizeof(int));
} else {
tmp = (int *)malloc(NUM_BUCKETS * sizeof(int));
}
assert(tmp);
for (unsigned i = 0; i < NUM_BUCKETS; i++) {
tmp[i] = chunk_bucket_offsets[i * num_threads + c];
}
for (uint64_t i = start_chunk; i < end_chunk; i++) {
const KEY_TYPE key = my_keys[i];
const uint32_t bucket_index = key / BUCKET_WIDTH;
uint32_t index = tmp[bucket_index]++;
assert(index < NUM_KEYS_PER_PE);
my_local_bucketed_keys[index] = key;
}
free(tmp);
}
free(chunk_bucket_offsets);
}
#ifdef ISX_PROFILING
unsigned long long end = current_time_ns();
if (shmem_my_pe() == 0)
printf("Bucketizing took %llu ns\n", end - start);
#endif
timer_stop(&timers[TIMER_BUCKETIZE]);
#ifdef DEBUG
wait_my_turn();
char msg[1024];
const int my_rank = shmem_my_pe();
// const int my_rank = ::shmem_my_pe();
sprintf(msg,"Rank %d: local bucketed keys: ", my_rank);
for(uint64_t i = 0; i < NUM_KEYS_PER_PE; ++i){
if(i < PRINT_MAX)
sprintf(msg + strlen(msg),"%d ", my_local_bucketed_keys[i]);
}
sprintf(msg + strlen(msg),"\n");
printf("%s",msg);
fflush(stdout);
my_turn_complete();
#endif
return my_local_bucketed_keys;
}
/*
* Each PE sends the contents of its local buckets to the PE that owns that bucket.
*/
static KEY_TYPE * exchange_keys(int const * const send_offsets,
int const * const local_bucket_sizes,
KEY_TYPE const * const my_local_bucketed_keys)
{
timer_start(&timers[TIMER_ATA_KEYS]);
const int my_rank = shmem_my_pe();
// const int my_rank = ::shmem_my_pe();
unsigned int total_keys_sent = 0;
// Keys destined for local key buffer can be written with memcpy
const long long int write_offset_into_self = shmem_longlong_fadd(
&receive_offset, (long long int)local_bucket_sizes[my_rank], my_rank);
assert((unsigned long long)write_offset_into_self +
(unsigned long long)local_bucket_sizes[my_rank] <= KEY_BUFFER_SIZE);
memcpy(&my_bucket_keys[write_offset_into_self],
&my_local_bucketed_keys[send_offsets[my_rank]],
local_bucket_sizes[my_rank]*sizeof(KEY_TYPE));
for(uint64_t i = 0; i < NUM_PES; ++i){
#ifdef PERMUTE
const int target_pe = permute_array[i];
#elif INCAST
const int target_pe = i;
#else
const int target_pe = (my_rank + i) % NUM_PES;
#endif
// Local keys already written with memcpy
if(target_pe == my_rank){ continue; }
const int read_offset_from_self = send_offsets[target_pe];
const int my_send_size = local_bucket_sizes[target_pe];
const long long int write_offset_into_target = shmem_longlong_fadd(
&receive_offset, (long long int)my_send_size, target_pe);
#ifdef DEBUG
printf("Rank: %d Target: %d Offset into target: %lld Offset into myself: %d Send Size: %d\n",
my_rank, target_pe, write_offset_into_target, read_offset_from_self, my_send_size);
#endif
if ((unsigned long long)write_offset_into_target +
(unsigned long long)my_send_size > KEY_BUFFER_SIZE) {
fprintf(stderr, "Put offset %llu was greater than KEY_BUFFER_SIZE "
"%llu\n", (unsigned long long)write_offset_into_target +
(unsigned long long)my_send_size, KEY_BUFFER_SIZE);
exit(1);
}
shmem_int_put(&(my_bucket_keys[write_offset_into_target]),
&(my_local_bucketed_keys[read_offset_from_self]),
my_send_size,
target_pe);
total_keys_sent += my_send_size;
}
#ifdef BARRIER_ATA
SHMEM_BARRIER_AT_EXCHANGE;
#endif
timer_stop(&timers[TIMER_ATA_KEYS]);
timer_count(&timers[TIMER_ATA_KEYS], total_keys_sent);
#ifdef DEBUG
wait_my_turn();
char msg[1024];
sprintf(msg,"Rank %d: Bucket Size %lld | Total Keys Sent: %u | Keys after exchange:",
my_rank, receive_offset, total_keys_sent);
for(long long int i = 0; i < receive_offset; ++i){
if(i < PRINT_MAX)
sprintf(msg + strlen(msg),"%d ", my_bucket_keys[i]);
}
sprintf(msg + strlen(msg),"\n");
printf("%s",msg);
fflush(stdout);
my_turn_complete();
#endif
return my_bucket_keys;
}
int compare_keys(const void *a, const void *b) {
const KEY_TYPE key1 = *((KEY_TYPE *)a);
const KEY_TYPE key2 = *((KEY_TYPE *)b);
return key1 - key2;
}
/*
* Counts the occurence of each key in my bucket.
* Key indices into the count array are the key's value minus my bucket's
* minimum key value to allow indexing from 0.
* my_bucket_keys: All keys in my bucket unsorted [my_rank * BUCKET_WIDTH, (my_rank+1)*BUCKET_WIDTH)
*/
static int * count_local_keys(KEY_TYPE const * const my_bucket_keys)
{
int * const my_local_key_counts = (int *)calloc(BUCKET_WIDTH, sizeof(int));
assert(my_local_key_counts);
timer_start(&timers[TIMER_SORT]);
const int my_rank = shmem_my_pe();
// const int my_rank = ::shmem_my_pe();
const int my_min_key = my_rank * BUCKET_WIDTH;
int *per_chunk_counts = (int *)calloc(num_threads * BUCKET_WIDTH, sizeof(int));
assert(per_chunk_counts);
#ifdef ISX_PROFILING
unsigned long long start = current_time_ns();
#endif
#ifdef ISX_PROFILING
unsigned long long intermediate;
#endif
#pragma omp parallel
{
const int c = omp_get_thread_num();
long long int chunk_size = (my_bucket_size + num_threads - 1) / num_threads;
long long int start_chunk = c * chunk_size;
long long int end_chunk = (c + 1) * chunk_size;
if (end_chunk > my_bucket_size) end_chunk = my_bucket_size;
int *counts = per_chunk_counts + (c * BUCKET_WIDTH);
#pragma omp for
for (int i = 0; i < my_bucket_size; i++) {
const unsigned int key_index = my_bucket_keys[i] - my_min_key;
counts[key_index]++;
}
#pragma omp barrier
#ifdef ISX_PROFILING
#pragma omp master
intermediate = current_time_ns();
#endif
chunk_size = (BUCKET_WIDTH + num_threads - 1) / num_threads;
start_chunk = c * chunk_size;
end_chunk = (c + 1) * chunk_size;
if (end_chunk > BUCKET_WIDTH) end_chunk = BUCKET_WIDTH;
// for (int c = 0; c < num_threads; c++) {
// int *counts = per_chunk_counts[c];
//
// #pragma omp simd
// for (unsigned i = start_chunk; i < end_chunk; i++) {
// my_local_key_counts[i] += counts[i];
// }
// }
// for (unsigned i = start_chunk; i < end_chunk; i++) {
for (int c = 0; c < num_threads; c++) {
int *thread_counts = per_chunk_counts + (c * BUCKET_WIDTH);
#pragma omp for
for (unsigned i = 0; i < BUCKET_WIDTH; i++) {
my_local_key_counts[i] += thread_counts[i];
}
}
}
free(per_chunk_counts);
#ifdef ISX_PROFILING
unsigned long long end = current_time_ns();
if (shmem_my_pe() == 0)
printf("Counting local took %llu ns for stage 1, %llu ns for stage 2, "
"my_bucket_size = %lld, BUCKET_WIDTH = %llu\n", intermediate - start,
end - intermediate, my_bucket_size, BUCKET_WIDTH);
#endif
// // Count the occurences of each key in my bucket
// for(long long int i = 0; i < my_bucket_size; ++i){
// const unsigned int key_index = my_bucket_keys[i] - my_min_key;
// assert(my_bucket_keys[i] >= my_min_key);
// assert(key_index < BUCKET_WIDTH);
// my_local_key_counts[key_index]++;
// }
timer_stop(&timers[TIMER_SORT]);
#ifdef DEBUG
wait_my_turn();
char msg[4096];
sprintf(msg,"Rank %d: Bucket Size %lld | Local Key Counts:", my_rank, my_bucket_size);
for(uint64_t i = 0; i < BUCKET_WIDTH; ++i){
if(i < PRINT_MAX)
sprintf(msg + strlen(msg),"%d ", my_local_key_counts[i]);
}
sprintf(msg + strlen(msg),"\n");
printf("%s",msg);
fflush(stdout);
my_turn_complete();
#endif
return my_local_key_counts;
}
/*
* Verifies the correctness of the sort.
* Ensures all keys are within a PE's bucket boundaries.
* Ensures the final number of keys is equal to the initial.
*/
static int verify_results(int const * const my_local_key_counts,
KEY_TYPE const * const my_local_keys)
{
shmem_barrier_all();
int error = 0;
const int my_rank = shmem_my_pe();
// const int my_rank = ::shmem_my_pe();
const int my_min_key = my_rank * BUCKET_WIDTH;
const int my_max_key = (my_rank+1) * BUCKET_WIDTH - 1;
#ifdef ISX_PROFILING
unsigned long long start = current_time_ns();
#endif
// Verify all keys are within bucket boundaries
for(long long int i = 0; i < my_bucket_size; ++i){
const int key = my_local_keys[i];
if((key < my_min_key) || (key > my_max_key)){
printf("Rank %d Failed Verification!\n",my_rank);
printf("Key: %d is outside of bounds [%d, %d]\n", key, my_min_key, my_max_key);
error = 1;
}
}
#ifdef ISX_PROFILING
unsigned long long end = current_time_ns();
if (shmem_my_pe() == 0)
printf("Verifying took %llu ns\n", end - start);
#endif
// Verify the sum of the key population equals the expected bucket size
long long int bucket_size_test = 0;
for(uint64_t i = 0; i < BUCKET_WIDTH; ++i){
bucket_size_test += my_local_key_counts[i];
}
if(bucket_size_test != my_bucket_size){
printf("Rank %d Failed Verification!\n",my_rank);
printf("Actual Bucket Size: %lld Should be %lld\n", bucket_size_test, my_bucket_size);
error = 1;
}
// Verify the final number of keys equals the initial number of keys
static long long int total_num_keys = 0;
shmem_longlong_sum_to_all(&total_num_keys, &my_bucket_size, 1, 0, 0, NUM_PES,
llWrk, pSync);
shmem_barrier_all();
if(total_num_keys != (long long int)(NUM_KEYS_PER_PE * NUM_PES)){
if(my_rank == ROOT_PE){
printf("Verification Failed!\n");
printf("Actual total number of keys: %lld Expected %" PRIu64 "\n", total_num_keys, NUM_KEYS_PER_PE * NUM_PES );
error = 1;
}
}
return error;
}
/*
* Gathers all the timing information from each PE and prints
* it to a file. All information from a PE is printed as a row in a tab seperated file
*/
static void log_times(char * log_file)
{
FILE * fp = NULL;
for(uint64_t i = 0; i < TIMER_NTIMERS; ++i){
timers[i].all_times = gather_rank_times(&timers[i]);
timers[i].all_counts = gather_rank_counts(&timers[i]);
}
if(shmem_my_pe() == ROOT_PE)
// if(::shmem_my_pe() == ROOT_PE)
{
int print_names = 0;
if(file_exists(log_file) != 1){
print_names = 1;
}
if((fp = fopen(log_file, "a+b"))==NULL){
perror("Error opening log file:");
exit(1);
}
if(print_names == 1){
print_run_info(fp);
print_timer_names(fp);
}
print_timer_values(fp);
report_summary_stats();
fclose(fp);
}
}
/*
* Computes the average total time and average all2all time and prints it to the command line
*/
static void report_summary_stats(void)
{
if(timers[TIMER_TOTAL].seconds_iter > 0) {
const uint32_t num_records = NUM_PES * timers[TIMER_TOTAL].seconds_iter;
double temp = 0.0;
for(uint64_t i = 0; i < num_records; ++i){
temp += timers[TIMER_TOTAL].all_times[i];
}
#ifdef EXTRA_STATS
avg_time = temp/num_records;
#endif
printf("Average total time (per PE): %f seconds\n", temp/num_records);
}
if(timers[TIMER_ATA_KEYS].seconds_iter >0) {
const uint32_t num_records = NUM_PES * timers[TIMER_ATA_KEYS].seconds_iter;
double temp = 0.0;
for(uint64_t i = 0; i < num_records; ++i){
temp += timers[TIMER_ATA_KEYS].all_times[i];
}
#ifdef EXTRA_STATS
avg_time_all2all = temp/num_records;
#endif
printf("Average all2all time (per PE): %f seconds\n", temp/num_records);
}
}
/*
* Prints all the labels for each timer as a row to the file specified by 'fp'
*/
static void print_timer_names(FILE * fp)
{
for(uint64_t i = 0; i < TIMER_NTIMERS; ++i){
if(timers[i].seconds_iter > 0){
fprintf(fp, "%s (sec)\t", timer_names[i]);
}
if(timers[i].count_iter > 0){
fprintf(fp, "%s_COUNTS\t", timer_names[i]);
}
}
fprintf(fp,"\n");
}
/*
* Prints all the relevant runtime parameters as a row to the file specified by 'fp'
*/
static void print_run_info(FILE * fp)
{
fprintf(fp,"SHMEM\t");
fprintf(fp,"NUM_PES %" PRIu64 "\t", NUM_PES);
fprintf(fp,"Max_Key %" PRIu64 "\t", MAX_KEY_VAL);
fprintf(fp,"Num_Iters %u\t", NUM_ITERATIONS);
switch(SCALING_OPTION){
case STRONG: {
fprintf(fp,"Strong Scaling: %" PRIu64 " total keys\t", NUM_KEYS_PER_PE * NUM_PES);
break;
}
case WEAK: {
fprintf(fp,"Weak Scaling: %" PRIu64 " keys per PE\t", NUM_KEYS_PER_PE);
break;
}
case WEAK_ISOBUCKET: {
fprintf(fp,"Weak Scaling Constant Bucket Width: %" PRIu64 "u keys per PE \t", NUM_KEYS_PER_PE);
fprintf(fp,"Constant Bucket Width: %" PRIu64 "\t", BUCKET_WIDTH);
break;
}
default:
{
fprintf(fp,"Invalid Scaling Option!\t");
break;
}
}
#ifdef PERMUTE
fprintf(fp,"Randomized All2All\t");
#elif INCAST
fprintf(fp,"Incast All2All\t");
#else
fprintf(fp,"Round Robin All2All\t");
#endif
fprintf(fp,"\n");
}
/*
* Prints all of the timining information for an individual PE as a row
* to the file specificed by 'fp'.
*/
static void print_timer_values(FILE * fp)
{
unsigned int num_records = NUM_PES * NUM_ITERATIONS;
for(uint64_t i = 0; i < num_records; ++i) {
for(int t = 0; t < TIMER_NTIMERS; ++t){
if(timers[t].all_times != NULL){
fprintf(fp,"%f\t", timers[t].all_times[i]);
}
if(timers[t].all_counts != NULL){
fprintf(fp,"%u\t", timers[t].all_counts[i]);
}
}
fprintf(fp,"\n");
}
}
/*
* Aggregates the per PE timing information
*/
static double * gather_rank_times(_timer_t * const timer)
{
if(timer->seconds_iter > 0) {
assert(timer->seconds_iter == timer->num_iters);
const unsigned int num_records = NUM_PES * timer->seconds_iter;
double * my_times = (double *)shmem_malloc(timer->seconds_iter * sizeof(double));
assert(my_times);
memcpy(my_times, timer->seconds, timer->seconds_iter * sizeof(double));
double * all_times = (double *)shmem_malloc( num_records * sizeof(double));
assert(all_times);
shmem_barrier_all();
shmem_fcollect64(all_times, my_times, timer->seconds_iter, 0, 0, NUM_PES, pSync);
shmem_barrier_all();
shmem_free(my_times);
return all_times;
}
else{
return NULL;
}
}
/*
* Aggregates the per PE timing 'count' information
*/
static unsigned int * gather_rank_counts(_timer_t * const timer)
{
if(timer->count_iter > 0){
const unsigned int num_records = NUM_PES * timer->num_iters;
unsigned int * my_counts = (unsigned int *)shmem_malloc(
timer->num_iters * sizeof(unsigned int));
assert(my_counts);
memcpy(my_counts, timer->count, timer->num_iters*sizeof(unsigned int));
unsigned int * all_counts = (unsigned int *)shmem_malloc(
num_records * sizeof(unsigned int) );
assert(all_counts);
shmem_barrier_all();
shmem_collect32(all_counts, my_counts, timer->num_iters, 0, 0, NUM_PES, pSync);
shmem_barrier_all();
shmem_free(my_counts);
return all_counts;
}
else{
return NULL;
}
}
/*
* Seeds each rank based on the rank number and time
*/
static pcg32_random_t seed_my_rank(const int chunk)
{
const unsigned int my_rank = shmem_my_pe();
const unsigned int virtual_rank = my_rank * num_threads + chunk;
pcg32_random_t rng;
pcg32_srandom_r(&rng, (uint64_t) virtual_rank, (uint64_t) virtual_rank );
return rng;
}
/*
* Initializes the work array required for SHMEM collective functions
*/
static void init_shmem_sync_array(long * const pSync)
{
for(uint64_t i = 0; i < _SHMEM_REDUCE_SYNC_SIZE; ++i){
pSync[i] = _SHMEM_SYNC_VALUE;
}
shmem_barrier_all();
}
/*
* Tests whether or not a file exists.
* Returns 1 if file exists
* Returns 0 if file does not exist
*/
static int file_exists(char * filename)
{
struct stat buffer;
if(stat(filename,&buffer) == 0){
return 1;
}
else {
return 0;
}
}
#ifdef DEBUG
static void wait_my_turn()
{
shmem_barrier_all();
whose_turn = 0;
shmem_barrier_all();
const int my_rank = shmem_my_pe();
// const int my_rank = ::shmem_my_pe();
shmem_int_wait_until((int*)&whose_turn, SHMEM_CMP_EQ, my_rank);
sleep(1);
}
static void my_turn_complete()
{
const int my_rank = shmem_my_pe();
// const int my_rank = ::shmem_my_pe();
const int next_rank = my_rank+1;
if(my_rank < (NUM_PES-1)){ // Last rank updates no one
shmem_int_put((int *)&whose_turn, &next_rank, 1, next_rank);
}
shmem_barrier_all();
}
#endif
#ifdef PERMUTE
/*
* Creates a randomly ordered array of PEs used in the exchange_keys function
*/
static void create_permutation_array()
{
permute_array = (int *) malloc( NUM_PES * sizeof(int) );
assert(permute_array);
for(uint64_t i = 0; i < NUM_PES; ++i){
permute_array[i] = i;
}
shuffle(permute_array, NUM_PES, sizeof(int));
}
/*
* Randomly shuffles a generic array
*/
static void shuffle(void * array, size_t n, size_t size)
{
char tmp[size];
char * arr = array;
size_t stride = size * sizeof(char);
if(n > 1){
for(size_t i = 0; i < (n - 1); ++i){
size_t rnd = (size_t) rand();
size_t j = i + rnd/(RAND_MAX/(n - i) + 1);
memcpy(tmp, arr + j*stride, size);
memcpy(arr + j*stride, arr + i*stride, size);
memcpy(arr + i*stride, tmp, size);
}
}
}
#endif
|
GB_unop__bnot_uint16_uint16.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the 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__bnot_uint16_uint16)
// op(A') function: GB (_unop_tran__bnot_uint16_uint16)
// C type: uint16_t
// A type: uint16_t
// cast: uint16_t cij = aij
// unaryop: cij = ~(aij)
#define GB_ATYPE \
uint16_t
#define GB_CTYPE \
uint16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint16_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = ~(x) ;
// casting
#define GB_CAST(z, aij) \
uint16_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint16_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint16_t z = aij ; \
Cx [pC] = ~(z) ; \
}
// 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_BNOT || GxB_NO_UINT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__bnot_uint16_uint16)
(
uint16_t *Cx, // Cx and Ax may be aliased
const uint16_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
// 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 (uint16_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint16_t aij = Ax [p] ;
uint16_t z = aij ;
Cx [p] = ~(z) ;
}
#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 ;
uint16_t aij = Ax [p] ;
uint16_t z = aij ;
Cx [p] = ~(z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__bnot_uint16_uint16)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
ten_tusscher_2004_epi_S1_18.c | //Original Ten Tusscher
#include <assert.h>
#include <stdlib.h>
#include "ten_tusscher_2004_epi_S1_18.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.6407442866583,0.00127024730863006,0.781477837871060,0.781226285372551,0.000173058844459830,0.485844316142820,0.00292517461971129,0.999998371825952,1.91031873007277e-08,1.87288135192733e-05,0.999773522474666,1.00766286802375,0.999999451356628,3.16576129409975e-05,0.737961690357158,10.2441215797546,139.210514590526};
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 []={14.5383636643555,0.000359007183612285,0.000154135859579797,0.000217532604523131,0.265156052763393,0.186639850277223,0.149365610424309,3.43320580539409,0.0166941723782826,1.45123160724562,1094.13527370174,0.000494385096732911,0.269171393030809,0.0183256017779276,0.00468024174172971,1.50869252254344e-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;
}
|
loop-3.c | /* { dg-do run } */
extern void abort (void);
volatile int count;
static int test(void)
{
return ++count > 0;
}
int main()
{
int i;
#pragma omp for
for (i = 0; i < 10; ++i)
{
if (test())
continue;
abort ();
}
if (i != count)
abort ();
return 0;
}
|
laplace2d.c | /*
* Copyright 2012 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <math.h>
#include <string.h>
#include "timer.h"
#include <stdio.h>
#ifndef VERIFICATION
#define VERIFICATION 0
#endif
#ifndef NN
#define NN 4096
#endif
#ifndef NM
#define NM 4096
#endif
double A[NN][NM];
double Anew[NN][NM];
#if VERIFICATION == 1
double A_CPU[NN][NM];
double Anew_CPU[NN][NM];
#endif
int main(int argc, char** argv)
{
int n = NN;
int m = NM;
int iter_max = 1000;
double tol = 1.0e-6;
double error = 1.0;
int i, j;
int iter = 0;
double runtime;
memset(A, 0, n * m * sizeof(double));
memset(Anew, 0, n * m * sizeof(double));
#if VERIFICATION == 1
memset(A_CPU, 0, n * m * sizeof(double));
memset(Anew_CPU, 0, n * m * sizeof(double));
#endif
for (j = 0; j < n; j++)
{
A[j][0] = 1.0;
Anew[j][0] = 1.0;
#if VERIFICATION == 1
A_CPU[j][0] = 1.0;
Anew_CPU[j][0] = 1.0;
#endif
}
printf("Jacobi relaxation Calculation: %d x %d mesh\n", n, m);
StartTimer();
#pragma aspen enter modelregion
//aspen_param_whilecnt = 1000 for NN = NM = 4096
//aspen_param_whilecnt = 1000 for NN = NM = 8192
#pragma aspen declare param(aspen_param_whilecnt:1000)
#pragma aspen control loop(aspen_param_whilecnt)
#pragma acc data copy(A), create(Anew)
while ( error > tol && iter < iter_max )
{
error = 0.0;
//#pragma omp parallel for shared(m, n, Anew, A)
#pragma acc parallel num_gangs(16) num_workers(32) reduction(max:error) private(j)
{
double lerror = 0.0;
#pragma acc loop gang
for( j = 1; j < n-1; j++)
{
#pragma acc loop worker reduction(max:lerror)
for( i = 1; i < m-1; i++ )
{
Anew[j][i] = 0.25 * ( A[j][i+1] + A[j][i-1]
+ A[j-1][i] + A[j+1][i]);
lerror = fmax( lerror, fabs(Anew[j][i] - A[j][i]));
}
error = fmax(error, lerror);
}
}
//#pragma omp parallel for shared(m, n, Anew, A)
#pragma acc kernels loop gang(16) worker(16)
for( j = 1; j < n-1; j++)
{
#pragma acc loop gang(16) worker(16)
for( i = 1; i < m-1; i++ )
{
A[j][i] = Anew[j][i];
}
}
if(iter % 100 == 0) printf("%5d, %0.6f\n", iter, error);
iter++;
}
#pragma aspen exit modelregion
printf("iter: %d\n", iter);
runtime = GetTimer();
#if VERIFICATION == 1
{
error = 1.0;
iter = 0;
while ( error > tol && iter < iter_max )
{
error = 0.0;
{
for( j = 1; j < n-1; j++)
{
for( i = 1; i < m-1; i++ )
{
Anew_CPU[j][i] = 0.25 * ( A_CPU[j][i+1] + A_CPU[j][i-1]
+ A_CPU[j-1][i] + A_CPU[j+1][i]);
error = fmax( error, fabs(Anew_CPU[j][i] - A_CPU[j][i]));
}
}
}
for( j = 1; j < n-1; j++)
{
for( i = 1; i < m-1; i++ )
{
A_CPU[j][i] = Anew_CPU[j][i];
}
}
if(iter % 100 == 0) printf("%5d, %0.6f\n", iter, error);
iter++;
}
{
double cpu_sum = 0.0f;
double gpu_sum = 0.0f;
double rel_err = 0.0f;
for (i = 1; i < m-1; i++)
{
cpu_sum += A_CPU[i][i]*A_CPU[i][i];
gpu_sum += A[i][i]*A[i][i];
}
cpu_sum = sqrt(cpu_sum);
gpu_sum = sqrt(gpu_sum);
if( cpu_sum > gpu_sum ) {
rel_err = (cpu_sum-gpu_sum)/cpu_sum;
} else {
rel_err = (gpu_sum-cpu_sum)/cpu_sum;
}
if(rel_err < 1e-6)
{
printf("Verification Successful err = %e\n", rel_err);
}
else
{
printf("Verification Fail err = %e\n", rel_err);
}
}
}
#endif
printf("Accelerator Elapsed %f s\n", runtime / 1000);
}
|
DeformationSolver.h | /*
Copyright (c) 2017, Fabian Prada
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer. Redistributions in binary form must reproduce
the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
Neither the name of the Johns Hopkins University 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.
*/
#ifndef DEFORMATION_SOLVER_INCLUDED
#define DEFORMATION_SOLVER_INCLUDED
#include <ceres/ceres.h>
#include <ceres/rotation.h>
#include"HierarchicalModel.h"
#include <omp.h>
#include <ctime>
const int numVariablesPerNode = 6;
//
// Regularity Costs
//
struct RigidityCostFunctor
{
RigidityCostFunctor(double tX, double tY, double tZ)
: m_tX(tX), m_tY(tY), m_tZ(tZ)
{}
template <typename T>
bool operator() (const T* const R1, const T* const T1, const T* const T2, T* residual) const {
T point[3] = { T(m_tX), T(m_tY), T(m_tZ) };
T rotatedPoint[3];
ceres::AngleAxisRotatePoint(R1, point, rotatedPoint);
residual[0] = rotatedPoint[0] + T1[0] - T2[0] - T(m_tX);
residual[1] = rotatedPoint[1] + T1[1] - T2[1] - T(m_tY);
residual[2] = rotatedPoint[2] + T1[2] - T2[2] - T(m_tZ);
return true;
}
private:
const double m_tX;
const double m_tY;
const double m_tZ;
};
void SetRigidityResiduals(const std::vector<std::vector<int>> & neighbourhoods, const std::vector<Eigen::Vector3f> & nodeReferencePosition, double rigidityWeight, Eigen::VectorXd &vars, ceres::Problem &problem)
{
for (int j = 0; j < neighbourhoods.size(); j++)
{
Eigen::Vector3f refPosCurrent = nodeReferencePosition[j];
for (int n = 0; n < neighbourhoods[j].size(); n++)
{
int k = neighbourhoods[j][n];
int jVariableOffset = int(j*numVariablesPerNode);
int kVariableOffset = int(k*numVariablesPerNode);
Eigen::Vector3f diff = nodeReferencePosition[k] - refPosCurrent;
ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<RigidityCostFunctor, 3 /*#residuals*/, 3 /*rotate*/,3 /*jTranslate*/, 3/*kTranslate*/>(new RigidityCostFunctor(diff[0], diff[1], diff[2]));
problem.AddResidualBlock(cost_function, new ceres::ScaledLoss(NULL, rigidityWeight, ceres::TAKE_OWNERSHIP), &(vars[jVariableOffset]) /*rotate*/, &(vars[jVariableOffset + 3]) /*jTranslate*/, &(vars[kVariableOffset + 3]) /*kTranslate*/);
}
}
}
struct FixedNodeRotationCostFunctor
{
FixedNodeRotationCostFunctor(){}
template <typename T>
bool operator() (const T* const R, T* residual) const {
residual[0] = R[0];
residual[1] = R[1];
residual[2] = R[2];
return true;
}
};
void SetFixedNodeRotationResiduals(const std::vector<bool> & fixedNodes, double fixedWeight, Eigen::VectorXd &vars, ceres::Problem &problem)
{
for (int j = 0; j < fixedNodes.size(); j++)
{
if (fixedNodes[j]){
int jVariableOffset = int(j*numVariablesPerNode);
ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<FixedNodeRotationCostFunctor, 3 /*#residuals*/, 3 /*rotate*/>(new FixedNodeRotationCostFunctor());
problem.AddResidualBlock(cost_function, new ceres::ScaledLoss(NULL, fixedWeight, ceres::TAKE_OWNERSHIP), &(vars[jVariableOffset]) /*rotate*/);
}
}
}
struct FixedNodeTranslationCostFunctor
{
FixedNodeTranslationCostFunctor(){}
template <typename T>
bool operator() (const T* const R, T* residual) const {
residual[0] = R[0];
residual[1] = R[1];
residual[2] = R[2];
return true;
}
};
void SetFixedNodeTranslationResiduals(const std::vector<bool> & fixedNodes, double fixedWeight, Eigen::VectorXd &vars, ceres::Problem &problem)
{
for (int j = 0; j < fixedNodes.size(); j++)
{
if (fixedNodes[j]){
int jVariableOffset = int(j*numVariablesPerNode);
ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<FixedNodeTranslationCostFunctor, 3 /*#residuals*/, 3 /*translation*/>(new FixedNodeTranslationCostFunctor());
problem.AddResidualBlock(cost_function, new ceres::ScaledLoss(NULL, fixedWeight, ceres::TAKE_OWNERSHIP), &(vars[jVariableOffset + 3]) /*translation*/);
}
}
}
struct FitCostFunctor
{
typedef
ceres::DynamicAutoDiffCostFunction < FitCostFunctor, 12 /*batch size of derivative evaluation*/ >
CostFunction;
FitCostFunctor(
const int numNodes,
const std::vector<Eigen::Vector3f> &diff,
const std::vector<Eigen::Vector3f> &nodePos,
const std::vector<double> &nodeWeight,
const double fittingWeight,
const Eigen::Vector3f &cpPos,
const Eigen::Vector3f &cpNormal)
: m_numNodes(numNodes)
, m_diff(diff)
, m_nodePos(nodePos)
, m_nodeWeight(nodeWeight)
, m_fittinWeight(fittingWeight)
, m_cpPos(cpPos)
, m_cpNormal(cpNormal)
{}
template <typename T>
bool operator() (T const* const* RT, T* residual) const
{
T pX = -T(m_cpPos[0]);
T pY = -T(m_cpPos[1]);
T pZ = -T(m_cpPos[2]);
for (int i = 0; i < m_numNodes; i++)
{
int ri = i * 2; // start index of rotation
int ti = i * 2 + 1; // start index of translation
T point[3] = { T(m_diff[i][0]), T(m_diff[i][1]), T(m_diff[i][2]) };
T rotatedPoint[3];
ceres::AngleAxisRotatePoint(RT[ri], point, rotatedPoint);
pX += ((rotatedPoint[0]) + RT[ti][0] + T(m_nodePos[i][0])) * T(m_nodeWeight[i]);
pY += ((rotatedPoint[1]) + RT[ti][1] + T(m_nodePos[i][1])) * T(m_nodeWeight[i]);
pZ += ((rotatedPoint[2]) + RT[ti][2] + T(m_nodePos[i][2])) * T(m_nodeWeight[i]);
}
// Point Constraints
residual[0] = pX * 0.316 * m_fittinWeight; // Following [Li et al. 2009], we weight the point-to-point constraint 10% as important as the point-to-normal constraint
residual[1] = pY * 0.316 * m_fittinWeight; // i.e., sqrt(0.1) ~= 0.316. (taking square root here since Ceres wants the "signed cost", not "energy")
residual[2] = pZ * 0.316 * m_fittinWeight;
// Normal Constraint
residual[3] = (pX * T(m_cpNormal[0])) + (pY * T(m_cpNormal[1])) + (pZ * T(m_cpNormal[2]))*m_fittinWeight;
return true;
}
static const int c_numResiduals = 4; // i.e., 3 for point constraints and 1 for normal
private:
const int m_numNodes; // Number of neighboring nodes (usually between 2~5)
const std::vector<Eigen::Vector3f> m_diff; // Difference vectors between the current point and its neighboring nodes
const std::vector<Eigen::Vector3f> m_nodePos; // Positions of the neighboring nodes
const std::vector<double> m_nodeWeight; // Weights of the neighboring nodes
const double m_fittinWeight; //Fitting weight
const Eigen::Vector3f m_cpPos; // Position of the closest point
const Eigen::Vector3f m_cpNormal; // Normal of the closest point
};
void SetFitResiduals(
const std::vector<Eigen::Vector3f> &nodeReferencePosition,
const std::vector<std::vector<IndexWeight>> &vertexParents,
const std::vector<double> & fittingWeight,
const std::vector<int> &targetVertexIndex,
const std::vector<Eigen::Vector3f> &targetVertexPosition,
const std::vector<Eigen::Vector3f> &referenceVertexPosition,
const std::vector<Eigen::Vector3f> &targetVertexNormal,
Eigen::VectorXd &vars,
ceres::Problem &problem)
{
for (int k = 0; k < targetVertexIndex.size(); k++)
{
const int fineIndex = targetVertexIndex[k];
const std::vector<IndexWeight> & parents = vertexParents[fineIndex];
const Eigen::Vector3f referencePosition = referenceVertexPosition[k];
int numNodes = int(parents.size());
std::vector<double*> parameter_blocks(numNodes * 2); // rotation and translation
std::vector<Eigen::Vector3f> diff(numNodes);
std::vector<Eigen::Vector3f> nPos(numNodes);
std::vector<double> nWeight(numNodes);
for (int i = 0; i < numNodes; i++)
{
int nodeIdx = parents[i].index;
double nodeWeight = parents[i].weight;
diff[i] = referencePosition - nodeReferencePosition[nodeIdx];
int baseIdx = nodeIdx*numVariablesPerNode;
parameter_blocks[i * 2] = &(vars[baseIdx]); // rotation
parameter_blocks[i * 2 + 1] = &(vars[baseIdx + 3]); // translation
nPos[i] = nodeReferencePosition[nodeIdx];
nWeight[i] = nodeWeight;
}
FitCostFunctor* fitCostFunctor = new FitCostFunctor(numNodes, diff, nPos, nWeight, fittingWeight[k], targetVertexPosition[k], targetVertexNormal[k]);
FitCostFunctor::CostFunction* cost_function = new FitCostFunctor::CostFunction(fitCostFunctor);
for (int i = 0; i < numNodes; i++)
{
cost_function->AddParameterBlock(3); //for rotations
cost_function->AddParameterBlock(3); //for translations
}
cost_function->SetNumResiduals(FitCostFunctor::c_numResiduals);
problem.AddResidualBlock(cost_function, NULL, parameter_blocks);
}
}
double ComputeRigidityError(const std::vector<std::vector<int>> & neighbourhoods, const std::vector<Eigen::Vector3f> & nodeReferencePosition, double rigidityWeight,const Eigen::VectorXd &vars){
double cumRigiditySquaredError = 0;
for (int j = 0; j < neighbourhoods.size(); j++)
{
Eigen::Vector3f refPosCurrent = nodeReferencePosition[j];
for (int n = 0; n < neighbourhoods[j].size(); n++)
{
int k = neighbourhoods[j][n];
Eigen::Vector3f refPosNeighbour = nodeReferencePosition[k];
int jVariableOffset = int(j*numVariablesPerNode);
int kVariableOffset = int(k*numVariablesPerNode);
Eigen::Vector3f angleAxisj(vars[jVariableOffset], vars[jVariableOffset + 1], vars[jVariableOffset + 2]);
Eigen::Matrix3f rotationj;
ceres::AngleAxisToRotationMatrix((float *)&angleAxisj, (float *)&rotationj);
Eigen::Vector3f translationj(vars[jVariableOffset + 3], vars[jVariableOffset + 4], vars[jVariableOffset + 5]);
Eigen::Vector3f translationk(vars[kVariableOffset + 3], vars[kVariableOffset + 4], vars[kVariableOffset + 5]);
Eigen::Vector3f residual = rotationj*(refPosNeighbour - refPosCurrent) + translationj + refPosCurrent - (translationk + refPosNeighbour);
cumRigiditySquaredError += residual.squaredNorm();
}
}
return 0.5*cumRigiditySquaredError*rigidityWeight;
}
double ComputeFitError(const std::vector<Eigen::Vector3f> &nodeReferencePosition, const std::vector<std::vector<IndexWeight>> &vertexParents, const std::vector<double> & fittingWeight, const std::vector<int> &targetVertexIndex,
const std::vector<Eigen::Vector3f> &targetVertexPosition, const std::vector<Eigen::Vector3f> &referenceVertexPosition, const std::vector<Eigen::Vector3f> &targetVertexNormal, const Eigen::VectorXd &vars)
{
double cumDistanceSquaredError = 0;
double cumNormalSquaredError = 0;
for (int k = 0; k < targetVertexIndex.size(); k++)
{
const int fineIndex = targetVertexIndex[k];
const std::vector<IndexWeight> & parents = vertexParents[fineIndex];
const Eigen::Vector3f referencePosition = referenceVertexPosition[k];
Eigen::Vector3f predictedPosition = Eigen::Vector3f::Zero();
for (int i = 0; i < parents.size(); i++)
{
int variableOffset = parents[i].index*numVariablesPerNode;
Eigen::Vector3f angleAxis(vars[variableOffset], vars[variableOffset + 1], vars[variableOffset + 2]);
Eigen::Matrix3f rotation;
ceres::AngleAxisToRotationMatrix((float *)&angleAxis, (float *)&rotation);
Eigen::Vector3f translation(vars[variableOffset + 3], vars[variableOffset + 4], vars[variableOffset + 5]);
Eigen::Vector3f refNodePosition = nodeReferencePosition[parents[i].index];
predictedPosition += (rotation*(referencePosition - refNodePosition) + translation + refNodePosition)*parents[i].weight;
}
Eigen::Vector3f residual = predictedPosition - targetVertexPosition[k];
cumDistanceSquaredError += residual.squaredNorm() * 0.316 * 0.316;
double normalResidual = residual.dot(targetVertexNormal[k]);
cumNormalSquaredError += normalResidual*normalResidual;
cumDistanceSquaredError *= (fittingWeight[k] * fittingWeight[k]);
cumNormalSquaredError *= (fittingWeight[k] * fittingWeight[k]);
}
return 0.5*(cumDistanceSquaredError + cumNormalSquaredError);
}
double ComputeFixedNodeError(const std::vector<bool> & fixedNodes, double fixedWeight, const Eigen::VectorXd &vars){
double cumSquaredError = 0;
for (int j = 0; j < fixedNodes.size(); j++)
{
if (fixedNodes[j]){
int variableOffset = int(j*numVariablesPerNode);
for (int k = 0; k < numVariablesPerNode; k++) cumSquaredError += (vars[variableOffset + k] * vars[variableOffset + k]);
}
}
return 0.5*cumSquaredError*fixedWeight;
}
void SolveDeformation(const std::vector<bool> & fixedNodes, const std::vector<Eigen::Vector3f> & nodeReferencePosition, const std::vector<std::vector<int>> & neighbourhoods, const std::vector<std::vector<IndexWeight>> &vertexParents, std::vector<RigidTransformation> & transformations,
const double fixedWeight, const double rigidityWeight, const std::vector<double> & fittingWeight, const std::vector<int> &targetVertexIndex, const std::vector<Eigen::Vector3f> &targetVertexPosition, const std::vector<Eigen::Vector3f> &referenceVertexPosition, const std::vector<Eigen::Vector3f> &targetVertexNormal, bool verbose = false){
int numNodes = nodeReferencePosition.size();
if (verbose)printf("Num nodes %d \n", numNodes);
ceres::Problem problem;
Eigen::VectorXd vars;
vars.resize(numVariablesPerNode*numNodes);
for (int i = 0; i < transformations.size(); i++){
Eigen::Vector3f angleAxis;
Eigen::Matrix3f rotation = transformations[i].rotation;
Eigen::Vector3f translation = transformations[i].translation;
ceres::RotationMatrixToAngleAxis((float *)&rotation, (float *)&angleAxis);
vars[i*numVariablesPerNode] = angleAxis[0];
vars[i*numVariablesPerNode + 1] = angleAxis[1];
vars[i*numVariablesPerNode + 2] = angleAxis[2];
vars[i*numVariablesPerNode + 3] = translation[0];
vars[i*numVariablesPerNode + 4] = translation[1];
vars[i*numVariablesPerNode + 5] = translation[2];
}
if (verbose){
double rigidityError = ComputeRigidityError(neighbourhoods, nodeReferencePosition, rigidityWeight, vars);
double fittingError = ComputeFitError(nodeReferencePosition, vertexParents, fittingWeight, targetVertexIndex, targetVertexPosition, referenceVertexPosition, targetVertexNormal, vars);
double fixedError = ComputeFixedNodeError(fixedNodes, fixedWeight, vars);
printf("Initial Error %g : Rigid %g - Fit %g - Fixed %g \n", rigidityError + fittingError + fixedError, rigidityError, fittingError, fixedError);
}
if (fixedNodes.size() != transformations.size()){
printf("Unexpected node count! \n");
}
SetRigidityResiduals(neighbourhoods, nodeReferencePosition, rigidityWeight, vars, problem);
SetFixedNodeRotationResiduals(fixedNodes, fixedWeight, vars, problem);
SetFixedNodeTranslationResiduals(fixedNodes, fixedWeight, vars, problem);
SetFitResiduals(nodeReferencePosition, vertexParents, fittingWeight, targetVertexIndex, targetVertexPosition, referenceVertexPosition, targetVertexNormal, vars, problem);
ceres::Solver::Options options;
options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;
options.num_threads = omp_get_num_procs(); // Use OpenMP to parallelize
options.num_linear_solver_threads = omp_get_num_procs(); // Use OpenMP to parallelize
options.minimizer_progress_to_stdout = false;
options.function_tolerance = 5e-3;
ceres::Solver::Summary summary;
ceres::Solve(options, &problem, &summary);
std::string report = summary.BriefReport();
const char * _report = report.c_str();
if (verbose)printf("Ceres Summary : %s \n", _report);
if (verbose){
double rigidityError = ComputeRigidityError(neighbourhoods, nodeReferencePosition, rigidityWeight, vars);
double fittingError = ComputeFitError(nodeReferencePosition, vertexParents, fittingWeight, targetVertexIndex, targetVertexPosition, referenceVertexPosition, targetVertexNormal, vars);
double fixedError = ComputeFixedNodeError(fixedNodes, fixedWeight, vars);
printf("Initial Error %g : Rigid %g - Fit %g - Fixed %g \n", rigidityError + fittingError + fixedError, rigidityError, fittingError, fixedError);
}
for (int i = 0; i < transformations.size(); i++){
Eigen::Vector3f angleAxis(vars[i*numVariablesPerNode], vars[i*numVariablesPerNode + 1], vars[i*numVariablesPerNode + 2]);
Eigen::Matrix3f rotation;
Eigen::Vector3f translation(vars[i*numVariablesPerNode + 3], vars[i*numVariablesPerNode + 4], vars[i*numVariablesPerNode + 5]);
ceres::AngleAxisToRotationMatrix((float *)&angleAxis,(float *)&rotation);
transformations[i].rotation = rotation;
transformations[i].translation = translation;
}
}
void RigidAlignment(const std::vector<Eigen::Vector3f> & sourcePts, const std::vector<Eigen::Vector3f> & targetPts, const std::vector<float> & weights, Eigen::Vector3f & optimalTranslation, Eigen::Matrix3f & optimalRotation)
{
if (sourcePts.size() != targetPts.size()) printf("Target points does not match source points! \n");
int vCount = (int)sourcePts.size();
Eigen::Vector3f sCentroid(0.f, 0.f, 0.f);
Eigen::Vector3f tCentroid(0.f, 0.f, 0.f);
float cumWeight = 0.f;
for (int i = 0; i < vCount; i++){
float weight = weights[i];
sCentroid += sourcePts[i] * weight;
tCentroid += targetPts[i] * weight;
cumWeight += weight;
}
sCentroid /= cumWeight;
tCentroid /= cumWeight;
Eigen::Matrix3f varianceMatrix = Eigen::Matrix3f::Zero();
for (int i = 0; i < vCount; i++){
Eigen::Vector3f sourceVector = sourcePts[i] - sCentroid;
Eigen::Vector3f targetVector = targetPts[i] - tCentroid;
for (int k = 0; k < 3; k++) for (int l = 0; l < 3; l++) varianceMatrix(k,l) += weights[i] * sourceVector[k] * targetVector[l];
}
Eigen::JacobiSVD<Eigen::Matrix3f> _svd(varianceMatrix, Eigen::ComputeFullU | Eigen::ComputeFullV);
Eigen::Matrix3f U = _svd.matrixU();
Eigen::Matrix3f V = _svd.matrixV();
if (U.determinant()*V.determinant() < 0.f) for (int k = 0; k < 3; k++) U(k, 2) *= -1.f;
Eigen::Matrix3f U_transpose = U.transpose();
optimalRotation = V*U_transpose;
optimalTranslation = tCentroid - optimalRotation*sCentroid;
}
//TODO: Make sure each node has at least 4 sons to ensure rigid transformation is well defined?
void ProjectDeformation(const std::vector<Eigen::Vector3f> & vertexReferencePositions, const std::vector<Eigen::Vector3f> & vertexDeformedPositions, const std::vector<Eigen::Vector3f> & nodeReferencePositions, const std::vector<std::vector<IndexWeight>> &nodeSons, std::vector<RigidTransformation> & transformations){
int threads = omp_get_num_procs();
#pragma omp parallel for num_threads( threads )
for (int i = 0; i < nodeSons.size(); i++){
const Eigen::Vector3f nodePosition = nodeReferencePositions[i];
const std::vector<IndexWeight> & currentSons = nodeSons[i];
std::vector<Eigen::Vector3f> sonReferencePositions(currentSons.size());
std::vector<Eigen::Vector3f> sonTargetPositions(currentSons.size());
std::vector<float> sonsWeights(currentSons.size());
for (int j = 0; j < currentSons.size(); j++){
sonReferencePositions[j] = vertexReferencePositions[currentSons[j].index] - nodePosition;
sonTargetPositions[j] = vertexDeformedPositions[currentSons[j].index] - nodePosition;
sonsWeights[j] = currentSons[j].weight;
}
RigidAlignment(sonReferencePositions, sonTargetPositions, sonsWeights, transformations[i].translation, transformations[i].rotation);
}
}
void HierarchicalDeformationSolver(HierarchicalModel & hierarchy, const double fixedWeight, const double rigidityWeight, const std::vector<double> & fittingWeight, std::vector<Eigen::Vector3f> &vertexPosition, const std::vector<int> &targetVertexIndex, const std::vector<Eigen::Vector3f> &targetVertexPosition, const std::vector<Eigen::Vector3f> &referenceVertexPosition, const std::vector<Eigen::Vector3f> &targetVertexNormal, const int finestLevelSoved, bool verbose = false){
std::vector<Eigen::Vector3f> transformedPositions = vertexPosition;
double cummulativeTime = 0;
for (int l = hierarchy.numLevels - 1; l >= finestLevelSoved; l--){
if (verbose)printf("Level %d ... \n", l);
clock_t startTimer = clock();
ProjectDeformation(hierarchy.hierarchyReferencePosition[0], transformedPositions, hierarchy.hierarchyReferencePosition[l], hierarchy.hierarchicalSons[l], hierarchy.hierarchicalTransformation[l]);
SolveDeformation(hierarchy.hierarchicalFixedNodes[l], hierarchy.hierarchyReferencePosition[l], hierarchy.hierarchyNeighbourhoods[l], hierarchy.hierarchicalParents[l], hierarchy.hierarchicalTransformation[l], fixedWeight, rigidityWeight / hierarchy.hierarchicalSquaredEdgeLenght[l], fittingWeight, targetVertexIndex, targetVertexPosition, referenceVertexPosition, targetVertexNormal, verbose);
TransformModel(hierarchy.hierarchyReferencePosition[0], hierarchy.hierarchicalTransformation[l], hierarchy.hierarchicalParents[l], hierarchy.hierarchyFineIndices[l], transformedPositions);
double partialTime = clock() - startTimer;
cummulativeTime += partialTime;
if (verbose)printf("Time %.4f \n", double(partialTime) / CLOCKS_PER_SEC);
}
vertexPosition = transformedPositions;
if (verbose)printf("Total Time %.4f \n", double(cummulativeTime) / CLOCKS_PER_SEC);
}
#endif //DEFORMATION_SOLVER_INCLUDED |
tmp_par.c | #include <stdio.h>
#include <omp.h>
// #include <omp.h>
// #include <stdio.h>
// #include <stdlib.h>
long long num_passos = 10000000000;
// long long num_passos = 10000000000;
double passo;
int main(int argc, char** argv){
long long i;
double x, pi, soma=0.0;
passo = 1.0/(double)num_passos;
#pragma omp parallel for private(i, passo, soma, x)
for(i=0; i < num_passos; i++){
x = (i + 0.5)*passo;
soma += 4.0/(1.0 + x*x);
}
pi = soma*passo;
printf("O valor de PI é: %f\n", pi);
return 0;
}
|
statistic.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC %
% SS T A A T I SS T I C %
% SSS T AAAAA T I SSS T I C %
% SS T A A T I SS T I C %
% SSSSS T A A T IIIII SSSSS T IIIII CCCC %
% %
% %
% MagickCore Image Methods %
% %
% Software Design %
% John Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2009 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/property.h"
#include "magick/animate.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/cache-private.h"
#include "magick/cache-view.h"
#include "magick/client.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/composite-private.h"
#include "magick/compress.h"
#include "magick/constitute.h"
#include "magick/deprecate.h"
#include "magick/display.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/list.h"
#include "magick/image-private.h"
#include "magick/magic.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/option.h"
#include "magick/paint.h"
#include "magick/pixel-private.h"
#include "magick/profile.h"
#include "magick/quantize.h"
#include "magick/random_.h"
#include "magick/segment.h"
#include "magick/semaphore.h"
#include "magick/signature-private.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/timer.h"
#include "magick/utility.h"
#include "magick/version.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e B o u n d i n g B o x %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageBoundingBox() returns the bounding box of an image canvas.
%
% The format of the GetImageBoundingBox method is:
%
% RectangleInfo GetImageBoundingBox(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o bounds: Method GetImageBoundingBox returns the bounding box of an
% image canvas.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport RectangleInfo GetImageBoundingBox(const Image *image,
ExceptionInfo *exception)
{
long
y;
MagickBooleanType
status;
MagickPixelPacket
target[3],
zero;
RectangleInfo
bounds;
register const PixelPacket
*p;
ViewInfo
*image_view;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
bounds.width=0;
bounds.height=0;
bounds.x=(long) image->columns;
bounds.y=(long) image->rows;
GetMagickPixelPacket(image,&target[0]);
image_view=AcquireCacheView(image);
p=GetCacheViewVirtualPixels(image_view,0,0,1,1,exception);
if (p == (const PixelPacket *) NULL)
{
image_view=DestroyCacheView(image_view);
return(bounds);
}
SetMagickPixelPacket(image,p,GetCacheViewAuthenticIndexQueue(image_view),
&target[0]);
GetMagickPixelPacket(image,&target[1]);
p=GetCacheViewVirtualPixels(image_view,(long) image->columns-1,0,1,1,
exception);
SetMagickPixelPacket(image,p,GetCacheViewAuthenticIndexQueue(image_view),
&target[1]);
GetMagickPixelPacket(image,&target[2]);
p=GetCacheViewVirtualPixels(image_view,0,(long) image->rows-1,1,1,
exception);
SetMagickPixelPacket(image,p,GetCacheViewAuthenticIndexQueue(image_view),
&target[2]);
status=MagickTrue;
GetMagickPixelPacket(image,&zero);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(status)
#endif
for (y=0; y < (long) image->rows; y++)
{
MagickPixelPacket
pixel;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register long
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
pixel=zero;
for (x=0; x < (long) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
if ((x < bounds.x) &&
(IsMagickColorSimilar(&pixel,&target[0]) == MagickFalse))
bounds.x=x;
if ((x > (long) bounds.width) &&
(IsMagickColorSimilar(&pixel,&target[1]) == MagickFalse))
bounds.width=(unsigned long) x;
if ((y < bounds.y) &&
(IsMagickColorSimilar(&pixel,&target[0]) == MagickFalse))
bounds.y=y;
if ((y > (long) bounds.height) &&
(IsMagickColorSimilar(&pixel,&target[2]) == MagickFalse))
bounds.height=(unsigned long) y;
p++;
}
}
image_view=DestroyCacheView(image_view);
if ((bounds.width == 0) || (bounds.height == 0))
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"GeometryDoesNotContainImage","`%s'",image->filename);
else
{
bounds.width-=(bounds.x-1);
bounds.height-=(bounds.y-1);
}
return(bounds);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l D e p t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelDepth() returns the depth of a particular image channel.
%
% The format of the GetImageChannelDepth method is:
%
% unsigned long GetImageDepth(const Image *image,ExceptionInfo *exception)
% unsigned long GetImageChannelDepth(const Image *image,
% const ChannelType channel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport unsigned long GetImageDepth(const Image *image,
ExceptionInfo *exception)
{
return(GetImageChannelDepth(image,AllChannels,exception));
}
MagickExport unsigned long GetImageChannelDepth(const Image *image,
const ChannelType channel,ExceptionInfo *exception)
{
long
y;
MagickBooleanType
status;
register long
id;
unsigned long
*current_depth,
depth,
number_threads;
ViewInfo
*image_view;
/*
Compute image depth.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
number_threads=GetPixelCacheMaximumThreads();
current_depth=(unsigned long *) AcquireQuantumMemory(number_threads,
sizeof(*current_depth));
if (current_depth == (unsigned long *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
status=MagickTrue;
for (id=0; id < (long) number_threads; id++)
current_depth[id]=1;
if ((image->storage_class == PseudoClass) && (image->matte == MagickFalse))
{
register const PixelPacket
*p;
register long
i;
p=image->colormap;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(status)
#endif
for (i=0; i < (long) image->colors; i++)
{
if (status == MagickFalse)
continue;
id=GetPixelCacheThreadId();
while (current_depth[id] < MAGICKCORE_QUANTUM_DEPTH)
{
MagickStatusType
status;
QuantumAny
scale;
status=0;
scale=GetQuantumScale(current_depth[id]);
if ((channel & RedChannel) != 0)
status|=p->red != ScaleAnyToQuantum(ScaleQuantumToAny(p->red,
current_depth[id],scale),current_depth[id],scale);
if ((channel & GreenChannel) != 0)
status|=p->green != ScaleAnyToQuantum(ScaleQuantumToAny(p->green,
current_depth[id],scale),current_depth[id],scale);
if ((channel & BlueChannel) != 0)
status|=p->blue != ScaleAnyToQuantum(ScaleQuantumToAny(p->blue,
current_depth[id],scale),current_depth[id],scale);
if (status == 0)
break;
current_depth[id]++;
}
p++;
}
depth=current_depth[0];
for (id=1; id < (long) number_threads; id++)
if (depth < current_depth[id])
depth=current_depth[id];
current_depth=(unsigned long *) RelinquishMagickMemory(current_depth);
return(depth);
}
image_view=AcquireCacheView(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(status)
#endif
for (y=0; y < (long) image->rows; y++)
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register long
id,
x;
if (status == MagickFalse)
continue;
id=GetPixelCacheThreadId();
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
continue;
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (long) image->columns; x++)
{
while (current_depth[id] < MAGICKCORE_QUANTUM_DEPTH)
{
MagickStatusType
status;
QuantumAny
scale;
status=0;
scale=GetQuantumScale(current_depth[id]);
if ((channel & RedChannel) != 0)
status|=p->red != ScaleAnyToQuantum(ScaleQuantumToAny(p->red,
current_depth[id],scale),current_depth[id],scale);
if ((channel & GreenChannel) != 0)
status|=p->green != ScaleAnyToQuantum(ScaleQuantumToAny(p->green,
current_depth[id],scale),current_depth[id],scale);
if ((channel & BlueChannel) != 0)
status|=p->blue != ScaleAnyToQuantum(ScaleQuantumToAny(p->blue,
current_depth[id],scale),current_depth[id],scale);
if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse))
status|=p->opacity != ScaleAnyToQuantum(ScaleQuantumToAny(p->opacity,
current_depth[id],scale),current_depth[id],scale);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
status|=indexes[x] != ScaleAnyToQuantum(ScaleQuantumToAny(indexes[x],
current_depth[id],scale),current_depth[id],scale);
if (status == 0)
break;
current_depth[id]++;
}
p++;
}
if (current_depth[id] == MAGICKCORE_QUANTUM_DEPTH)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
depth=current_depth[0];
for (id=1; id < (long) number_threads; id++)
if (depth < current_depth[id])
depth=current_depth[id];
current_depth=(unsigned long *) RelinquishMagickMemory(current_depth);
return(depth);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e C h a n n e l E x t r e m a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelExtrema() returns the extrema of one or more image channels.
%
% The format of the GetImageChannelExtrema method is:
%
% MagickBooleanType GetImageChannelExtrema(const Image *image,
% const ChannelType channel,unsigned long *minima,unsigned long *maxima,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o minima: the minimum value in the channel.
%
% o maxima: the maximum value in the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageExtrema(const Image *image,
unsigned long *minima,unsigned long *maxima,ExceptionInfo *exception)
{
return(GetImageChannelExtrema(image,AllChannels,minima,maxima,exception));
}
MagickExport MagickBooleanType GetImageChannelExtrema(const Image *image,
const ChannelType channel,unsigned long *minima,unsigned long *maxima,
ExceptionInfo *exception)
{
double
max,
min;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=GetImageChannelRange(image,channel,&min,&max,exception);
*minima=(unsigned long) (min+0.5);
*maxima=(unsigned long) (max+0.5);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l M e a n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelMean() returns the mean and standard deviation of one or more
% image channels.
%
% The format of the GetImageChannelMean method is:
%
% MagickBooleanType GetImageChannelMean(const Image *image,
% const ChannelType channel,double *mean,double *standard_deviation,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o mean: the average value in the channel.
%
% o standard_deviation: the standard deviation of the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean,
double *standard_deviation,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=GetImageChannelMean(image,AllChannels,mean,standard_deviation,
exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelMean(const Image *image,
const ChannelType channel,double *mean,double *standard_deviation,
ExceptionInfo *exception)
{
#define PixelSquared(x) ((x)*(x))
double
area;
long
y;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register long
x;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
*mean=0.0;
*standard_deviation=0.0;
area=0.0;
for (y=0; y < (long) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (long) image->columns; x++)
{
if ((channel & RedChannel) != 0)
{
*mean+=p->red;
*standard_deviation+=(double) p->red*p->red;
area++;
}
if ((channel & GreenChannel) != 0)
{
*mean+=p->green;
*standard_deviation+=(double) p->green*p->green;
area++;
}
if ((channel & BlueChannel) != 0)
{
*mean+=p->blue;
*standard_deviation+=(double) p->blue*p->blue;
area++;
}
if ((channel & OpacityChannel) != 0)
{
*mean+=p->opacity;
*standard_deviation+=(double) p->opacity*p->opacity;
area++;
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
*mean+=indexes[x];
*standard_deviation+=(double) indexes[x]*indexes[x];
area++;
}
p++;
}
}
if (y < (long) image->rows)
return(MagickFalse);
if (area != 0)
{
*mean/=area;
*standard_deviation/=area;
}
*standard_deviation=sqrt(*standard_deviation-(*mean*(*mean)));
return(y == (long) image->rows ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l R a n g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelRange() returns the range of one or more image channels.
%
% The format of the GetImageChannelRange method is:
%
% MagickBooleanType GetImageChannelRange(const Image *image,
% const ChannelType channel,double *minima,double *maxima,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o minima: the minimum value in the channel.
%
% o maxima: the maximum value in the channel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageRange(const Image *image,
double *minima,double *maxima,ExceptionInfo *exception)
{
return(GetImageChannelRange(image,AllChannels,minima,maxima,exception));
}
MagickExport MagickBooleanType GetImageChannelRange(const Image *image,
const ChannelType channel,double *minima,double *maxima,
ExceptionInfo *exception)
{
long
y;
MagickPixelPacket
pixel;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register long
x;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
*maxima=(-1.0E-37);
*minima=1.0E+37;
GetMagickPixelPacket(image,&pixel);
for (y=0; y < (long) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (long) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
if ((channel & RedChannel) != 0)
{
if (pixel.red < *minima)
*minima=(double) pixel.red;
if (pixel.red > *maxima)
*maxima=(double) pixel.red;
}
if ((channel & GreenChannel) != 0)
{
if (pixel.green < *minima)
*minima=(double) pixel.green;
if (pixel.green > *maxima)
*maxima=(double) pixel.green;
}
if ((channel & BlueChannel) != 0)
{
if (pixel.blue < *minima)
*minima=(double) pixel.blue;
if (pixel.blue > *maxima)
*maxima=(double) pixel.blue;
}
if ((channel & OpacityChannel) != 0)
{
if (pixel.opacity < *minima)
*minima=(double) pixel.opacity;
if (pixel.opacity > *maxima)
*maxima=(double) pixel.opacity;
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
if ((double) indexes[x] < *minima)
*minima=(double) indexes[x];
if ((double) indexes[x] > *maxima)
*maxima=(double) indexes[x];
}
p++;
}
}
return(y == (long) image->rows ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l S t a t i s t i c s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelStatistics() returns statistics for each channel in the
% image. The statistics incude the channel depth, its minima, maxima, mean,
% and the standard deviation. You can access the red channel mean, for
% example, like this:
%
% channel_statistics=GetImageChannelStatistics(image,excepton);
% red_mean=channel_statistics[RedChannel].mean;
%
% Use MagickRelinquishMemory() to free the statistics buffer.
%
% The format of the GetImageChannelStatistics method is:
%
% ChannelStatistics *GetImageChannelStatistics(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.
%
*/
static inline double MagickMax(const double x,const double y)
{
if (x > y)
return(x);
return(y);
}
static inline double MagickMin(const double x,const double y)
{
if (x < y)
return(x);
return(y);
}
MagickExport ChannelStatistics *GetImageChannelStatistics(const Image *image,
ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
double
area;
long
y;
MagickStatusType
status;
QuantumAny
scale;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register long
i,
x;
size_t
length;
unsigned long
channels,
depth;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=AllChannels+1UL;
channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(length,
sizeof(*channel_statistics));
if (channel_statistics == (ChannelStatistics *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) ResetMagickMemory(channel_statistics,0,length*
sizeof(*channel_statistics));
for (i=0; i <= AllChannels; i++)
{
channel_statistics[i].depth=1;
channel_statistics[i].maxima=(-1.0E-37);
channel_statistics[i].minima=1.0E+37;
channel_statistics[i].mean=0.0;
channel_statistics[i].standard_deviation=0.0;
}
y=(long) image->rows;
for (y=0; y < (long) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (long) image->columns; )
{
if (channel_statistics[RedChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[RedChannel].depth;
scale=GetQuantumScale(depth);
status=p->red != ScaleAnyToQuantum(ScaleQuantumToAny(p->red,depth,
scale),depth,scale) ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
channel_statistics[RedChannel].depth++;
continue;
}
}
if (channel_statistics[GreenChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[GreenChannel].depth;
scale=GetQuantumScale(depth);
status=p->green != ScaleAnyToQuantum(ScaleQuantumToAny(p->green,
depth,scale),depth,scale) ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
channel_statistics[GreenChannel].depth++;
continue;
}
}
if (channel_statistics[BlueChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[BlueChannel].depth;
scale=GetQuantumScale(depth);
status=p->blue != ScaleAnyToQuantum(ScaleQuantumToAny(p->blue,
depth,scale),depth,scale) ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
channel_statistics[BlueChannel].depth++;
continue;
}
}
if (channel_statistics[OpacityChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[OpacityChannel].depth;
scale=GetQuantumScale(depth);
status=p->opacity != ScaleAnyToQuantum(ScaleQuantumToAny(p->opacity,
depth,scale),depth,scale) ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
channel_statistics[OpacityChannel].depth++;
continue;
}
}
if (image->colorspace == CMYKColorspace)
{
if (channel_statistics[BlackChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[BlackChannel].depth;
scale=GetQuantumScale(depth);
status=indexes[x] != ScaleAnyToQuantum(ScaleQuantumToAny(
indexes[x],depth,scale),depth,scale) ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
channel_statistics[BlackChannel].depth++;
continue;
}
}
}
if ((double) p->red < channel_statistics[RedChannel].minima)
channel_statistics[RedChannel].minima=(double) p->red;
if ((double) p->red > channel_statistics[RedChannel].maxima)
channel_statistics[RedChannel].maxima=(double) p->red;
channel_statistics[RedChannel].mean+=p->red;
channel_statistics[RedChannel].standard_deviation+=(double)
p->red*p->red;
if ((double) p->green < channel_statistics[GreenChannel].minima)
channel_statistics[GreenChannel].minima=(double) p->green;
if ((double) p->green > channel_statistics[GreenChannel].maxima)
channel_statistics[GreenChannel].maxima=(double) p->green;
channel_statistics[GreenChannel].mean+=p->green;
channel_statistics[GreenChannel].standard_deviation+=(double)
p->green*p->green;
if ((double) p->blue < channel_statistics[BlueChannel].minima)
channel_statistics[BlueChannel].minima=(double) p->blue;
if ((double) p->blue > channel_statistics[BlueChannel].maxima)
channel_statistics[BlueChannel].maxima=(double) p->blue;
channel_statistics[BlueChannel].mean+=p->blue;
channel_statistics[BlueChannel].standard_deviation+=(double)
p->blue*p->blue;
if ((double) p->opacity < channel_statistics[OpacityChannel].minima)
channel_statistics[OpacityChannel].minima=(double) p->opacity;
if ((double) p->opacity > channel_statistics[OpacityChannel].maxima)
channel_statistics[OpacityChannel].maxima=(double) p->opacity;
channel_statistics[OpacityChannel].mean+=p->opacity;
channel_statistics[OpacityChannel].standard_deviation+=(double)
p->opacity*p->opacity;
if (image->colorspace == CMYKColorspace)
{
if ((double) indexes[x] < channel_statistics[BlackChannel].minima)
channel_statistics[BlackChannel].minima=(double) indexes[x];
if ((double) indexes[x] > channel_statistics[BlackChannel].maxima)
channel_statistics[BlackChannel].maxima=(double) indexes[x];
channel_statistics[BlackChannel].mean+=indexes[x];
channel_statistics[BlackChannel].standard_deviation+=(double)
indexes[x]*indexes[x];
}
x++;
p++;
}
}
area=(double) image->columns*image->rows;
for (i=0; i < AllChannels; i++)
{
channel_statistics[i].mean/=area;
channel_statistics[i].standard_deviation/=area;
}
for (i=0; i < AllChannels; i++)
{
channel_statistics[AllChannels].depth=(unsigned long) MagickMax((double)
channel_statistics[AllChannels].depth,(double)
channel_statistics[i].depth);
channel_statistics[AllChannels].minima=MagickMin(
channel_statistics[AllChannels].minima,channel_statistics[i].minima);
channel_statistics[AllChannels].maxima=MagickMax(
channel_statistics[AllChannels].maxima,channel_statistics[i].maxima);
channel_statistics[AllChannels].mean+=channel_statistics[i].mean;
channel_statistics[AllChannels].standard_deviation+=
channel_statistics[i].standard_deviation;
}
channels=4;
if (image->colorspace == CMYKColorspace)
channels++;
channel_statistics[AllChannels].mean/=channels;
channel_statistics[AllChannels].standard_deviation/=channels;
for (i=0; i <= AllChannels; i++)
channel_statistics[i].standard_deviation=sqrt(
channel_statistics[i].standard_deviation-
(channel_statistics[i].mean*channel_statistics[i].mean));
return(channel_statistics);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e Q u a n t u m D e p t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageQuantumDepth() returns the depth of the image rounded to a legal
% quantum depth: 8, 16, or 32.
%
% The format of the GetImageQuantumDepth method is:
%
% unsigned long GetImageQuantumDepth(const Image *image,
% const MagickBooleanType constrain)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o constrain: A value other than MagickFalse, constrains the depth to
% a maximum of MAGICKCORE_QUANTUM_DEPTH.
%
*/
MagickExport unsigned long GetImageQuantumDepth(const Image *image,
const MagickBooleanType constrain)
{
unsigned long
depth;
depth=image->depth;
if (depth <= 8)
depth=8;
else
if (depth <= 16)
depth=16;
else
if (depth <= 32)
depth=32;
else
if (depth <= 64)
depth=64;
if (constrain != MagickFalse)
depth=(unsigned long) MagickMin((double) depth,(double)
MAGICKCORE_QUANTUM_DEPTH);
return(depth);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C h a n n e l D e p t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageChannelDepth() sets the depth of the image.
%
% The format of the SetImageChannelDepth method is:
%
% MagickBooleanType SetImageDepth(Image *image,const unsigned long depth)
% MagickBooleanType SetImageChannelDepth(Image *image,
% const ChannelType channel,const unsigned long depth)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o depth: the image depth.
%
*/
MagickExport MagickBooleanType SetImageDepth(Image *image,
const unsigned long depth)
{
return(SetImageChannelDepth(image,AllChannels,depth));
}
MagickExport MagickBooleanType SetImageChannelDepth(Image *image,
const ChannelType channel,const unsigned long depth)
{
ExceptionInfo
*exception;
long
y;
MagickBooleanType
status;
QuantumAny
scale;
ViewInfo
*image_view;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
if (GetImageDepth(image,&image->exception) <= (unsigned long)
MagickMin((double) depth,(double) MAGICKCORE_QUANTUM_DEPTH))
{
image->depth=depth;
return(MagickTrue);
}
/*
Scale pixels to desired depth.
*/
status=MagickTrue;
scale=GetQuantumScale(depth);
exception=(&image->exception);
image_view=AcquireCacheView(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(status)
#endif
for (y=0; y < (long) image->rows; y++)
{
register IndexPacket
*indexes;
register long
x;
register PixelPacket
*q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (long) image->columns; x++)
{
if ((channel & RedChannel) != 0)
q->red=ScaleAnyToQuantum(ScaleQuantumToAny(q->red,depth,scale),depth,
scale);
if ((channel & GreenChannel) != 0)
q->green=ScaleAnyToQuantum(ScaleQuantumToAny(q->green,depth,scale),
depth,scale);
if ((channel & BlueChannel) != 0)
q->blue=ScaleAnyToQuantum(ScaleQuantumToAny(q->blue,depth,scale),
depth,scale);
if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse))
q->opacity=ScaleAnyToQuantum(ScaleQuantumToAny(q->opacity,depth,scale),
depth,scale);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
indexes[x]=ScaleAnyToQuantum(ScaleQuantumToAny(indexes[x],depth,scale),
depth,scale);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
{
status=MagickFalse;
continue;
}
}
image_view=DestroyCacheView(image_view);
if (image->storage_class == PseudoClass)
{
QuantumAny
scale;
register long
i;
register PixelPacket
*p;
p=image->colormap;
scale=GetQuantumScale(depth);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,4) shared(status)
#endif
for (i=0; i < (long) image->colors; i++)
{
if ((channel & RedChannel) != 0)
p->red=ScaleAnyToQuantum(ScaleQuantumToAny(p->red,depth,
scale),depth,scale);
if ((channel & GreenChannel) != 0)
p->green=ScaleAnyToQuantum(ScaleQuantumToAny(p->green,depth,
scale),depth,scale);
if ((channel & BlueChannel) != 0)
p->blue=ScaleAnyToQuantum(ScaleQuantumToAny(p->blue,depth,
scale),depth,scale);
if ((channel & OpacityChannel) != 0)
p->opacity=ScaleAnyToQuantum(ScaleQuantumToAny(p->opacity,depth,
scale),depth,scale);
p++;
}
}
image->depth=depth;
return(status);
}
|
ast-dump-openmp-for.c | // RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s
void test_one(int x) {
#pragma omp for
for (int i = 0; i < x; i++)
;
}
void test_two(int x, int y) {
#pragma omp for
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
;
}
void test_three(int x, int y) {
#pragma omp for collapse(1)
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
;
}
void test_four(int x, int y) {
#pragma omp for collapse(2)
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
;
}
void test_five(int x, int y, int z) {
#pragma omp for collapse(2)
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
for (int i = 0; i < z; i++)
;
}
// CHECK: TranslationUnitDecl 0x{{.*}} <<invalid sloc>> <invalid sloc>
// CHECK: |-FunctionDecl 0x{{.*}} <{{.*}}ast-dump-openmp-for.c:3:1, line:7:1> line:3:6 test_one 'void (int)'
// CHECK-NEXT: | |-ParmVarDecl 0x{{.*}} <col:15, col:19> col:19 used x 'int'
// CHECK-NEXT: | `-CompoundStmt 0x{{.*}} <col:22, line:7:1>
// CHECK-NEXT: | `-OMPForDirective 0x{{.*}} <line:4:1, col:16>
// CHECK-NEXT: | `-CapturedStmt 0x{{.*}} <line:5:3, line:6:5>
// CHECK-NEXT: | |-CapturedDecl 0x{{.*}} <<invalid sloc>> <invalid sloc>
// CHECK-NEXT: | | |-ForStmt 0x{{.*}} <line:5:3, line:6:5>
// CHECK-NEXT: | | | |-DeclStmt 0x{{.*}} <line:5:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl 0x{{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral 0x{{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator 0x{{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr 0x{{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr 0x{{.*}} <col:19> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr 0x{{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:23> 'int' lvalue ParmVar 0x{{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator 0x{{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:26> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt 0x{{.*}} <line:6:5> openmp_structured_block
// CHECK-NEXT: | | |-ImplicitParamDecl 0x{{.*}} <line:4:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-for.c:4:1) *const restrict'
// CHECK-NEXT: | | `-VarDecl 0x{{.*}} <line:5:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral 0x{{.*}} <col:16> 'int' 0
// CHECK-NEXT: | `-DeclRefExpr 0x{{.*}} <col:3> 'int' lvalue ParmVar 0x{{.*}} 'x' 'int'
// CHECK-NEXT: |-FunctionDecl 0x{{.*}} <line:9:1, line:14:1> line:9:6 test_two 'void (int, int)'
// CHECK-NEXT: | |-ParmVarDecl 0x{{.*}} <col:15, col:19> col:19 used x 'int'
// CHECK-NEXT: | |-ParmVarDecl 0x{{.*}} <col:22, col:26> col:26 used y 'int'
// CHECK-NEXT: | `-CompoundStmt 0x{{.*}} <col:29, line:14:1>
// CHECK-NEXT: | `-OMPForDirective 0x{{.*}} <line:10:1, col:16>
// CHECK-NEXT: | `-CapturedStmt 0x{{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | |-CapturedDecl 0x{{.*}} <<invalid sloc>> <invalid sloc>
// CHECK-NEXT: | | |-ForStmt 0x{{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | |-DeclStmt 0x{{.*}} <line:11:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl 0x{{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral 0x{{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator 0x{{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr 0x{{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr 0x{{.*}} <col:19> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr 0x{{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:23> 'int' lvalue ParmVar 0x{{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator 0x{{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:26> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ForStmt 0x{{.*}} <line:12:5, line:13:7> openmp_structured_block
// CHECK-NEXT: | | | |-DeclStmt 0x{{.*}} <line:12:10, col:19>
// CHECK-NEXT: | | | | `-VarDecl 0x{{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral 0x{{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator 0x{{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr 0x{{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr 0x{{.*}} <col:21> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr 0x{{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:25> 'int' lvalue ParmVar 0x{{.*}} 'y' 'int'
// CHECK-NEXT: | | | |-UnaryOperator 0x{{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:28> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt 0x{{.*}} <line:13:7>
// CHECK-NEXT: | | |-ImplicitParamDecl 0x{{.*}} <line:10:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-for.c:10:1) *const restrict'
// CHECK-NEXT: | | |-VarDecl 0x{{.*}} <line:11:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral 0x{{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | `-VarDecl 0x{{.*}} <line:12:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral 0x{{.*}} <col:18> 'int' 0
// CHECK-NEXT: | |-DeclRefExpr 0x{{.*}} <line:11:3> 'int' lvalue ParmVar 0x{{.*}} 'x' 'int'
// CHECK-NEXT: | `-DeclRefExpr 0x{{.*}} <line:12:25> 'int' lvalue ParmVar 0x{{.*}} 'y' 'int'
// CHECK-NEXT: |-FunctionDecl 0x{{.*}} <line:16:1, line:21:1> line:16:6 test_three 'void (int, int)'
// CHECK-NEXT: | |-ParmVarDecl 0x{{.*}} <col:17, col:21> col:21 used x 'int'
// CHECK-NEXT: | |-ParmVarDecl 0x{{.*}} <col:24, col:28> col:28 used y 'int'
// CHECK-NEXT: | `-CompoundStmt 0x{{.*}} <col:31, line:21:1>
// CHECK-NEXT: | `-OMPForDirective 0x{{.*}} <line:17:1, col:28>
// CHECK-NEXT: | |-OMPCollapseClause 0x{{.*}} <col:17, col:27>
// CHECK-NEXT: | | `-ConstantExpr 0x{{.*}} <col:26> 'int'
// CHECK-NEXT: | | `-IntegerLiteral 0x{{.*}} <col:26> 'int' 1
// CHECK-NEXT: | `-CapturedStmt 0x{{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | |-CapturedDecl 0x{{.*}} <<invalid sloc>> <invalid sloc>
// CHECK-NEXT: | | |-ForStmt 0x{{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | |-DeclStmt 0x{{.*}} <line:18:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl 0x{{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral 0x{{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator 0x{{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr 0x{{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr 0x{{.*}} <col:19> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr 0x{{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:23> 'int' lvalue ParmVar 0x{{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator 0x{{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:26> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ForStmt 0x{{.*}} <line:19:5, line:20:7> openmp_structured_block
// CHECK-NEXT: | | | |-DeclStmt 0x{{.*}} <line:19:10, col:19>
// CHECK-NEXT: | | | | `-VarDecl 0x{{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral 0x{{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator 0x{{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr 0x{{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr 0x{{.*}} <col:21> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr 0x{{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:25> 'int' lvalue ParmVar 0x{{.*}} 'y' 'int'
// CHECK-NEXT: | | | |-UnaryOperator 0x{{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:28> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt 0x{{.*}} <line:20:7>
// CHECK-NEXT: | | |-ImplicitParamDecl 0x{{.*}} <line:17:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-for.c:17:1) *const restrict'
// CHECK-NEXT: | | |-VarDecl 0x{{.*}} <line:18:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral 0x{{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | `-VarDecl 0x{{.*}} <line:19:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral 0x{{.*}} <col:18> 'int' 0
// CHECK-NEXT: | |-DeclRefExpr 0x{{.*}} <line:18:3> 'int' lvalue ParmVar 0x{{.*}} 'x' 'int'
// CHECK-NEXT: | `-DeclRefExpr 0x{{.*}} <line:19:25> 'int' lvalue ParmVar 0x{{.*}} 'y' 'int'
// CHECK-NEXT: |-FunctionDecl 0x{{.*}} <line:23:1, line:28:1> line:23:6 test_four 'void (int, int)'
// CHECK-NEXT: | |-ParmVarDecl 0x{{.*}} <col:16, col:20> col:20 used x 'int'
// CHECK-NEXT: | |-ParmVarDecl 0x{{.*}} <col:23, col:27> col:27 used y 'int'
// CHECK-NEXT: | `-CompoundStmt 0x{{.*}} <col:30, line:28:1>
// CHECK-NEXT: | `-OMPForDirective 0x{{.*}} <line:24:1, col:28>
// CHECK-NEXT: | |-OMPCollapseClause 0x{{.*}} <col:17, col:27>
// CHECK-NEXT: | | `-ConstantExpr 0x{{.*}} <col:26> 'int'
// CHECK-NEXT: | | `-IntegerLiteral 0x{{.*}} <col:26> 'int' 2
// CHECK-NEXT: | `-CapturedStmt 0x{{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | |-CapturedDecl 0x{{.*}} <<invalid sloc>> <invalid sloc>
// CHECK-NEXT: | | |-ForStmt 0x{{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | |-DeclStmt 0x{{.*}} <line:25:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl 0x{{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral 0x{{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator 0x{{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr 0x{{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr 0x{{.*}} <col:19> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr 0x{{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:23> 'int' lvalue ParmVar 0x{{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator 0x{{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:26> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ForStmt 0x{{.*}} <line:26:5, line:27:7>
// CHECK-NEXT: | | | |-DeclStmt 0x{{.*}} <line:26:10, col:19>
// CHECK-NEXT: | | | | `-VarDecl 0x{{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral 0x{{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator 0x{{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr 0x{{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr 0x{{.*}} <col:21> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr 0x{{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:25> 'int' lvalue ParmVar 0x{{.*}} 'y' 'int'
// CHECK-NEXT: | | | |-UnaryOperator 0x{{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:28> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt 0x{{.*}} <line:27:7> openmp_structured_block
// CHECK-NEXT: | | |-ImplicitParamDecl 0x{{.*}} <line:24:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-for.c:24:1) *const restrict'
// CHECK-NEXT: | | |-VarDecl 0x{{.*}} <line:25:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral 0x{{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | `-VarDecl 0x{{.*}} <line:26:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral 0x{{.*}} <col:18> 'int' 0
// CHECK-NEXT: | |-DeclRefExpr 0x{{.*}} <line:25:3> 'int' lvalue ParmVar 0x{{.*}} 'x' 'int'
// CHECK-NEXT: | `-DeclRefExpr 0x{{.*}} <line:26:5> 'int' lvalue ParmVar 0x{{.*}} 'y' 'int'
// CHECK-NEXT: `-FunctionDecl 0x{{.*}} <line:30:1, line:36:1> line:30:6 test_five 'void (int, int, int)'
// CHECK-NEXT: |-ParmVarDecl 0x{{.*}} <col:16, col:20> col:20 used x 'int'
// CHECK-NEXT: |-ParmVarDecl 0x{{.*}} <col:23, col:27> col:27 used y 'int'
// CHECK-NEXT: |-ParmVarDecl 0x{{.*}} <col:30, col:34> col:34 used z 'int'
// CHECK-NEXT: `-CompoundStmt 0x{{.*}} <col:37, line:36:1>
// CHECK-NEXT: `-OMPForDirective 0x{{.*}} <line:31:1, col:28>
// CHECK-NEXT: |-OMPCollapseClause 0x{{.*}} <col:17, col:27>
// CHECK-NEXT: | `-ConstantExpr 0x{{.*}} <col:26> 'int'
// CHECK-NEXT: | `-IntegerLiteral 0x{{.*}} <col:26> 'int' 2
// CHECK-NEXT: `-CapturedStmt 0x{{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: |-CapturedDecl 0x{{.*}} <<invalid sloc>> <invalid sloc>
// CHECK-NEXT: | |-ForStmt 0x{{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | |-DeclStmt 0x{{.*}} <line:32:8, col:17>
// CHECK-NEXT: | | | `-VarDecl 0x{{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral 0x{{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | |-<<<NULL>>>
// CHECK-NEXT: | | |-BinaryOperator 0x{{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | |-ImplicitCastExpr 0x{{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:19> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr 0x{{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | `-DeclRefExpr 0x{{.*}} <col:23> 'int' lvalue ParmVar 0x{{.*}} 'x' 'int'
// CHECK-NEXT: | | |-UnaryOperator 0x{{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | `-DeclRefExpr 0x{{.*}} <col:26> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | `-ForStmt 0x{{.*}} <line:33:5, line:35:9>
// CHECK-NEXT: | | |-DeclStmt 0x{{.*}} <line:33:10, col:19>
// CHECK-NEXT: | | | `-VarDecl 0x{{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral 0x{{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | |-<<<NULL>>>
// CHECK-NEXT: | | |-BinaryOperator 0x{{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | |-ImplicitCastExpr 0x{{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:21> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr 0x{{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | `-DeclRefExpr 0x{{.*}} <col:25> 'int' lvalue ParmVar 0x{{.*}} 'y' 'int'
// CHECK-NEXT: | | |-UnaryOperator 0x{{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | `-DeclRefExpr 0x{{.*}} <col:28> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | `-ForStmt 0x{{.*}} <line:34:7, line:35:9> openmp_structured_block
// CHECK-NEXT: | | |-DeclStmt 0x{{.*}} <line:34:12, col:21>
// CHECK-NEXT: | | | `-VarDecl 0x{{.*}} <col:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral 0x{{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | |-<<<NULL>>>
// CHECK-NEXT: | | |-BinaryOperator 0x{{.*}} <col:23, col:27> 'int' '<'
// CHECK-NEXT: | | | |-ImplicitCastExpr 0x{{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr 0x{{.*}} <col:23> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr 0x{{.*}} <col:27> 'int' <LValueToRValue>
// CHECK-NEXT: | | | `-DeclRefExpr 0x{{.*}} <col:27> 'int' lvalue ParmVar 0x{{.*}} 'z' 'int'
// CHECK-NEXT: | | |-UnaryOperator 0x{{.*}} <col:30, col:31> 'int' postfix '++'
// CHECK-NEXT: | | | `-DeclRefExpr 0x{{.*}} <col:30> 'int' lvalue Var 0x{{.*}} 'i' 'int'
// CHECK-NEXT: | | `-NullStmt 0x{{.*}} <line:35:9>
// CHECK-NEXT: | |-ImplicitParamDecl 0x{{.*}} <line:31:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-for.c:31:1) *const restrict'
// CHECK-NEXT: | |-VarDecl 0x{{.*}} <line:32:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral 0x{{.*}} <col:16> 'int' 0
// CHECK-NEXT: | |-VarDecl 0x{{.*}} <line:33:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral 0x{{.*}} <col:18> 'int' 0
// CHECK-NEXT: | `-VarDecl 0x{{.*}} <line:34:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | `-IntegerLiteral 0x{{.*}} <col:20> 'int' 0
// CHECK-NEXT: |-DeclRefExpr 0x{{.*}} <line:32:3> 'int' lvalue ParmVar 0x{{.*}} 'x' 'int'
// CHECK-NEXT: |-DeclRefExpr 0x{{.*}} <line:33:5> 'int' lvalue ParmVar 0x{{.*}} 'y' 'int'
// CHECK-NEXT: `-DeclRefExpr 0x{{.*}} <line:34:27> 'int' lvalue ParmVar 0x{{.*}} 'z' 'int'
|
GeometryFunctions.h | /*
* File: GeometryFunctions.h
* Author: msantasusana, Chun Feng
*
* Created on 21 de mayo de 2012, 19:40
*/
#ifndef _GEOMETRYFUNCTIONS_H
#define _GEOMETRYFUNCTIONS_H
#include <cmath>
#include "utilities/openmp_utils.h"
#include "utilities/quaternion.h"
#include "includes/model_part.h"
#include "DEM_application_variables.h"
namespace Kratos {
namespace GeometryFunctions {
typedef Geometry<Node < 3 > > GeometryType;
static inline void RotateAVectorAGivenAngleAroundAUnitaryVector(const array_1d<double, 3>& old_vec, const array_1d<double, 3>& axis,
const double ang, array_1d<double, 3>& new_vec) {
double cang = std::cos(ang);
double sang = std::sin(ang);
new_vec[0] = axis[0] * (axis[0] * old_vec[0] + axis[1] * old_vec[1] + axis[2] * old_vec[2]) * (1 - cang) + old_vec[0] * cang + (-axis[2] * old_vec[1] + axis[1] * old_vec[2]) * sang;
new_vec[1] = axis[1] * (axis[0] * old_vec[0] + axis[1] * old_vec[1] + axis[2] * old_vec[2]) * (1 - cang) + old_vec[1] * cang + ( axis[2] * old_vec[0] - axis[0] * old_vec[2]) * sang;
new_vec[2] = axis[2] * (axis[0] * old_vec[0] + axis[1] * old_vec[1] + axis[2] * old_vec[2]) * (1 - cang) + old_vec[2] * cang + (-axis[1] * old_vec[0] + axis[0] * old_vec[1]) * sang;
}
static inline void TranslateGridOfNodes(const double time, const double velocity_start_time, const double velocity_stop_time, array_1d<double, 3>& center_position,
const array_1d<double, 3>& initial_center, array_1d<double, 3>& previous_displ, array_1d<double, 3>& linear_velocity_changed,
const double linear_period, const double dt, const array_1d<double, 3>& linear_velocity) {
if (time < velocity_start_time || time > velocity_stop_time) {
center_position[0] = initial_center[0] + previous_displ[0];
center_position[1] = initial_center[1] + previous_displ[1];
center_position[2] = initial_center[2] + previous_displ[2];
linear_velocity_changed = ZeroVector(3);
} else {
if (linear_period > 0.0) {
double linear_omega = 2.0 * Globals::Pi / linear_period;
double inv_linear_omega = 1.0 / linear_omega;
noalias(center_position) = initial_center + linear_velocity * std::sin(linear_omega * (time - velocity_start_time)) * inv_linear_omega;
noalias(linear_velocity_changed) = linear_velocity * std::cos(linear_omega * (time - velocity_start_time));
noalias(previous_displ) = center_position - initial_center;
} else {
center_position[0] = initial_center[0] + previous_displ[0] + dt * linear_velocity[0];
center_position[1] = initial_center[1] + previous_displ[1] + dt * linear_velocity[1];
center_position[2] = initial_center[2] + previous_displ[2] + dt * linear_velocity[2];
previous_displ[0] += dt * linear_velocity[0];
previous_displ[1] += dt * linear_velocity[1];
previous_displ[2] += dt * linear_velocity[2];
linear_velocity_changed = linear_velocity;
}
}
}
static inline int sign(const double a)
{
return (0.0 < a) - (a < 0.0);
/*int output;
if (a < 0.0) output = -1;
else if (a > 0.0) output = 1;
else output = 0;
return output;*/
}
static inline double min(double a, double b)
{
double output;
if (a<=b) output = a;
else output = b;
return output;
}
static inline double max(double a, double b)
{
double output;
if (a>=b) output = a;
else output = b;
return output;
}
static inline void normalize(double Vector[3])
{
double distance = DEM_INNER_PRODUCT_3(Vector, Vector);
double inv_distance = (distance > 0.0) ? 1.0 / sqrt(distance) : 0.00;
Vector[0] = Vector[0] * inv_distance;
Vector[1] = Vector[1] * inv_distance;
Vector[2] = Vector[2] * inv_distance;
}
static inline void normalize(array_1d<double,3>& Vector, double& distance)
{
distance = DEM_MODULUS_3(Vector);
double inv_distance = (distance != 0.0) ? 1.0 / distance : 0.00;
Vector[0] = Vector[0] * inv_distance;
Vector[1] = Vector[1] * inv_distance;
Vector[2] = Vector[2] * inv_distance;
}
static inline void normalize(double Vector[3], double& distance)
{
distance = DEM_MODULUS_3(Vector);
double inv_distance = (distance != 0.0) ? 1.0 / distance : 0.00;
Vector[0] = Vector[0] * inv_distance;
Vector[1] = Vector[1] * inv_distance;
Vector[2] = Vector[2] * inv_distance;
}
static inline void normalize(array_1d<double,3>& Vector)
{
double distance = DEM_MODULUS_3(Vector);
double inv_distance = (distance != 0.0) ? 1.0 / distance : 0.00;
Vector[0] = Vector[0] * inv_distance;
Vector[1] = Vector[1] * inv_distance;
Vector[2] = Vector[2] * inv_distance;
}
static inline void module(const array_1d<double,3>& Vector, double& distance)
{
distance = DEM_MODULUS_3(Vector);
}
static inline double module(const double Vector[3])
{
return DEM_MODULUS_3(Vector);
}
static inline void module(const double Vector[3], double& distance)
{
distance = DEM_MODULUS_3(Vector);
}
static inline double module(const array_1d<double,3>& Vector)
{
double distance = DEM_MODULUS_3(Vector);
return distance;
}
static inline void VectorGlobal2Local(const double LocalCoordSystem[3][3], const double GlobalVector[3], double LocalVector[3])
{
for (int i=0; i<3; i++) {
LocalVector[i] = 0.0;
for (int j=0; j<3; j++) {
LocalVector[i]+=LocalCoordSystem[i][j]*GlobalVector[j];
}
}
}
static inline void VectorGlobal2Local(const double LocalCoordSystem[3][3], const array_1d<double, 3>& GlobalVector, array_1d<double, 3>& LocalVector)
{
for (int i=0; i<3; i++) {
LocalVector[i] = 0.0;
for (int j=0; j<3; j++) {
LocalVector[i]+=LocalCoordSystem[i][j]*GlobalVector[j];
}
}
}
static inline void VectorGlobal2Local(const double LocalCoordSystem[3][3], const array_1d<double, 3>& GlobalVector, double LocalVector[3])
{
for (int i=0; i<3; i++) {
LocalVector[i] = 0.0;
for (int j=0; j<3; j++) {
LocalVector[i]+=LocalCoordSystem[i][j]*GlobalVector[j];
}
}
}
static inline void VectorLocal2Global(const double LocalCoordSystem[3][3], const double LocalVector[3], double GlobalVector[3])
{
for (int i=0; i<3; i++) {
GlobalVector[i] = 0.0;
for (int j=0; j<3; j++) {
GlobalVector[i]+=LocalCoordSystem[j][i]*LocalVector[j];
}
}
}
static inline void VectorLocal2Global(const double LocalCoordSystem[3][3], const array_1d<double, 3>& LocalVector, array_1d<double, 3>& GlobalVector)
{
for (int i=0; i<3; i++) {
GlobalVector[i] = 0.0;
for (int j=0; j<3; j++) {
GlobalVector[i]+=LocalCoordSystem[j][i]*LocalVector[j];
}
}
}
static inline void VectorLocal2Global(const double LocalCoordSystem[3][3], const array_1d<double, 3>& LocalVector, double GlobalVector[3])
{
for (int i=0; i<3; i++) {
GlobalVector[i] = 0.0;
for (int j=0; j<3; j++) {
GlobalVector[i]+=LocalCoordSystem[j][i]*LocalVector[j];
}
}
}
static inline void VectorLocal2Global(const double LocalCoordSystem[3][3], const double LocalVector[3], array_1d<double, 3>& GlobalVector)
{
for (int i=0; i<3; i++) {
GlobalVector[i] = 0.0;
for (int j=0; j<3; j++) {
GlobalVector[i]+=LocalCoordSystem[j][i]*LocalVector[j];
}
}
}
static inline void ProductMatrices3X3(const double Matrix1[3][3], const double Matrix2[3][3], double Matrix3[3][3])
{
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
Matrix3[i][j] = 0.0;
for (int k = 0; k < 3; k++) {
Matrix3[i][j] += Matrix1[i][k] * Matrix2[k][j];
}
}
}
}
static inline void ProductMatrix3X3Vector3X1(const double Matrix[3][3], const array_1d<double,3>& Vector1, array_1d<double,3>& Vector2)
{
for (int i=0; i<3; i++) {
Vector2[i] = 0.0;
for (int j=0; j<3; j++) {
Vector2[i]+=Matrix[j][i]*Vector1[j];
}
}
}
static inline void TensorGlobal2Local(const double LocalCoordSystem[3][3], const double GlobalTensor[3][3], double LocalTensor[3][3])
{
// We will compute LocalTensor = LocalCoordSystem * GlobalTensor * transposed(LocalCoordSystem)
// starting on the left, so we will first compute the product TemporalResult = LocalCoordSystem * GlobalTensor
// and afterwards TemporalResult * transposed(LocalCoordSystem), which will give the value of the tensor LocalTensor
double TransposedLocalCoordSystem[3][3];
double TemporalResult[3][3];
TransposedLocalCoordSystem[0][0] = LocalCoordSystem[0][0]; TransposedLocalCoordSystem[0][1] = LocalCoordSystem[1][0]; TransposedLocalCoordSystem[0][2] = LocalCoordSystem[2][0];
TransposedLocalCoordSystem[1][0] = LocalCoordSystem[0][1]; TransposedLocalCoordSystem[1][1] = LocalCoordSystem[1][1]; TransposedLocalCoordSystem[1][2] = LocalCoordSystem[2][1];
TransposedLocalCoordSystem[2][0] = LocalCoordSystem[0][2]; TransposedLocalCoordSystem[2][1] = LocalCoordSystem[1][2]; TransposedLocalCoordSystem[2][2] = LocalCoordSystem[2][2];
ProductMatrices3X3(LocalCoordSystem, GlobalTensor, TemporalResult);
ProductMatrices3X3(TemporalResult, TransposedLocalCoordSystem, LocalTensor);
}
static inline void TensorLocal2Global(const double LocalCoordSystem[3][3], const double LocalTensor[3][3], double GlobalTensor[3][3])
{
// We will compute GlobalTensor = transposed(LocalCoordSystem) * LocalTensor * LocalCoordSystem
// starting on the left, so we will first compute the product TemporalResult = transposed(LocalCoordSystem) * LocalTensor
// and afterwards TemporalResult * LocalCoordSystem, which will give the value of the tensor LocalTensor
double TransposedLocalCoordSystem[3][3];
double TemporalResult[3][3];
TransposedLocalCoordSystem[0][0] = LocalCoordSystem[0][0]; TransposedLocalCoordSystem[0][1] = LocalCoordSystem[1][0]; TransposedLocalCoordSystem[0][2] = LocalCoordSystem[2][0];
TransposedLocalCoordSystem[1][0] = LocalCoordSystem[0][1]; TransposedLocalCoordSystem[1][1] = LocalCoordSystem[1][1]; TransposedLocalCoordSystem[1][2] = LocalCoordSystem[2][1];
TransposedLocalCoordSystem[2][0] = LocalCoordSystem[0][2]; TransposedLocalCoordSystem[2][1] = LocalCoordSystem[1][2]; TransposedLocalCoordSystem[2][2] = LocalCoordSystem[2][2];
ProductMatrices3X3(TransposedLocalCoordSystem, LocalTensor, TemporalResult);
ProductMatrices3X3(TemporalResult, LocalCoordSystem, GlobalTensor);
}
static inline void RotaMatrixTensorLocal2Global(const double R[3][3], const double LocalTensor[3][3], double GlobalTensor[3][3])
{
double RT[3][3]; double Temp[3][3];
RT[0][0] = R[0][0]; RT[0][1] = R[1][0]; RT[0][2] = R[2][0];
RT[1][0] = R[0][1]; RT[1][1] = R[1][1]; RT[1][2] = R[2][1];
RT[2][0] = R[0][2]; RT[2][1] = R[1][2]; RT[2][2] = R[2][2];
ProductMatrices3X3(R, LocalTensor, Temp);
ProductMatrices3X3(Temp, RT, GlobalTensor);
}
static inline void ConstructLocalTensor(const double moment_of_inertia, double LocalTensor[3][3])
{
LocalTensor[0][0] = moment_of_inertia; LocalTensor[0][1] = 0.0; LocalTensor[0][2] = 0.0;
LocalTensor[1][0] = 0.0; LocalTensor[1][1] = moment_of_inertia; LocalTensor[1][2] = 0.0;
LocalTensor[2][0] = 0.0; LocalTensor[2][1] = 0.0; LocalTensor[2][2] = moment_of_inertia;
}
static inline void ConstructInvLocalTensor(const double moment_of_inertia, double LocalTensorInv[3][3])
{
double moment_of_inertia_inv = 1/moment_of_inertia;
LocalTensorInv[0][0] = moment_of_inertia_inv; LocalTensorInv[0][1] = 0.0; LocalTensorInv[0][2] = 0.0;
LocalTensorInv[1][0] = 0.0; LocalTensorInv[1][1] = moment_of_inertia_inv; LocalTensorInv[1][2] = 0.0;
LocalTensorInv[2][0] = 0.0; LocalTensorInv[2][1] = 0.0; LocalTensorInv[2][2] = moment_of_inertia_inv;
}
static inline void ConstructLocalTensor(const array_1d<double, 3 >& moments_of_inertia, double LocalTensor[3][3])
{
LocalTensor[0][0] = moments_of_inertia[0]; LocalTensor[0][1] = 0.0; LocalTensor[0][2] = 0.0;
LocalTensor[1][0] = 0.0; LocalTensor[1][1] = moments_of_inertia[1]; LocalTensor[1][2] = 0.0;
LocalTensor[2][0] = 0.0; LocalTensor[2][1] = 0.0; LocalTensor[2][2] = moments_of_inertia[2];
}
static inline void ConstructInvLocalTensor(const array_1d<double, 3 >& moments_of_inertia, double LocalTensorInv[3][3])
{
LocalTensorInv[0][0] = 1/moments_of_inertia[0]; LocalTensorInv[0][1] = 0.0; LocalTensorInv[0][2] = 0.0;
LocalTensorInv[1][0] = 0.0; LocalTensorInv[1][1] = 1/moments_of_inertia[1]; LocalTensorInv[1][2] = 0.0;
LocalTensorInv[2][0] = 0.0; LocalTensorInv[2][1] = 0.0; LocalTensorInv[2][2] = 1/moments_of_inertia[2];
}
static inline double DotProduct(double Vector1[3], double Vector2[3])
{
return Vector1[0] * Vector2[0] + Vector1[1] * Vector2[1] + Vector1[2] * Vector2[2];
}
static inline double DotProduct(const array_1d<double,3>& Vector1, const array_1d<double,3>& Vector2)
{
return Vector1[0] * Vector2[0] + Vector1[1] * Vector2[1] + Vector1[2] * Vector2[2];
}
static inline void CrossProduct(const double u[3], const double v[3], double ReturnVector[3])
{
ReturnVector[0] = u[1]*v[2] - u[2]*v[1];
ReturnVector[1] = v[0]*u[2] - u[0]*v[2];
ReturnVector[2] = u[0]*v[1] - u[1]*v[0];
}
static inline void CrossProduct(const array_1d<double,3>& u, const array_1d<double,3>& v, array_1d<double,3>& ReturnVector)
{
ReturnVector[0] = u[1]*v[2] - u[2]*v[1];
ReturnVector[1] = v[0]*u[2] - u[0]*v[2];
ReturnVector[2] = u[0]*v[1] - u[1]*v[0];
}
static inline void CrossProduct(const double u[3], const array_1d<double,3>& v, double ReturnVector[3])
{
ReturnVector[0] = u[1]*v[2] - u[2]*v[1];
ReturnVector[1] = v[0]*u[2] - u[0]*v[2];
ReturnVector[2] = u[0]*v[1] - u[1]*v[0];
}
static inline void CrossProduct(const array_1d<double,3>& u, const double v[3], double ReturnVector[3])
{
ReturnVector[0] = u[1]*v[2] - u[2]*v[1];
ReturnVector[1] = v[0]*u[2] - u[0]*v[2];
ReturnVector[2] = u[0]*v[1] - u[1]*v[0];
}
static inline void CrossProduct(const array_1d<double,3>& u, const double v[3], array_1d<double,3>& ReturnVector)
{
ReturnVector[0] = u[1]*v[2] - u[2]*v[1];
ReturnVector[1] = v[0]*u[2] - u[0]*v[2];
ReturnVector[2] = u[0]*v[1] - u[1]*v[0];
}
static inline void CrossProduct(const array_1d<double,3>& u, const array_1d<double,3>& v, double ReturnVector[3])
{
ReturnVector[0] = u[1]*v[2] - u[2]*v[1];
ReturnVector[1] = v[0]*u[2] - u[0]*v[2];
ReturnVector[2] = u[0]*v[1] - u[1]*v[0];
}
static inline void RotateRightHandedBasisAroundAxis(const array_1d<double, 3>& e1, const array_1d<double, 3>& e2, const array_1d<double, 3>& axis,
const double ang, array_1d<double, 3>& new_axes1, array_1d<double, 3>& new_axes2,
array_1d<double, 3>& new_axes3) {
RotateAVectorAGivenAngleAroundAUnitaryVector(e1, axis, ang, new_axes1);
RotateAVectorAGivenAngleAroundAUnitaryVector(e2, axis, ang, new_axes2);
CrossProduct(new_axes1, new_axes2, new_axes3);
}
static inline void RotateGridOfNodes(const double time, const double angular_velocity_start_time, const double angular_velocity_stop_time,
array_1d<double, 3>& angular_velocity_changed, const double angular_period, const double mod_angular_velocity,
const array_1d<double, 3>& angular_velocity, array_1d<double, 3>& new_axes1, array_1d<double, 3>& new_axes2,
array_1d<double, 3>& new_axes3) {
array_1d<double, 3> angle;
noalias(angle) = ZeroVector(3);
double sign_angle = 1.0;
array_1d<double, 3> final_angle = ZeroVector(3);
if (time < angular_velocity_start_time) angular_velocity_changed = ZeroVector(3);
else if (((time - angular_velocity_start_time) > 0.0) && ((time - angular_velocity_stop_time) < 0.0)) {
if (angular_period > 0.0) {
double angular_omega = 2.0 * Globals::Pi / angular_period;
double inv_angular_omega = 1.0 / angular_omega;
noalias(angle) = angular_velocity * std::sin(angular_omega * (time - angular_velocity_start_time)) * inv_angular_omega;
sign_angle = std::sin(angular_omega * (time - angular_velocity_start_time)) / fabs(sin(angular_omega * (time - angular_velocity_start_time)));
noalias(angular_velocity_changed) = angular_velocity * std::cos(angular_omega * (time - angular_velocity_start_time));
noalias(final_angle) = angle;
} else {
noalias(angle) = angular_velocity * (time - angular_velocity_start_time);
noalias(angular_velocity_changed) = angular_velocity;
}
} else { //if ((time - angular_velocity_stop_time) > 0.0) {
noalias(angular_velocity_changed) = ZeroVector(3);
if (angular_period > 0.0) {
double angular_omega = 2.0 * Globals::Pi / angular_period;
double inv_angular_omega = 1.0 / angular_omega;
noalias(angle) = angular_velocity * std::sin(angular_omega * (angular_velocity_stop_time - angular_velocity_start_time)) * inv_angular_omega;
} else {
noalias(angle) = angular_velocity * (angular_velocity_stop_time - angular_velocity_start_time);
}
}
//mod_angular_velocity = MathUtils<double>::Norm3(angular_velocity);
new_axes1[0] = 1.0;
new_axes1[1] = 0.0;
new_axes1[2] = 0.0;
new_axes2[0] = 0.0;
new_axes2[1] = 1.0;
new_axes2[2] = 0.0;
new_axes3[0] = 0.0;
new_axes3[1] = 0.0;
new_axes3[2] = 1.0;
if (mod_angular_velocity > 0.0) {
double ang = sign_angle * MathUtils<double>::Norm3(angle);
array_1d<double, 3> rotation_axis;
noalias(rotation_axis) = angular_velocity / mod_angular_velocity;
array_1d<double, 3> e1;
e1[0] = 1.0;
e1[1] = 0.0;
e1[2] = 0.0;
array_1d<double, 3> e2;
e2[0] = 0.0;
e2[1] = 1.0;
e2[2] = 0.0;
RotateRightHandedBasisAroundAxis(e1, e2, rotation_axis, ang, new_axes1, new_axes2, new_axes3);
}
}
static inline void UpdateKinematicVariablesOfAGridOfNodes(double mod_angular_velocity, const array_1d<double, 3>& linear_velocity,
const array_1d<double, 3>& initial_center, array_1d<double, 3>& new_axes1, array_1d<double, 3>& new_axes2,
array_1d<double, 3>& new_axes3, array_1d<double, 3>& angular_velocity_changed,
array_1d<double, 3>& linear_velocity_changed, array_1d<double, 3>& center_position,
const bool fixed_mesh, const double dt, ModelPart::NodesContainerType& pNodes)
{
if (mod_angular_velocity > std::numeric_limits<double>::epsilon() || MathUtils<double>::Norm3(linear_velocity) > std::numeric_limits<double>::epsilon()) {
#pragma omp parallel for
for (int k = 0; k < (int)pNodes.size(); k++) {
array_1d<double, 3> local_coordinates = ZeroVector(3);
array_1d<double, 3> relative_position = ZeroVector(3);
ModelPart::NodeIterator node = pNodes.begin() + k;
noalias(local_coordinates) = node->GetInitialPosition().Coordinates() - initial_center;
noalias(relative_position) = new_axes1 * local_coordinates[0] + new_axes2 * local_coordinates[1] + new_axes3 * local_coordinates[2];
array_1d<double, 3> old_coordinates;
noalias(old_coordinates) = node->Coordinates();
array_1d<double, 3> velocity_due_to_rotation;
array_1d<double, 3>& velocity = node->FastGetSolutionStepValue(VELOCITY);
CrossProduct(angular_velocity_changed, relative_position, velocity_due_to_rotation);
noalias(velocity) = linear_velocity_changed + velocity_due_to_rotation;
if (!fixed_mesh) {
// NEW POSITION
noalias(node->Coordinates()) = center_position + relative_position;
// DISPLACEMENT
noalias(node->FastGetSolutionStepValue(DISPLACEMENT)) = node->Coordinates() - node->GetInitialPosition().Coordinates();
noalias(node->FastGetSolutionStepValue(DELTA_DISPLACEMENT)) = node->Coordinates() - old_coordinates;
} else {
(node->FastGetSolutionStepValue(DISPLACEMENT)).clear(); //Set values to zero
noalias(node->FastGetSolutionStepValue(DELTA_DISPLACEMENT)) = velocity * dt; //But still there must be some delta_displacement (or motion won't be detected by the spheres!)
}
}
}
}
//NOTE:: Modified by M. Santasusana Feb 2013 - simplification (the one proposed by F. Chun was for a more generalized case)
static inline void ComputeContactLocalCoordSystem(array_1d<double, 3> NormalDirection, const double& distance, double LocalCoordSystem[3][3]) //inline: modifies the LocalCoordSystem as it were a reference
{
double inv_distance = (distance != 0.0) ? 1.0 / distance : 0.0;
NormalDirection[0] *= inv_distance;
NormalDirection[1] *= inv_distance;
NormalDirection[2] *= inv_distance;
double N_fast[3];
N_fast[0] = NormalDirection[0];
N_fast[1] = NormalDirection[1];
N_fast[2] = NormalDirection[2];
if (fabs(N_fast[0]) >= 0.577) //0.57735026919
{
LocalCoordSystem[0][0] = - N_fast[1];
LocalCoordSystem[0][1] = N_fast[0];
LocalCoordSystem[0][2] = 0.0;
}
else if (fabs(N_fast[1]) >= 0.577)
{
LocalCoordSystem[0][0] = 0.0;
LocalCoordSystem[0][1] = - N_fast[2];
LocalCoordSystem[0][2] = N_fast[1];
}
else
{
LocalCoordSystem[0][0] = N_fast[2];
LocalCoordSystem[0][1] = 0.0;
LocalCoordSystem[0][2] = - N_fast[0];
}
//normalize(Vector0);
double distance0 = DEM_MODULUS_3(LocalCoordSystem[0]);
double inv_distance0 = (distance0 != 0.0) ? 1.0 / distance0 : 0.0;
LocalCoordSystem[0][0] = LocalCoordSystem[0][0] * inv_distance0;
LocalCoordSystem[0][1] = LocalCoordSystem[0][1] * inv_distance0;
LocalCoordSystem[0][2] = LocalCoordSystem[0][2] * inv_distance0;
//CrossProduct(NormalDirection, Vector0, Vector1);
LocalCoordSystem[1][0] = N_fast[1] * LocalCoordSystem[0][2] - N_fast[2] * LocalCoordSystem[0][1];
LocalCoordSystem[1][1] = N_fast[2] * LocalCoordSystem[0][0] - N_fast[0] * LocalCoordSystem[0][2];
LocalCoordSystem[1][2] = N_fast[0] * LocalCoordSystem[0][1] - N_fast[1] * LocalCoordSystem[0][0];
//normalize(Vector1);
LocalCoordSystem[2][0] = N_fast[0];
LocalCoordSystem[2][1] = N_fast[1];
LocalCoordSystem[2][2] = N_fast[2];
}
static inline double DistanceOfTwoPoint(const double coord1[3], const double coord2[3])
{
double dx = coord1[0] - coord2[0];
double dy = coord1[1] - coord2[1];
double dz = coord1[2] - coord2[2];
return sqrt(dx * dx + dy * dy + dz * dz);
}
static inline double DistanceOfTwoPoint(const array_1d<double,3>& coord1, const double coord2[3])
{
double dx = coord1[0] - coord2[0];
double dy = coord1[1] - coord2[1];
double dz = coord1[2] - coord2[2];
return sqrt(dx * dx + dy * dy + dz * dz);
}
static inline double DistanceOfTwoPointSquared(const array_1d<double,3>& coord1, const array_1d<double,3>& coord2)
{
double dx = coord1[0] - coord2[0];
double dy = coord1[1] - coord2[1];
double dz = coord1[2] - coord2[2];
return (dx * dx + dy * dy + dz * dz);
}
static inline double DistanceOfTwoPointSquared(double coord1[3], double coord2[3])
{
double dx = coord1[0] - coord2[0];
double dy = coord1[1] - coord2[1];
double dz = coord1[2] - coord2[2];
return (dx * dx + dy * dy + dz * dz);
}
static inline double DistancePointToPlane(const array_1d<double,3>& CoordInPlane, double PlaneUnitNormalVector[3], double TestCoord[3])
{
double Vector1[3] = {0.0};
for (unsigned int i = 0; i<3; i++)
{
Vector1[i] = TestCoord[i]- CoordInPlane[i];
}
double dist = fabs (DotProduct(Vector1, PlaneUnitNormalVector));
return dist;
}
static inline void CoordProjectionOnPlane(double CoordOut[3], double CoordIn[3], double LocalCoordSystem[3][3], double IntersectionCoord[3])
{
double out_coord_local[3] = {0.0};
double in_coord_local[3] = {0.0};
VectorGlobal2Local(LocalCoordSystem, CoordOut, out_coord_local);
VectorGlobal2Local(LocalCoordSystem, CoordIn, in_coord_local);
double vector1[3] = {0.0};
vector1[0] = out_coord_local[0];
vector1[1] = out_coord_local[1];
vector1[2] = in_coord_local [2];
VectorLocal2Global(LocalCoordSystem, vector1, IntersectionCoord);
}
static inline void CoordProjectionOnPlaneNew(double CoordOut[3], const array_1d<double, 3>& CoordIn, double LocalCoordSystem[3][3], double IntersectionCoord[3])
{
double out_coord_local[3] = {0.0};
double in_coord_local[3] = {0.0};
VectorGlobal2Local(LocalCoordSystem, CoordOut, out_coord_local);
VectorGlobal2Local(LocalCoordSystem, CoordIn, in_coord_local);
double vector1[3] = {0.0};
vector1[0] = out_coord_local[0];
vector1[1] = out_coord_local[1];
vector1[2] = in_coord_local [2];
VectorLocal2Global(LocalCoordSystem, vector1, IntersectionCoord);
}
static inline void Compute3DimElementFaceLocalSystem(const array_1d <double,3>& FaceCoord1, const array_1d <double,3>& FaceCoord2, const array_1d <double,3>& FaceCoord3, double ParticleCoord[3],
double LocalCoordSystem[3][3], double& normal_flag)
{
//NOTE: this function is designed in a way that the normal always points the side where the center of particle is found. Therefore should only be used in this way if the indentation is less than the radius value.
//the function returns a flag with the same value as the dot product of the normal of the triangle and the normal pointing to the particle.
double Vector1[3] = {0.0};
double Vector2[3] = {0.0};
double Vector3[3] = {0.0};
double Normal[3] = {0.0};
Vector1[0] = FaceCoord2[0] - FaceCoord1[0];
Vector1[1] = FaceCoord2[1] - FaceCoord1[1];
Vector1[2] = FaceCoord2[2] - FaceCoord1[2];
Vector2[0] = FaceCoord3[0] - FaceCoord2[0];
Vector2[1] = FaceCoord3[1] - FaceCoord2[1];
Vector2[2] = FaceCoord3[2] - FaceCoord2[2];
normalize(Vector1);
CrossProduct(Vector1, Vector2, Normal);
normalize(Normal);
CrossProduct(Normal, Vector1, Vector2);
normalize(Vector2);
Vector3[0] = ParticleCoord[0] - FaceCoord1[0];
Vector3[1] = ParticleCoord[1] - FaceCoord1[1];
Vector3[2] = ParticleCoord[2] - FaceCoord1[2];
normalize(Vector3);
if (DotProduct(Vector3, Normal) > 0.0)
{
for (int ia = 0; ia < 3; ia++)
{
normal_flag = 1.0;
LocalCoordSystem[0][ia] = Vector1[ia];
LocalCoordSystem[1][ia] = Vector2[ia];
LocalCoordSystem[2][ia] = Normal [ia];
}
}
else
{
for (int ia = 0; ia < 3; ia++)
{
normal_flag = -1.0;
LocalCoordSystem[0][ia] = -Vector1[ia];
LocalCoordSystem[1][ia] = -Vector2[ia];
LocalCoordSystem[2][ia] = -Normal [ia];
}
}
}
//MSIMSI this one is being used only for distributed... adapt it
static inline void Compute3DimElementFaceLocalSystem(double FaceCoord1[3], double FaceCoord2[3], double FaceCoord3[3], double ParticleCoord[3],
double LocalCoordSystem[3][3], double& normal_flag){
//NOTE: this function is designed in a way that the normal always points the side where the center of particle is found. Therefore should only be used in this way if the indentation is less than the radius value.
//the function returns a flag with the same value as the dot product of the normal of the triangle and the normal pointing to the particle.
double Vector1[3] = {0.0};
double Vector2[3] = {0.0};
double Vector3[3] = {0.0};
double Normal[3] = {0.0};
Vector1[0] = FaceCoord2[0] - FaceCoord1[0];
Vector1[1] = FaceCoord2[1] - FaceCoord1[1];
Vector1[2] = FaceCoord2[2] - FaceCoord1[2];
Vector2[0] = FaceCoord3[0] - FaceCoord2[0];
Vector2[1] = FaceCoord3[1] - FaceCoord2[1];
Vector2[2] = FaceCoord3[2] - FaceCoord2[2];
normalize(Vector1);
CrossProduct(Vector1, Vector2, Normal);
normalize(Normal);
CrossProduct(Normal, Vector1, Vector2);
normalize(Vector2);
Vector3[0] = ParticleCoord[0] - FaceCoord1[0];
Vector3[1] = ParticleCoord[1] - FaceCoord1[1];
Vector3[2] = ParticleCoord[2] - FaceCoord1[2];
normalize(Vector3);
if (DotProduct(Vector3, Normal) > 0.0)
{
for (int ia = 0; ia < 3; ia++)
{
normal_flag = 1.0;
LocalCoordSystem[0][ia] = Vector1[ia];
LocalCoordSystem[1][ia] = Vector2[ia];
LocalCoordSystem[2][ia] = Normal [ia];
}
}
else
{
for (int ia = 0; ia < 3; ia++)
{
normal_flag = -1.0;
LocalCoordSystem[0][ia] = -Vector1[ia];
LocalCoordSystem[1][ia] = -Vector2[ia];
LocalCoordSystem[2][ia] = -Normal [ia];
}
}
}//Compute3DimElementFaceLocalSystem
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////******Rotate a point over an arbitrary line though an arbitrary point******/////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static inline void RotatePointAboutArbitraryLine(array_1d<double,3>& TargetPoint, const array_1d<double,3>& CentrePoint, const array_1d<double,3>& LineVector, const double RotationAngle)
{
const double O = RotationAngle;
double x = TargetPoint[0], a = CentrePoint[0], u = LineVector[0];
double y = TargetPoint[1], b = CentrePoint[1], v = LineVector[1];
double z = TargetPoint[2], c = CentrePoint[2], w = LineVector[2];
double L = u*u+v*v+w*w;
if (L==0)
{
}
else
{
const double inv_L = 1.0 / L;
TargetPoint[0] = ((a*(v*v+w*w)-u*(b*v+c*w-u*x-v*y-w*z))*(1-cos(O))+L*x*cos(O)+sqrt(L)*(-c*w+b*w-w*y+v*z)*sin(O))* inv_L;
TargetPoint[1] = ((b*(u*u+w*w)-v*(a*u+c*w-u*x-v*y-w*z))*(1-cos(O))+L*y*cos(O)+sqrt(L)*(c*u-a*w+w*x-u*z)*sin(O))* inv_L;
TargetPoint[2] = ((c*(u*u+v*v)-w*(a*u+b*v-u*x-v*y-w*z))*(1-cos(O))+L*z*cos(O)+sqrt(L)*(-b*u+a*v-v*x+u*y)*sin(O))* inv_L;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////******Quaternions******////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static inline void QuaternionVectorLocal2Global(const Quaternion<double>& Q, const array_1d<double, 3>& LocalVector, array_1d<double, 3>& GlobalVector)
{
Q.RotateVector3(LocalVector, GlobalVector);
}
static inline void QuaternionVectorGlobal2Local(const Quaternion<double>& Q, const array_1d<double, 3>& GlobalVector, array_1d<double, 3>& LocalVector)
{
Quaternion<double> Q_conj = Q.conjugate();
Q_conj.RotateVector3(GlobalVector, LocalVector);
}
static inline void QuaternionTensorLocal2Global(const Quaternion<double>& Q, const double LocalTensor[3][3], double GlobalTensor[3][3])
{
array_1d<double, 3> LocalTensorC1; array_1d<double, 3> LocalTensorC2; array_1d<double, 3> LocalTensorC3;
LocalTensorC1[0] = LocalTensor[0][0]; LocalTensorC2[0] = LocalTensor[0][1]; LocalTensorC3[0] = LocalTensor[0][2];
LocalTensorC1[1] = LocalTensor[1][0]; LocalTensorC2[1] = LocalTensor[1][1]; LocalTensorC3[1] = LocalTensor[1][2];
LocalTensorC1[2] = LocalTensor[2][0]; LocalTensorC2[2] = LocalTensor[2][1]; LocalTensorC3[2] = LocalTensor[2][2];
array_1d<double, 3> TempTensorC1; array_1d<double, 3> TempTensorC2; array_1d<double, 3> TempTensorC3;
array_1d<double, 3> TempTensorTraspC1; array_1d<double, 3> TempTensorTraspC2; array_1d<double, 3> TempTensorTraspC3;
Q.RotateVector3(LocalTensorC1, TempTensorC1);
Q.RotateVector3(LocalTensorC2, TempTensorC2);
Q.RotateVector3(LocalTensorC3, TempTensorC3);
TempTensorTraspC1[0] = TempTensorC1[0]; TempTensorTraspC2[0] = TempTensorC1[1]; TempTensorTraspC3[0] = TempTensorC1[2];
TempTensorTraspC1[1] = TempTensorC2[0]; TempTensorTraspC2[1] = TempTensorC2[1]; TempTensorTraspC3[1] = TempTensorC2[2];
TempTensorTraspC1[2] = TempTensorC3[0]; TempTensorTraspC2[2] = TempTensorC3[1]; TempTensorTraspC3[2] = TempTensorC3[2];
array_1d<double, 3> GlobalTensorTraspC1; array_1d<double, 3> GlobalTensorTraspC2; array_1d<double, 3> GlobalTensorTraspC3;
Q.RotateVector3(TempTensorTraspC1, GlobalTensorTraspC1);
Q.RotateVector3(TempTensorTraspC2, GlobalTensorTraspC2);
Q.RotateVector3(TempTensorTraspC3, GlobalTensorTraspC3);
GlobalTensor[0][0] = GlobalTensorTraspC1[0]; GlobalTensor[0][1] = GlobalTensorTraspC1[1]; GlobalTensor[0][2] = GlobalTensorTraspC1[2];
GlobalTensor[1][0] = GlobalTensorTraspC2[0]; GlobalTensor[1][1] = GlobalTensorTraspC2[1]; GlobalTensor[1][2] = GlobalTensorTraspC2[2];
GlobalTensor[2][0] = GlobalTensorTraspC3[0]; GlobalTensor[2][1] = GlobalTensorTraspC3[1]; GlobalTensor[2][2] = GlobalTensorTraspC3[2];
}
static inline void UpdateOrientation(array_1d<double, 3>& EulerAngles, Quaternion<double>& Orientation, const array_1d<double, 3>& DeltaRotation)
{
Quaternion<double> DeltaOrientation = Quaternion<double>::Identity();
array_1d<double, 3 > theta = DeltaRotation;
DEM_MULTIPLY_BY_SCALAR_3(theta, 0.5);
double thetaMag = DEM_MODULUS_3(theta);
const double epsilon = std::numeric_limits<double>::epsilon();
if (thetaMag * thetaMag * thetaMag * thetaMag / 24.0 < epsilon) { //Taylor: low angle
double aux = (1 - thetaMag * thetaMag / 6);
DeltaOrientation = Quaternion<double>((1 + thetaMag * thetaMag / 2), theta[0]*aux, theta[1]*aux, theta[2]*aux);
DeltaOrientation.normalize();
}
else {
double aux = std::sin(thetaMag)/thetaMag;
DeltaOrientation = Quaternion<double>(cos(thetaMag), theta[0]*aux, theta[1]*aux, theta[2]*aux);
DeltaOrientation.normalize();
}
Orientation = DeltaOrientation * Orientation;
Orientation.ToEulerAngles(EulerAngles);
}
static inline void UpdateOrientation(Quaternion<double>& Orientation, const array_1d<double, 3>& DeltaRotation)
{
Quaternion<double> DeltaOrientation = Quaternion<double>::Identity();
array_1d<double, 3 > theta = DeltaRotation;
DEM_MULTIPLY_BY_SCALAR_3(theta, 0.5);
double thetaMag = DEM_MODULUS_3(theta);
const double epsilon = std::numeric_limits<double>::epsilon();
if (thetaMag * thetaMag * thetaMag * thetaMag / 24.0 < epsilon) { //Taylor: low angle
double aux = (1 - thetaMag * thetaMag / 6);
DeltaOrientation = Quaternion<double>((1 + thetaMag * thetaMag * 0.5), theta[0]*aux, theta[1]*aux, theta[2]*aux);
DeltaOrientation.normalize();
}
else {
double aux = std::sin(thetaMag)/thetaMag;
DeltaOrientation = Quaternion<double>(cos(thetaMag), theta[0]*aux, theta[1]*aux, theta[2]*aux);
DeltaOrientation.normalize();
}
Orientation = DeltaOrientation * Orientation;
}
static inline void UpdateOrientation(const Quaternion<double>& Orientation, Quaternion<double>& NewOrientation, const array_1d<double, 3>& DeltaRotation)
{
Quaternion<double> DeltaOrientation = Quaternion<double>::Identity();
array_1d<double, 3 > theta = DeltaRotation;
DEM_MULTIPLY_BY_SCALAR_3(theta, 0.5);
double thetaMag = DEM_MODULUS_3(theta);
const double epsilon = std::numeric_limits<double>::epsilon();
if (thetaMag * thetaMag * thetaMag * thetaMag / 24.0 < epsilon) { //Taylor: low angle
double aux = (1 - thetaMag * thetaMag / 6);
DeltaOrientation = Quaternion<double>((1 + thetaMag * thetaMag * 0.5), theta[0]*aux, theta[1]*aux, theta[2]*aux);
DeltaOrientation.normalize();
}
else {
double aux = std::sin(thetaMag)/thetaMag;
DeltaOrientation = Quaternion<double>(cos(thetaMag), theta[0]*aux, theta[1]*aux, theta[2]*aux);
DeltaOrientation.normalize();
}
NewOrientation = DeltaOrientation * Orientation;
}
static inline void EulerAnglesFromRotationAngle(array_1d<double, 3>& EulerAngles, const array_1d<double, 3>& RotatedAngle)
{
Quaternion<double> Orientation = Quaternion<double>::Identity();
array_1d<double, 3 > theta = RotatedAngle;
DEM_MULTIPLY_BY_SCALAR_3(theta, 0.5);
double thetaMag = DEM_MODULUS_3(theta);
const double epsilon = std::numeric_limits<double>::epsilon();
if (thetaMag * thetaMag * thetaMag * thetaMag / 24.0 < epsilon) { //Taylor: low angle
double aux = (1 - thetaMag * thetaMag / 6);
Orientation = Quaternion<double>((1 + thetaMag * thetaMag / 2), theta[0]*aux, theta[1]*aux, theta[2]*aux);
Orientation.normalize();
}
else {
double aux = std::sin(thetaMag)/thetaMag;
Orientation = Quaternion<double>(cos(thetaMag), theta[0]*aux, theta[1]*aux, theta[2]*aux);
Orientation.normalize();
}
Orientation.ToEulerAngles(EulerAngles);
}
static inline void OrientationFromRotationAngle(Quaternion<double>& DeltaOrientation, const array_1d<double, 3>& DeltaRotation)
{
array_1d<double, 3 > theta = DeltaRotation;
DEM_MULTIPLY_BY_SCALAR_3(theta, 0.5);
double thetaMag = DEM_MODULUS_3(theta);
const double epsilon = std::numeric_limits<double>::epsilon();
if (thetaMag * thetaMag * thetaMag * thetaMag / 24.0 < epsilon) { //Taylor: low angle
double aux = (1 - thetaMag * thetaMag / 6);
DeltaOrientation = Quaternion<double>((1 + thetaMag * thetaMag / 2), theta[0]*aux, theta[1]*aux, theta[2]*aux);
DeltaOrientation.normalize();
}
else {
double aux = std::sin(thetaMag)/thetaMag;
DeltaOrientation = Quaternion<double>(cos(thetaMag), theta[0]*aux, theta[1]*aux, theta[2]*aux);
DeltaOrientation.normalize();
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////******EULER ANGLES from 2 vectors******/////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*static inline void CalculateEulerAngles(const array_1d<double,3>& OriginalVector_X, const array_1d<double,3>& OriginalVector_Z,
const array_1d<double,3>& RotatedVector_X, const array_1d<double,3>& RotatedVector_Z, array_1d<double,3>& EulerAngles)
{
array_1d< double,3 > N = ZeroVector(3);
CrossProduct( OriginalVector_Z, RotatedVector_Z, N);
double return1 = DotProduct(N,OriginalVector_X); //cos(Alpha)
double return2 = DotProduct(OriginalVector_Z, RotatedVector_Z); //cos(Beta)
double return3 = DotProduct(N,RotatedVector_X); //cos(Gamma)
EulerAngles[0] = acos(return1);
EulerAngles[1] = acos(return2);
EulerAngles[2] = acos(return3);
}*/
static inline bool InsideOutside(const array_1d<double, 3>& Coord1,
const array_1d<double, 3>& Coord2,
const array_1d<double, 3>& JudgeCoord,
const array_1d<double, 3>& normal_element,
double& area){
//NOTE:: Normal_out here has to be the normal of the element orientation (not pointing particle)
double b[3];
double p1[3];
double coor[3];
DEM_COPY_SECOND_TO_FIRST_3(coor, Coord1)
b[0] = Coord2[0] - coor[0];
b[1] = Coord2[1] - coor[1];
b[2] = Coord2[2] - coor[2];
p1[0] = JudgeCoord[0] - coor[0];
p1[1] = JudgeCoord[1] - coor[1];
p1[2] = JudgeCoord[2] - coor[2];
DEM_SET_TO_CROSS_OF_FIRST_TWO_3(b, p1, coor)
if (DEM_INNER_PRODUCT_3(coor, normal_element) >= 0){
area = 0.5 * DEM_MODULUS_3(coor);
return true;
}
else return false;
}//InsideOutside
static inline bool InsideOutside(const array_1d<double, 3> &Coord1,
const array_1d<double, 3>& Coord2,
const array_1d<double, 3>& JudgeCoord,
const array_1d<double, 3>& normal_element) {
//NOTE:: Normal_out here has to be the normal of the element orientation (not pointing particle)
array_1d<double, 3> cp1;
array_1d<double, 3> b_a;
array_1d<double, 3> p1_a;
noalias(b_a) = Coord2 - Coord1;
noalias(p1_a) = JudgeCoord - Coord1;
GeometryFunctions::CrossProduct(b_a, p1_a, cp1);
if (GeometryFunctions::DotProduct(cp1, normal_element) >= 0)
{
//area = sqrt(cp1[0] * cp1[0] + cp1[1] * cp1[1] + cp1[2] * cp1[2]) * 0.5;
return true;
}
else return false;
}//InsideOutside
static inline void WeightsCalculation(std::vector<double> Area, std::vector<double>& Weight)
{
unsigned int facet_size = Area.size();
if (facet_size == 3)
{
const double total_area = Area[0]+Area[1]+Area[2];
const double inv_total_area = 1.0 / total_area;
for (unsigned int i = 0; i< 3; i++)
{
Weight[i] = Area[(i+1)%facet_size] * inv_total_area;
}
}
else if (facet_size == 4)
{
const double total_discriminant = Area[0]*Area[1]+Area[1]*Area[2]+Area[2]*Area[3]+Area[3]*Area[0]; //(Zhong et al 1993)
const double inv_total_discriminant = 1.0 / total_discriminant;
for (unsigned int i = 0; i< 4; i++)
{
Weight[i] = (Area[(i+1)%facet_size]*Area[(i+2)%facet_size]) * inv_total_discriminant;
}
}
else {
KRATOS_WATCH("WEIGHTS FOR N-SIZE POLYGONAL FE TO BE IMPLEMENTED")
}
}//WeightsCalculation
static inline bool FastFacetCheck(const std::vector< array_1d <double,3> >& Coord, const array_1d <double,3>& Particle_Coord, double rad, double &DistPToB, unsigned int ¤t_edge_index)
{
double A[3];
double B[3];
double PC[3];
for (unsigned int i = 0; i < 3; i++){
B[i] = Coord[0][i];
PC[i] = Coord[1][i];
A[i] = Coord[2][i];
}
for (unsigned int i = 0; i < 3; i++){
A[i] = A[i] - PC[i];
B[i] = B[i] - PC[i];
PC[i] = Particle_Coord[i] - PC[i];
}
//Calculate Normal
double N_fast[3];
DEM_SET_TO_CROSS_OF_FIRST_TWO_3(A, B, N_fast)
//normalize
double normal_flag = 1.0;
if (DEM_INNER_PRODUCT_3(PC, N_fast) < 0){ //it is assumed that Indentation wont be greater than radius so we can detect contacts on both sides of the FE.
normal_flag = -1.0;
}
normalize(N_fast);
//Calculate distance:
DistPToB = 0.0;
for (unsigned int i = 0; i < 3; i++){
DistPToB += normal_flag * N_fast[i] * PC[i];
}
if (DistPToB < rad){
array_1d <double, 3> IntersectionCoord;
array_1d <double, 3> N;
for (unsigned int i = 0; i < 3; i++){
IntersectionCoord[i] = Particle_Coord[i] - DistPToB * normal_flag * N_fast[i];
N[i] = N_fast[i];
}
int facet_size = Coord.size();
for (int i = 0; i < facet_size; i++) {
double this_area = 0.0;
if (InsideOutside(Coord[i], Coord[(i+1)%facet_size], IntersectionCoord, N, this_area) == false){
current_edge_index = i;
return false;
}
}
return true;
}//if DistPToB < rad
return false;
}//FastFacetCheck
static inline bool FacetCheck(const GeometryType& Coord, const array_1d <double,3>& Particle_Coord, double rad,
double LocalCoordSystem[3][3], double& DistPToB, std::vector<double>& Weight, unsigned int& current_edge_index)
{
int facet_size = Coord.size();
//Calculate Normal
array_1d <double,3> A;
array_1d <double,3> B;
array_1d <double,3> N;
array_1d <double,3> PC;
for (unsigned int i = 0; i<3; i++)
{
A[i] = Coord[2].Coordinates()[i]-Coord[1].Coordinates()[i];
B[i] = Coord[0].Coordinates()[i]-Coord[1].Coordinates()[i];
PC[i] = Particle_Coord[i]-Coord[1].Coordinates()[i];
}
N[0] = A[1]*B[2] - A[2]*B[1];
N[1] = A[2]*B[0] - A[0]*B[2];
N[2] = A[0]*B[1] - A[1]*B[0];
//normalize
double normal_flag = 1.0;
if (DotProduct(PC,N) < 0) //it is assumed that Indentation wont be greater than radius so we can detect contacts on both sides of the FE.
{
normal_flag = - 1.0;
N[0]=-N[0];
N[1]=-N[1];
N[2]=-N[2];
}
normalize(N);
//Calculate distance:
DistPToB = 0.0;
for (unsigned int i = 0; i<3; i++)
{
DistPToB += N[i]*PC[i];
}
if (DistPToB < rad )
{
array_1d <double,3> IntersectionCoord;
for (unsigned int i = 0; i<3; i++)
{
IntersectionCoord[i] = Particle_Coord[i] - DistPToB*N[i];
}
std::vector<double> Area;
Area.resize(facet_size);
for (int i = 0; i<facet_size; i++)
{
double this_area = 0.0;
if (InsideOutside(Coord[i],
Coord[(i+1)%facet_size],
IntersectionCoord,
normal_flag*N,
this_area) == false)
{
current_edge_index = i;
return false;
}
else
{
Area[i] = this_area; //the area adjacent to vertex[ID] is assigned as Area[ID] so further treatment shall be done for the Weight calculation
}
}//for every vertex
double auxiliar_unit_vector[3];
CrossProduct( N,A,auxiliar_unit_vector );
normalize( auxiliar_unit_vector );
normalize( A );
for (unsigned int j = 0; j<3; j++)
{
LocalCoordSystem[0][j] = A[j];
LocalCoordSystem[1][j] = auxiliar_unit_vector[j];
LocalCoordSystem[2][j] = N[j];
}
WeightsCalculation(Area,Weight);
return true;
}//if DistPToB < rad
return false;
} //FacetCheck
static inline bool FastEdgeVertexCheck(const array_1d<double,3>& Coord1, const array_1d<double,3>& Coord2, const array_1d<double,3>& Particle_Coord, double Radius)
{
double IntersectionCoordEdge[3];
double normal_unit_vector[3];
double edge_unit_vector[3];
double module_edge_vector = 0.0;
double particle_vector1[3];
double particle_vector2[3];
for (unsigned int j = 0; j<3; j++)
{
edge_unit_vector[j] = Coord2[j] - Coord1[j];
particle_vector1[j] = Particle_Coord[j] - Coord1[j];
particle_vector2[j] = Particle_Coord[j] - Coord2[j];
}
normalize( edge_unit_vector, module_edge_vector);
double projection_on_edge = DotProduct(particle_vector1,edge_unit_vector);
double eta = projection_on_edge/module_edge_vector;
if ((eta>=0.0) && (eta<=1.0)) //can only be edge, no vertex
{
for (unsigned int j = 0; j<3; j++)
{
IntersectionCoordEdge[j] = Coord1[j] + projection_on_edge*edge_unit_vector[j];
normal_unit_vector[j] = Particle_Coord[j] - IntersectionCoordEdge[j];
}
double DistParticleToEdge;
normalize( normal_unit_vector, DistParticleToEdge);
if (DistParticleToEdge < Radius)
{
return true;
}
}
if (eta < 0.0) //1rst Vertex
{
double dist_to_vertex_sq = 0.0;
double Rad_sq = Radius*Radius;
for (unsigned int j = 0; j<3; j++)
{
dist_to_vertex_sq +=particle_vector1[j]*particle_vector1[j];
}
if (dist_to_vertex_sq < Rad_sq)
{
return true;
}
}
if (eta > 1.0) //2n vertex
{
double dist_to_vertex_sq = 0.0;
double Rad_sq = Radius*Radius;
for (unsigned int j = 0; j<3; j++)
{
dist_to_vertex_sq +=particle_vector2[j]*particle_vector2[j];
}
if (dist_to_vertex_sq < Rad_sq)
{
return true;
}
}
return false;
}//FastEdgeVertexCheck;
static inline bool EdgeCheck(const array_1d<double,3>& Coord1, const array_1d<double,3>& Coord2, const array_1d<double,3>& Particle_Coord, double Radius,
double LocalCoordSystem[3][3], double& DistParticleToEdge, double& eta)
{
double IntersectionCoordEdge[3];
double normal_unit_vector[3];
double edge_unit_vector[3];
double module_edge_vector = 0.0;
double particle_vector[3];
for (unsigned int j = 0; j<3; j++)
{
edge_unit_vector[j] = Coord2[j] - Coord1[j];
particle_vector[j] = Particle_Coord[j] - Coord1[j];
}
normalize(edge_unit_vector, module_edge_vector);
double projection_on_edge = DotProduct(particle_vector,edge_unit_vector);
for (unsigned int j = 0; j<3; j++)
{
IntersectionCoordEdge[j] = Coord1[j] + projection_on_edge*edge_unit_vector[j];
normal_unit_vector[j] = Particle_Coord[j] - IntersectionCoordEdge[j];
}
normalize( normal_unit_vector, DistParticleToEdge);
if (DistParticleToEdge < Radius)
{
eta = projection_on_edge/module_edge_vector;
if ((eta>=0.0) && (eta<=1.0))
{
double dummy_length = 0.0;
double auxiliar_unit_vector[3];
CrossProduct(normal_unit_vector,edge_unit_vector,auxiliar_unit_vector);
normalize(auxiliar_unit_vector, dummy_length);
for (unsigned int j = 0; j<3; j++)
{
LocalCoordSystem[0][j] = edge_unit_vector[j];
LocalCoordSystem[1][j] = auxiliar_unit_vector[j];
LocalCoordSystem[2][j] = normal_unit_vector[j];
}
return true;
}
} //if distance to edge < radius
return false;
}//EdgeCheck
static inline bool VertexCheck(const array_1d<double,3>& Coord, const array_1d<double,3>& Particle_Coord, double Radius, double LocalCoordSystem[3][3], double& DistParticleToVertex)
{
double dist_sq = 0.0;
array_1d<double, 3> normal_v;
for (unsigned int j = 0; j < 3; j++)
{
normal_v[j] = Particle_Coord[j] - Coord[j];
dist_sq += normal_v[j] * normal_v[j];
}
if (dist_sq <= Radius * Radius)
{
DistParticleToVertex = sqrt(dist_sq);
ComputeContactLocalCoordSystem(normal_v, DistParticleToVertex, LocalCoordSystem);
return true;
}
return false;
}//VertexCheck
static inline bool FastVertexCheck(const array_1d<double,3>& Coord, const array_1d<double,3>& Particle_Coord, double Radius)
{
double dist_sq = 0.0;
array_1d<double, 3> normal_v;
for (unsigned int j = 0; j < 3; j++)
{
normal_v[j] = Particle_Coord[j] - Coord[j];
dist_sq += normal_v[j] * normal_v[j];
}
if (dist_sq <= Radius * Radius) return true;
return false;
}//FastVertexCheck
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////******The four Functions BELOW are used to calculate the weight coefficient for quadrilateral*******///////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*static inline void Coord_transform(double origin[3], double coordsystem[3][3], double Coord[3], double TransCoord[3])
{
TransCoord[0]=0.0;
TransCoord[1]=0.0;
TransCoord[2]=0.0;
double vector[3];
vector[0]=Coord[0] - origin[0];
vector[1]=Coord[1] - origin[1];
vector[2]=Coord[2] - origin[2];
TransCoord[0]=DotProduct(coordsystem[0],vector);
TransCoord[1]=DotProduct(coordsystem[1],vector);
TransCoord[2]=DotProduct(coordsystem[2],vector);
}*/
/*static inline void N44(double xp,double yp,double xy[4][2],double& N1,double& N2,double& N3,double& N4)
{
double xc=(xy[0][0]+xy[1][0]+xy[2][0]+xy[3][0])/4.0;
double yc=(xy[0][1]+xy[1][1]+xy[2][1]+xy[3][1])/4.0;
double elelength_x=2.0*fabs(xy[0][0]-xc);
double elelength_y=2.0*fabs(xy[0][1]-yc);
double Eps,Ita;
Eps=2.0*(xp-xc)/elelength_x;
Ita=2.0*(yp-yc)/elelength_y;
N1=0.25*(1+Eps*2*(xy[0][0]-xc)/elelength_x)*(1+Ita*2*(xy[0][1]-yc)/elelength_y);
N2=0.25*(1+Eps*2*(xy[1][0]-xc)/elelength_x)*(1+Ita*2*(xy[1][1]-yc)/elelength_y);
N3=0.25*(1+Eps*2*(xy[2][0]-xc)/elelength_x)*(1+Ita*2*(xy[2][1]-yc)/elelength_y);
N4=0.25*(1+Eps*2*(xy[3][0]-xc)/elelength_x)*(1+Ita*2*(xy[3][1]-yc)/elelength_y);
}*/
//Cfeng: irregular quadrilateral transfer to regular quadrilateral
/*static inline void gl_to_iso(double x0, double y0, double xy[4][2], double& x_exisp, double& y_etasp)
{
double exisp=0.0;
double etasp=0.0;
double tolerance=1.0e-8;
double x,y,x1,x2,x3,x4,y1,y2,y3,y4,a1,a2,a3,a4,b1,b2,b3,b4,s1,t1,d1,g1,g2,g0;
x1 = xy[0][0];
x2 = xy[1][0];
x3 = xy[2][0];
x4 = xy[3][0];
y1 = xy[0][1];
y2 = xy[1][1];
y3 = xy[2][1];
y4 = xy[3][1];
a1=0.25*(-x1+x2+x3-x4);
a2=0.25*(x1-x2+x3-x4);
a3=0.25*(-x1-x2+x3+x4);
a4=0.25*(x1+x2+x3+x4);
b1=0.25*(-y1+y2+y3-y4);
b2=0.25*(y1-y2+y3-y4);
b3=0.25*(-y1-y2+y3+y4);
b4=0.25*(y1+y2+y3+y4);
x = x0 - a4;
y = y0 - b4;
s1 = a2*b3 - a3*b2;
t1 = b2*x - a2*y + a1*b3 - a3*b1;
d1 = b1*x - a1*y;
if (fabs(s1) < tolerance)
{
etasp = -d1/t1;
exisp = (x-a3*etasp) / (a1+a2*etasp);
}
else
{
const double sqrt_aux = sqrt(t1*t1-4*s1*d1);
g1 = (-t1 + sqrt_aux) / (2*s1);
g2 = (-t1 - sqrt_aux) / (2*s1);
if (fabs(g1) < 1.0+tolerance)
{
g0 = (x-a3*g1) / (a1+a2*g1);
if (fabs(g0) < 1.0+tolerance)
{
etasp = g1;
exisp = g0;
}
}
if(fabs(g2) < 1.0+tolerance)
{
g0 = (x-a3*g2) / (a1+a2*g2);
if(fabs(g0) < 1.0+tolerance)
{
etasp = g2;
exisp = g0;
}
}
}
x_exisp=exisp;
y_etasp=etasp;
}*/
/*static void CalQuadWeightCoefficient(double Coord[4][3], double LocalCoordSystem[3][3], double IntersectionCoord[3], double Weight[4])
{
int j;
double FaceCenter[3] = {0.0};
for(j = 0; j < 4; j++)
{
FaceCenter[0] += Coord[j][0] * 0.25;
FaceCenter[1] += Coord[j][1] * 0.25;
FaceCenter[2] += Coord[j][2] * 0.25;
}
double TransCoord0[3],TransCoord1[3],TransCoord2[3],TransCoord3[3];
double xy[4][2];
double xy1[4][2]={{-1.0,-1.0},{1.0,-1.0},{1.0,1.0},{-1.0,1.0}};
double TempLocalCoordSystem[3][3]={{0.0}, {0.0}, {0.0}};
double vx[3]={1.0,0,0},vy[3]={0,1.0,0},vz[3]={0, 0, 1.0};
if( DotProduct(LocalCoordSystem[2],vx)<0 || DotProduct(LocalCoordSystem[2],vy)<0 || DotProduct(LocalCoordSystem[2],vz)<0 )
{
for(j=0;j<3;j++)
{
TempLocalCoordSystem[0][j] = LocalCoordSystem[0][j];
TempLocalCoordSystem[1][j] = LocalCoordSystem[1][j];
TempLocalCoordSystem[2][j] = -LocalCoordSystem[2][j];
}
}
else
{
for(j=0;j<3;j++)
{
TempLocalCoordSystem[0][j] = LocalCoordSystem[0][j];
TempLocalCoordSystem[1][j] = LocalCoordSystem[1][j];
TempLocalCoordSystem[2][j] = LocalCoordSystem[2][j];
}
}
Coord_transform(FaceCenter, TempLocalCoordSystem, Coord[0], TransCoord0);
Coord_transform(FaceCenter, TempLocalCoordSystem, Coord[1], TransCoord1);
Coord_transform(FaceCenter, TempLocalCoordSystem, Coord[2], TransCoord2);
Coord_transform(FaceCenter, TempLocalCoordSystem, Coord[3], TransCoord3);
xy[0][0] = TransCoord0[0]; xy[0][1] = TransCoord0[1];
xy[1][0] = TransCoord1[0]; xy[1][1] = TransCoord1[1];
xy[2][0] = TransCoord2[0]; xy[2][1] = TransCoord2[1];
xy[3][0] = TransCoord3[0]; xy[3][1] = TransCoord3[1];
double in0=0.0, in1=0.0, in2=0.0, in3=0.0;
double TransCoordp[3];
double Coordp_iso[2];
Coord_transform(FaceCenter, TempLocalCoordSystem, IntersectionCoord, TransCoordp);
gl_to_iso(TransCoordp[0],TransCoordp[1],xy,Coordp_iso[0],Coordp_iso[1]);
N44(Coordp_iso[0],Coordp_iso[1], xy1, in0, in1, in2, in3);
Weight[0]=in0;
Weight[1]=in1;
Weight[2]=in2;
Weight[3]=in3;
}*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////******The four Functions ABOVE are used to calculate the weight coefficient for quadrilateral*******///////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static inline void GetRotationMatrix(const array_1d<double, 3>& EulerAngles, double rotation_matrix[3][3]) {
double cosA=cos(EulerAngles[0]);
double sinA=sin(EulerAngles[0]);
double cosB=cos(EulerAngles[1]);
double sinB=sin(EulerAngles[1]);
double cosC=cos(EulerAngles[2]);
double sinC=sin(EulerAngles[2]);
rotation_matrix[0][0] = cosC*cosA - cosB*sinA*sinC;
rotation_matrix[0][1] = -sinC*cosA - cosB*sinA*cosC;
rotation_matrix[0][2] = sinB*sinA;
rotation_matrix[1][0] = cosC*sinA + cosB*cosA*sinC;
rotation_matrix[1][1] = -sinC*sinA + cosB*cosA*cosC;
rotation_matrix[1][2] = -sinB*cosA;
rotation_matrix[2][0] = sinC*sinB;
rotation_matrix[2][1] = cosC*sinB;
rotation_matrix[2][2] = cosB;
return;
}
static inline void GetEulerAngles(const double rotation_matrix[3][3], array_1d<double, 3 > & EulerAngles)
{
if (rotation_matrix[2][2] < 1.0)
{
if (rotation_matrix[2][2] > -1.0) {
EulerAngles[0] = atan2(rotation_matrix[0][2], -rotation_matrix[1][2]);
EulerAngles[1] = acos(rotation_matrix[2][2]);
EulerAngles[2] = atan2(rotation_matrix[2][0], rotation_matrix[2][1]);
}
else // r22 = -1
{
// Not a unique solution: thetaZ1 - thetaZ0 = atan2(-r01,r00)
EulerAngles[0] = -atan2(-rotation_matrix[0][1], rotation_matrix[0][0]);
EulerAngles[1] = Globals::Pi;
EulerAngles[2] = 0;
}
}
else // r22 = +1
{
// Not a unique solution: thetaZ1 + thetaZ0 = atan2(-r01,r00)
EulerAngles[0] = atan2(-rotation_matrix[0][1], rotation_matrix[0][0]);
EulerAngles[1] = 0;
EulerAngles[2] = 0;
}
return;
}
static inline void GetGiDEulerAngles(const BoundedMatrix<double, 3, 3>& rotation_matrix, array_1d<double, 3>& EulerAngles) {
const double numerical_limit = std::numeric_limits<double>::epsilon();
const double two_pi = 3.1415926535897932384626433 * 2.0;
if(rotation_matrix(2, 2)<1.0-numerical_limit && rotation_matrix(2, 2)>-1.0+numerical_limit){
const double senb=sqrt(1.0-rotation_matrix(2, 2)*rotation_matrix(2, 2));
EulerAngles[1]=acos(rotation_matrix(2, 2));
EulerAngles[2]=acos(rotation_matrix(1, 2)/senb);
if(rotation_matrix(0, 2)/senb<0.0) EulerAngles[2]=two_pi - EulerAngles[2];
EulerAngles[0]=acos(-rotation_matrix(2, 1)/senb);
if(rotation_matrix(2, 0)/senb<0.0) EulerAngles[0]=two_pi - EulerAngles[0];
} else {
// fixed a=0.0 (arbitrary)
EulerAngles[1]=acos(rotation_matrix(2, 2));
EulerAngles[0]=0.0;
EulerAngles[2]=acos(rotation_matrix(0, 0));
if(-rotation_matrix(1, 0)<0.0) EulerAngles[2]=two_pi - EulerAngles[2];
}
}
inline void QuaternionToGiDEulerAngles(const Quaternion<double>& quaternion, array_1d<double, 3>& EulerAngles) {
BoundedMatrix<double, 3, 3> rotation_matrix = ZeroMatrix(3,3);
quaternion.ToRotationMatrix(rotation_matrix);
GetGiDEulerAngles(rotation_matrix, EulerAngles);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////****************************TRIANGLE - SPHERE INTERSECTION AREA CALCULATION**************************///////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static inline void TriAngleArea(double Coord1[3], double Coord2[3], double Coord3[3], double& area)
{
int k;
double Vector1[3],Vector2[3],Vector0[3];
for (k = 0;k < 3; k++)
{
Vector1[k] = Coord3[k] - Coord1[k];
Vector2[k] = Coord2[k] - Coord1[k];
}
CrossProduct(Vector1, Vector2, Vector0);
area = 0.5 * DEM_MODULUS_3(Vector0);
}
//TriAngle Weight, coord1,coord2,coord3,testcoord,weight
static inline void TriAngleWeight(double Coord1[3], double Coord2[3], double Coord3[3], double JudgeCoord[3], double Weight[3])
{
double area[3], s;
TriAngleArea(Coord1, Coord2, JudgeCoord, area[0]);
TriAngleArea(Coord2, Coord3, JudgeCoord, area[1]);
TriAngleArea(Coord3, Coord1, JudgeCoord, area[2]);
TriAngleArea(Coord1, Coord2, Coord3, s);
/////s = area[0] + area[1] + area[2];
const double s_inv = 1.0 / s;
Weight[0] = area[1] * s_inv;
Weight[1] = area[2] * s_inv;
Weight[2] = area[0] * s_inv;
}
//Quadrilatera Weight, coord1,coord2,coord3,testcoord,weight (Paper Zhang)
static inline void QuadAngleWeight(double Coord1[3], double Coord2[3], double Coord3[3], double Coord4[3], double JudgeCoord[3], double Weight[4])
{
double area[4], s1, s2, s;
TriAngleArea(Coord1, Coord2, JudgeCoord, area[0]);
TriAngleArea(Coord2, Coord3, JudgeCoord, area[1]);
TriAngleArea(Coord3, Coord4, JudgeCoord, area[2]);
TriAngleArea(Coord4, Coord1, JudgeCoord, area[3]);
TriAngleArea(Coord1, Coord2, Coord3, s1);//msimsi
TriAngleArea(Coord1, Coord3, Coord4, s2);//msimsi
s = s1 + s2;
if (fabs(area[0] + area[1] + area[2] + area[3] - s) < 1.0e-15) //msimsi
{
double QuadNormArea = 1 / ((area[0] + area[2]) * (area[1] + area[3]));
Weight[0] = (area[1] * area[2]) * QuadNormArea;
Weight[1] = (area[2] * area[3]) * QuadNormArea;
Weight[2] = (area[3] * area[0]) * QuadNormArea;
Weight[3] = (area[0] * area[1]) * QuadNormArea;
}
}
static inline void AreaAndCentroidCircularSector(double C[3], double Radius, double P1[3], double P2[3], double Normal[3], double& Area, double CoMSC[3])
{
double a[3] = {0.0};
double c[3] = {0.0};
double bisection[3] = {0.0};
double norm_a = 0.0;
for (unsigned int index = 0;index<3;index++) {
a[index] = P1[index]-C[index];
c[index] = P2[index]-P1[index];
}
CrossProduct(Normal,c,bisection);
normalize(bisection);
double dot_product = DotProduct(bisection,a);
if (dot_product<0.0) {
for (unsigned int index = 0;index<3;index++) {
bisection[index] = -bisection[index];
}
dot_product = -dot_product;
}
module(a, norm_a);
double cos_alpha = dot_product/norm_a;
double alpha = acos(cos_alpha);
double sin_alpha = std::sin(alpha);
Area = Radius*Radius*alpha;
double dist = 0.66666666666666*(Radius*sin_alpha/alpha);
for (unsigned int index = 0;index<3;index++) {
CoMSC[index] = C[index]+dist*bisection[index];
}
}//AreaCircularSector
static inline void AlternativeAreaCircularSegment(double Radius, double tol_Radius, double V0V1[3], double V0CC[3], double Normal[3], double& AreaSC, bool& flag)
{
double normal_outwards[3] = {0.0};
flag = false;
AreaSC = 0.0;
CrossProduct(V0V1, Normal, normal_outwards);
normalize(normal_outwards);
double dist = DotProduct(normal_outwards,V0CC);
double delta_circle = Radius + dist; //distance can be positive or negative, depending on the side where the circle is
if ((delta_circle > tol_Radius) && (delta_circle - 2*Radius < -tol_Radius)) {//check for intersection
flag = true;
double b = sqrt(delta_circle*(2*Radius-delta_circle));
AreaSC = 2.0*Radius*Radius*atan(delta_circle/b)-b*(Radius-delta_circle);
}
}//AreaAndCentroidCircularSector1
static inline void AreaAndCentroidCircularSegment(double Centre[3], double Radius, double tol_Radius, double V0[3], double V1[3], double Normal[3], double& AreaSegC, double CoMSegC[3], bool& flag)
{
double V0V1[3] = {0.0};
double V0CC[3] = {0.0};
double a[3] = {0.0};
double normal_outwards[3] = {0.0};
double Radius_SQ = 0.0;
double distance_V0V1 = 0.0;
double dist_CoM = 0.0;
AreaSegC = 0.0;
flag = false;
for (unsigned int index = 0; index<3; index++) {
V0V1[index] = V1[index] - V0[index];
V0CC[index] = Centre[index] - V0[index];
}
GeometryFunctions::CrossProduct(V0V1,Normal,normal_outwards);
GeometryFunctions::normalize(V0V1,distance_V0V1);
double distV0 = GeometryFunctions::DotProduct(V0CC,V0V1);
if ((distV0 > 0.0) && (distV0 < distance_V0V1)) {
GeometryFunctions::normalize(normal_outwards);
double dist_normal = GeometryFunctions::DotProduct(normal_outwards,V0CC);
double delta_circle = Radius + dist_normal; //distance can be positive or negative, depending on the side where the circle is
if ((delta_circle > tol_Radius) && ( delta_circle - 2.0*Radius < -tol_Radius)) {//check for intersection
Radius_SQ = Radius*Radius;
double semi_dist = sqrt(Radius_SQ - dist_normal*dist_normal);
flag = true;
for (unsigned int index = 0;index<3;index++) {
a[index] = V0[index] + (distV0 - semi_dist)*V0V1[index] - Centre[index]; //Vector from Center to first intersection point
}
double cos_alpha = GeometryFunctions::DotProduct(a,normal_outwards)/(GeometryFunctions::module(a)*GeometryFunctions::module(normal_outwards));
double alpha = acos(cos_alpha);
double sin_alpha = std::sin(alpha);
AreaSegC = Radius_SQ*(alpha-sin_alpha*cos_alpha);
if (fabs(sin_alpha) < tol_Radius) {dist_CoM=0.0;}
else {dist_CoM = 0.6666666666666 * (Radius*sin_alpha*sin_alpha*sin_alpha/(alpha-sin_alpha*cos_alpha));}
for (unsigned int index = 0; index<3; index++) {
CoMSegC[index] = Centre[index] + dist_CoM*normal_outwards[index];
}
} //if normal dist is okay
} // if longitudinal dist is okay
}//AreaAndCentroidCircularSegment
static inline void AreaAndCentroidTriangle(double Coord1[3], double Coord2[3], double Coord3[3], double& area, double CoMTri[3]) {
TriAngleArea(Coord1,Coord2,Coord3,area);
for (unsigned int index =0; index<3; index++) {
CoMTri[index] = 0.33333333333333 * (Coord1[index]+Coord2[index]+Coord3[index]);
}
} //AreaAndCentroidTriangle
} //namespace GeometryFunctions
} //namespace Kratos
#endif /* _GEOMETRYFUNCTIONS_H */
|
BFEgg_fmt_plug.c | /*
* This file is part of Eggdrop blowfish patch for John The Ripper.
* Copyright (c) 2002 by Sun-Zero <sun-zero at freemail.hu>
* This is a free software distributable under terms of the GNU GPL.
*
* This format has collisions for repeated patterns (eg. "1" vs. "11",
* or "hey" vs. "heyheyheyhey") - you can run it with --keep-guessing
* if you'd like to see alternative plaintexts.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_BFEgg;
#elif FMT_REGISTERS_H
john_register_one(&fmt_BFEgg);
#else
#include <string.h>
#include "misc.h"
#include "formats.h"
#include "common.h"
#include "blowfish.c"
#ifdef _OPENMP
static int omp_t = 1;
#include <omp.h>
// Tuning on AMD A8 4500M laptop, cygwin64 with OMP(4x) -test=5
// 4 = 44330 (original)
// 16 = 54760
// 24 = 56151
// 32 = 56216
// 64 = 57770
// 96 = 57888
// 128 = 58016 > instant -test=0
// 256 = 58282 // from here on, not enough gain to matter.
// 512 = 58573
// 1024= 59464
// 4096= 59244 > 1s -test=0
#ifndef OMP_SCALE
#define OMP_SCALE 128
#endif
#endif
#include "memdbg.h"
#define FORMAT_LABEL "bfegg"
#define FORMAT_NAME "Eggdrop"
#define ALGORITHM_NAME "Blowfish 32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define PLAINTEXT_MIN_LENGTH 1
#define PLAINTEXT_LENGTH 72
#define CIPHERTEXT_LENGTH 13
#define BINARY_SIZE 7
#define BINARY_ALIGN 4
#define SALT_SIZE 0
#define SALT_ALIGN 1
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
static struct fmt_tests tests[] = {
{"+9F93o1OxwgK1", "123456"},
{"+C/.8o.Wuph9.", "qwerty"},
{"+EEHgy/MBLDd0", "walkman"},
{"+vPBrs07OTXE/", "tesztuser"},
{"+zIvO/1nDsd9.", "654321"},
{"+V6ZOx0rVGWT0", "1"},
{"+V6ZOx0rVGWT0", "11"},
{"+Obytd.zXYjH/", "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static uint32_t (*crypt_out)[(BINARY_SIZE + 1) / sizeof(uint32_t)];
#if defined (_MSC_VER) || defined (__MINGW32__)
// in VC, _atoi64 is a function.
#define _atoi64 JtR_atoi64
#endif
static const char _itoa64[] = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static char _atoi64[0x100];
static int valid(char *ciphertext, struct fmt_main *self) {
char *pos;
if (*ciphertext != '+') return 0;
if (strnlen(ciphertext, CIPHERTEXT_LENGTH + 1) != CIPHERTEXT_LENGTH) return 0;
for (pos = &ciphertext[1]; atoi64[ARCH_INDEX(*pos)] != 0x7F; pos++);
if (*pos || pos - ciphertext != CIPHERTEXT_LENGTH) return 0;
return 1;
}
void init(struct fmt_main *self) {
const char *pos;
#ifdef _OPENMP
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#endif
saved_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_key));
crypt_out = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_out));
memset(_atoi64, 0x7F, sizeof(_atoi64));
for (pos = _itoa64; pos <= &_itoa64[63]; pos++)
_atoi64[ARCH_INDEX(*pos)] = pos - _itoa64;
}
static void done(void)
{
MEM_FREE(crypt_out);
MEM_FREE(saved_key);
}
/* The base64 is flawed - we just mimic flaws from the original code */
static void *get_binary(char *ciphertext)
{
static union toalign {
unsigned char c[BINARY_SIZE];
uint32_t a[1];
} a;
unsigned char *out = a.c;
uint32_t value;
char *pos;
pos = ciphertext + 1;
value = (uint32_t)_atoi64[ARCH_INDEX(pos[0])] |
((uint32_t)_atoi64[ARCH_INDEX(pos[1])] << 6) |
((uint32_t)_atoi64[ARCH_INDEX(pos[2])] << 12) |
((uint32_t)_atoi64[ARCH_INDEX(pos[3])] << 18);
out[0] = value;
out[1] = value >> 8;
out[2] = value >> 16;
out[3] = _atoi64[ARCH_INDEX(pos[4])] |
(_atoi64[ARCH_INDEX(pos[5])] << 6);
pos += 6;
value = (uint32_t)_atoi64[ARCH_INDEX(pos[0])] |
((uint32_t)_atoi64[ARCH_INDEX(pos[1])] << 6) |
((uint32_t)_atoi64[ARCH_INDEX(pos[2])] << 12) |
((uint32_t)_atoi64[ARCH_INDEX(pos[3])] << 18);
out[4] = value;
out[5] = value >> 8;
out[6] = value >> 16;
return (void *)out;
}
static void set_key(char *key, int index) {
strnzcpy(saved_key[index], key, sizeof(*saved_key));
}
static char *get_key(int index) {
return saved_key[index];
}
static int cmp_all(void *binary, int count) {
int index = 0;
#ifdef _OPENMP
for (; index < count; index++)
#endif
if (!memcmp(binary, crypt_out[index], 4))
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return !memcmp(binary, crypt_out[index], BINARY_SIZE);
}
static int cmp_exact(char *source, int index)
{
return 1;
}
#define COMMON_GET_HASH_VAR crypt_out
#include "common-get-hash.h"
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
#ifdef _OPENMP
#pragma omp parallel for
for (index = 0; index < count; index++)
#endif
{
/*if (saved_key[index][0] == '\0') {
zerolengthkey = 1;
} else {
zerolengthkey = 0; */
if (saved_key[index][0] != 0)
blowfish_encrypt_pass(saved_key[index],
(char*)crypt_out[index]);
}
return count;
}
struct fmt_main fmt_BFEgg = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
PLAINTEXT_MIN_LENGTH,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP,
{ NULL },
{ NULL },
tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
fmt_default_split,
get_binary,
fmt_default_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash_0,
fmt_default_binary_hash_1,
fmt_default_binary_hash_2,
fmt_default_binary_hash_3,
fmt_default_binary_hash_4,
fmt_default_binary_hash_5,
fmt_default_binary_hash_6
},
fmt_default_salt_hash,
NULL,
fmt_default_set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
#define COMMON_GET_HASH_LINK
#include "common-get-hash.h"
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
slange.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/zlange.c, normal z -> s, Fri Sep 28 17:38:07 2018
*
**/
#include "plasma.h"
#include "plasma_async.h"
#include "plasma_context.h"
#include "plasma_descriptor.h"
#include "plasma_internal.h"
#include "plasma_tuning.h"
#include "plasma_types.h"
/***************************************************************************//**
*
* @ingroup plasma_lange
*
* Returns the norm of a general matrix as
*
* slange = ( max(abs(A(i,j))), NORM = PlasmaMaxNorm
* (
* ( norm1(A), NORM = PlasmaOneNorm
* (
* ( normI(A), NORM = PlasmaInfNorm
* (
* ( normF(A), NORM = PlasmaFrobeniusNorm
*
* where norm1 denotes the one norm of a matrix (maximum column sum),
* normI denotes the infinity norm of a matrix (maximum row sum) and
* normF denotes the Frobenius norm of a matrix (square root of sum
* of squares). Note that max(abs(A(i,j))) is not a consistent matrix
* norm.
*
*******************************************************************************
*
* @param[in] norm
* - PlasmaMaxNorm: max norm
* - PlasmaOneNorm: one norm
* - PlasmaInfNorm: infinity norm
* - PlasmaFrobeniusNorm: Frobenius norm
*
* @param[in] m
* The number of rows of the matrix A. m >= 0. When m = 0,
* the returned value is set to zero.
*
* @param[in] n
* The number of columns of the matrix A. n >= 0. When n = 0,
* the returned value is set to zero.
*
* @param[in] pA
* The m-by-n matrix A.
*
* @param[in] lda
* The leading dimension of the array A. lda >= max(1,m).
*
*******************************************************************************
*
* @retval float
* The specified norm of the general matrix A.
*
*******************************************************************************
*
* @sa plasma_omp_slange
* @sa plasma_clange
* @sa plasma_slange
* @sa plasma_slange
*
******************************************************************************/
float plasma_slange(plasma_enum_t norm,
int m, int n,
float *pA, int lda)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA not initialized");
return PlasmaErrorNotInitialized;
}
// Check input arguments.
if ((norm != PlasmaMaxNorm) && (norm != PlasmaOneNorm) &&
(norm != PlasmaInfNorm) && (norm != PlasmaFrobeniusNorm) ) {
plasma_error("illegal value of norm");
return -1;
}
if (m < 0) {
plasma_error("illegal value of m");
return -2;
}
if (n < 0) {
plasma_error("illegal value of n");
return -3;
}
if (lda < imax(1, m)) {
printf("%d\n", lda);
plasma_error("illegal value of lda");
return -5;
}
// quick return
if (imin(n, m) == 0)
return 0.0;
// Tune parameters.
if (plasma->tuning)
plasma_tune_lange(plasma, PlasmaRealFloat, m, n);
// Set tiling parameters
int nb = plasma->nb;
// Create tile matrices.
plasma_desc_t A;
int retval;
retval = plasma_desc_general_create(PlasmaRealFloat, nb, nb,
m, n, 0, 0, m, n, &A);
if (retval != PlasmaSuccess) {
plasma_error("plasma_desc_general_create() failed");
return retval;
}
// Allocate workspace.
float *work = NULL;
switch (norm) {
case PlasmaMaxNorm:
work = (float*)malloc((size_t)A.mt*A.nt*sizeof(float));
break;
case PlasmaOneNorm:
work = (float*)malloc(((size_t)A.mt*A.n+A.n)*sizeof(float));
break;
case PlasmaInfNorm:
work = (float*)malloc(((size_t)A.nt*A.m+A.m)*sizeof(float));
break;
case PlasmaFrobeniusNorm:
work = (float*)malloc((size_t)2*A.mt*A.nt*sizeof(float));
break;
}
if (work == NULL) {
plasma_error("malloc() failed");
return PlasmaErrorOutOfMemory;
}
// Initialize sequence.
plasma_sequence_t sequence;
retval = plasma_sequence_init(&sequence);
// Initialize request.
plasma_request_t request;
retval = plasma_request_init(&request);
float value;
// asynchronous block
#pragma omp parallel
#pragma omp master
{
// Translate to tile layout.
plasma_omp_sge2desc(pA, lda, A, &sequence, &request);
// Call tile async function.
plasma_omp_slange(norm, A, work, &value, &sequence, &request);
}
// implicit synchronization
free(work);
// Free matrix in tile layout.
plasma_desc_destroy(&A);
// Return the norm.
return value;
}
/***************************************************************************//**
*
* @ingroup plasma_lange
*
* Calculates the max, one, infinity or Frobenius norm of a general matrix.
* Non-blocking equivalent of plasma_slange(). May return before the
* computation is finished. Operates on matrices stored by tiles. All matrices
* are passed through descriptors. All dimensions are taken from the
* descriptors. Allows for pipelining of operations at runtime.
*
*******************************************************************************
*
* @param[in] norm
* - PlasmaMaxNorm: Max norm
* - PlasmaOneNorm: One norm
* - PlasmaInfNorm: Infinity norm
* - PlasmaFrobeniusNorm: Frobenius norm
*
* @param[in] A
* The descriptor of matrix A.
*
* @param[out] work
* Workspace of size:
* - PlasmaMaxNorm: A.mt*A.nt
* - PlasmaOneNorm: A.mt*A.n + A.n
* - PlasmaInfNorm: A.nt*A.m + A.m
* - PlasmaFrobeniusNorm: 2*A.mt*A.nt
*
* @param[out] value
* The calculated value of the norm requested.
*
* @param[in] sequence
* Identifies the sequence of function calls that this call belongs to
* (for completion checks and exception handling purposes).
*
* @param[out] request
* Identifies this function call (for exception handling purposes).
*
* @retval void
* Errors are returned by setting sequence->status and
* request->status to error values. The sequence->status and
* request->status should never be set to PlasmaSuccess (the
* initial values) since another async call may be setting a
* failure value at the same time.
*
*******************************************************************************
*
* @sa plasma_slange
* @sa plasma_omp_clange
* @sa plasma_omp_slange
* @sa plasma_omp_slange
*
******************************************************************************/
void plasma_omp_slange(plasma_enum_t norm, plasma_desc_t A,
float *work, float *value,
plasma_sequence_t *sequence, plasma_request_t *request)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA not initialized");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
// Check input arguments.
if ((norm != PlasmaMaxNorm) && (norm != PlasmaOneNorm) &&
(norm != PlasmaInfNorm) && (norm != PlasmaFrobeniusNorm)) {
plasma_error("illegal value of norm");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (plasma_desc_check(A) != PlasmaSuccess) {
plasma_error("invalid descriptor A");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (sequence == NULL) {
plasma_error("NULL sequence");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (request == NULL) {
plasma_error("NULL request");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
// quick return
if (imin(A.m, A.n) == 0) {
*value = 0.0;
return;
}
// Call the parallel function.
plasma_pslange(norm, A, work, value, sequence, request);
}
|
f_aligned.c | /* Example of the aligned clause on the simd construct
The aligned clause asserts that the value of the pointer
variable x is always aligned on a 16 byte boundary.
With this information, the compiler may generate wider and
more efficient vector load and store instructions.
*/
void f_aligned(float *x, float scale, int n)
{
int i;
#pragma omp simd aligned(x:16)
for (i=0; i<n; i++)
x[i] = x[i]*scale;
}
|
mxEvaluateFlux1d.c | #include "../../@SWEAbstract1d/private/mxSWE1d.h"
#include "mex.h"
#ifdef _OPENMP
#include <omp.h>
#endif
void evaluateNodalFlux(double hcrit, double gra, double h, double qx, double z,
double *Eh, double *Eqx) {
double h2 = 0.5 * gra * (h * h - z * z);
if (h > hcrit) {
*Eh = qx;
*Eqx = (qx * qx / h + h2);
} else { // for dry nodes
*Eh = 0;
*Eqx = 0;
}
return;
}
#define NRHS 4
#define NLHS 1
#define NVAR 2
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
/* check input & output */
if (nrhs != NRHS) {
mexPrintf("Matlab:%s:InvalidNumberInput,\n", __FILE__);
mexPrintf("%d inputs required.\n", NRHS);
}
if (nlhs != NLHS) {
mexPrintf("Matlab:%s:InvalidNumberOutput,\n", __FILE__);
mexPrintf("%d inputs required.\n", NLHS);
}
double hcrit = mxGetScalar(prhs[0]);
double gra = mxGetScalar(prhs[1]);
signed char *regType = (signed char *)mxGetData(prhs[2]);
// double *fphys = mxGetPr(prhs[3]);
PhysField1d fphys = convertMexToPhysField(prhs[3]);
const size_t Np = fphys.Np;
const size_t K = fphys.K;
// const mwSize *dims = mxGetDimensions(prhs[3]);
// const size_t Np = dims[0];
// const size_t K = dims[1];
// const size_t ndimOut = 3;
const mwSize dimOut[3] = {Np, K, NVAR};
plhs[0] = mxCreateNumericArray(3, dimOut, mxDOUBLE_CLASS, mxREAL);
PhysField1d E = convertMexToPhysField(plhs[0]);
#ifdef _OPENMP
#pragma omp parallel for num_threads(DG_THREADS)
#endif
for (int k = 0; k < K; k++) {
NdgRegionType type = (NdgRegionType)regType[k];
if (type == NdgRegionDry) {
continue;
}
for (int n = 0; n < Np; n++) {
size_t sk = k * Np + n;
evaluateNodalFlux(hcrit, gra, fphys.h[sk], fphys.hu[sk], fphys.z[sk],
E.h + sk, E.hu + sk);
}
}
return;
} |
triangleCounting.h | int64_t T = 0 ;
void outputTriangleCounting(graph *G) {
printf("\nThe total number of Triangles = %lld\n", T);
}
void triangleCounting(graph *G) {
inittracking("triangleCounting.csv");
T = 0;
#pragma omp parallel
{
int64_t T_private = 0;
node_t v;
#if defined(PARFOR_GUIDED)
#pragma omp for schedule(guided, PAR_CHUNKSIZE)
#elif defined(PARFOR_DYNAMIC)
#pragma omp for schedule(dynamic, PAR_CHUNKSIZE)
#elif defined(TASKLOOP_DEFINED)
#pragma omp taskloop num_tasks(NUM_TASKS)
#else
#pragma omp for schedule(static)
#endif
for (v = 0; v < G->numNodes; v ++) {
edge_t u_idx;
for (u_idx = G->begin[v]; u_idx < G->begin[v+1]; u_idx ++) {
node_t u = G->node_idx [u_idx];
if (u > v) {
edge_t w_idx;
for (w_idx = G->begin[v]; w_idx < G->begin[v+1]; w_idx ++) {
node_t w = G->node_idx [w_idx];
if (w > u) {
edge_t s;
for(s= G->begin[w]; s < G->begin[w+1]; s++) {
node_t y = G->node_idx[s];
if(y == u) {
T_private = T_private + 1 ;
break;
}
}
}
}
}
}
}
#pragma omp atomic
T += T_private;
}
endtracking();
}
|
profile.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP RRRR OOO FFFFF IIIII L EEEEE %
% P P R R O O F I L E %
% PPPP RRRR O O FFF I L EEE %
% P R R O O F I L E %
% P R R OOO F IIIII LLLLL EEEEE %
% %
% %
% MagickCore Image Profile Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/colorspace-private.h"
#include "magick/configure.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/hashmap.h"
#include "magick/image.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/option-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/splay-tree.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread-private.h"
#include "magick/token.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_LCMS_DELEGATE)
#if defined(MAGICKCORE_HAVE_LCMS_LCMS2_H)
#include <wchar.h>
#include <lcms/lcms2.h>
#else
#include <wchar.h>
#include "lcms2.h"
#endif
#endif
#if defined(MAGICKCORE_XML_DELEGATE)
# if defined(MAGICKCORE_WINDOWS_SUPPORT)
# if !defined(__MINGW32__)
# include <win32config.h>
# endif
# endif
# include <libxml/parser.h>
# include <libxml/tree.h>
#endif
/*
Forward declarations
*/
static MagickBooleanType
SetImageProfileInternal(Image *,const char *,const StringInfo *,
const MagickBooleanType);
static void
WriteTo8BimProfile(Image *,const char*,const StringInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImageProfiles() clones one or more image profiles.
%
% The format of the CloneImageProfiles method is:
%
% MagickBooleanType CloneImageProfiles(Image *image,
% const Image *clone_image)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o clone_image: the clone image.
%
*/
MagickExport MagickBooleanType CloneImageProfiles(Image *image,
const Image *clone_image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(clone_image != (const Image *) NULL);
assert(clone_image->signature == MagickCoreSignature);
image->color_profile.length=clone_image->color_profile.length;
image->color_profile.info=clone_image->color_profile.info;
image->iptc_profile.length=clone_image->iptc_profile.length;
image->iptc_profile.info=clone_image->iptc_profile.info;
if (clone_image->profiles != (void *) NULL)
{
if (image->profiles != (void *) NULL)
DestroyImageProfiles(image);
image->profiles=CloneSplayTree((SplayTreeInfo *) clone_image->profiles,
(void *(*)(void *)) ConstantString,(void *(*)(void *)) CloneStringInfo);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e l e t e I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DeleteImageProfile() deletes a profile from the image by its name.
%
% The format of the DeleteImageProfile method is:
%
% MagickBooleanTyupe DeleteImageProfile(Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport MagickBooleanType DeleteImageProfile(Image *image,const char *name)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return(MagickFalse);
if (LocaleCompare(name,"icc") == 0)
{
/*
Continue to support deprecated color profile for now.
*/
image->color_profile.length=0;
image->color_profile.info=(unsigned char *) NULL;
}
if (LocaleCompare(name,"iptc") == 0)
{
/*
Continue to support deprecated IPTC profile for now.
*/
image->iptc_profile.length=0;
image->iptc_profile.info=(unsigned char *) NULL;
}
WriteTo8BimProfile(image,name,(StringInfo *) NULL);
return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->profiles,name));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImageProfiles() releases memory associated with an image profile map.
%
% The format of the DestroyProfiles method is:
%
% void DestroyImageProfiles(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DestroyImageProfiles(Image *image)
{
if (image->profiles != (SplayTreeInfo *) NULL)
image->profiles=DestroySplayTree((SplayTreeInfo *) image->profiles);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageProfile() gets a profile associated with an image by name.
%
% The format of the GetImageProfile method is:
%
% const StringInfo *GetImageProfile(const Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport const StringInfo *GetImageProfile(const Image *image,
const char *name)
{
const StringInfo
*profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((StringInfo *) NULL);
profile=(const StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,name);
return(profile);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t N e x t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetNextImageProfile() gets the next profile name for an image.
%
% The format of the GetNextImageProfile method is:
%
% char *GetNextImageProfile(const Image *image)
%
% A description of each parameter follows:
%
% o hash_info: the hash info.
%
*/
MagickExport char *GetNextImageProfile(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((char *) NULL);
return((char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->profiles));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P r o f i l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ProfileImage() associates, applies, or removes an ICM, IPTC, or generic
% profile with / to / from an image. If the profile is NULL, it is removed
% from the image otherwise added or applied. Use a name of '*' and a profile
% of NULL to remove all profiles from the image.
%
% ICC and ICM profiles are handled as follows: If the image does not have
% an associated color profile, the one you provide is associated with the
% image and the image pixels are not transformed. Otherwise, the colorspace
% transform defined by the existing and new profile are applied to the image
% pixels and the new profile is associated with the image.
%
% The format of the ProfileImage method is:
%
% MagickBooleanType ProfileImage(Image *image,const char *name,
% const void *datum,const size_t length,const MagickBooleanType clone)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: Name of profile to add or remove: ICC, IPTC, or generic profile.
%
% o datum: the profile data.
%
% o length: the length of the profile.
%
% o clone: should be MagickFalse.
%
*/
#if defined(MAGICKCORE_LCMS_DELEGATE)
typedef struct _LCMSInfo
{
ColorspaceType
colorspace;
cmsUInt32Number
type;
size_t
channels;
cmsHPROFILE
profile;
int
intent;
double
**magick_restrict pixels,
scale,
translate;
} LCMSInfo;
#if LCMS_VERSION < 2060
static void* cmsGetContextUserData(cmsContext ContextID)
{
return(ContextID);
}
static cmsContext cmsCreateContext(void *magick_unused(Plugin),void *UserData)
{
magick_unreferenced(Plugin);
return((cmsContext) UserData);
}
static void cmsSetLogErrorHandlerTHR(cmsContext magick_unused(ContextID),
cmsLogErrorHandlerFunction Fn)
{
magick_unreferenced(ContextID);
cmsSetLogErrorHandler(Fn);
}
static void cmsDeleteContext(cmsContext magick_unused(ContextID))
{
magick_unreferenced(ContextID);
}
#endif
static double **DestroyPixelThreadSet(double **pixels)
{
register ssize_t
i;
if (pixels == (double **) NULL)
return((double **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixels[i] != (double *) NULL)
pixels[i]=(double *) RelinquishMagickMemory(pixels[i]);
pixels=(double **) RelinquishMagickMemory(pixels);
return(pixels);
}
static double **AcquirePixelThreadSet(const size_t columns,
const size_t channels)
{
double
**pixels;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(double **) AcquireQuantumMemory(number_threads,sizeof(*pixels));
if (pixels == (double **) NULL)
return((double **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=(double *) AcquireQuantumMemory(columns,channels*
sizeof(**pixels));
if (pixels[i] == (double *) NULL)
return(DestroyPixelThreadSet(pixels));
}
return(pixels);
}
static cmsHTRANSFORM *DestroyTransformThreadSet(cmsHTRANSFORM *transform)
{
register ssize_t
i;
assert(transform != (cmsHTRANSFORM *) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (transform[i] != (cmsHTRANSFORM) NULL)
cmsDeleteTransform(transform[i]);
transform=(cmsHTRANSFORM *) RelinquishMagickMemory(transform);
return(transform);
}
static cmsHTRANSFORM *AcquireTransformThreadSet(const LCMSInfo *source_info,
const LCMSInfo *target_info,const cmsUInt32Number flags,
cmsContext cms_context)
{
cmsHTRANSFORM
*transform;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
transform=(cmsHTRANSFORM *) AcquireQuantumMemory(number_threads,
sizeof(*transform));
if (transform == (cmsHTRANSFORM *) NULL)
return((cmsHTRANSFORM *) NULL);
(void) memset(transform,0,number_threads*sizeof(*transform));
for (i=0; i < (ssize_t) number_threads; i++)
{
transform[i]=cmsCreateTransformTHR(cms_context,source_info->profile,
source_info->type,target_info->profile,target_info->type,
target_info->intent,flags);
if (transform[i] == (cmsHTRANSFORM) NULL)
return(DestroyTransformThreadSet(transform));
}
return(transform);
}
static void LCMSExceptionHandler(cmsContext context,cmsUInt32Number severity,
const char *message)
{
Image
*image;
(void) LogMagickEvent(TransformEvent,GetMagickModule(),"lcms: #%u, %s",
severity,message != (char *) NULL ? message : "no message");
image=(Image *) cmsGetContextUserData(context);
if (image != (Image *) NULL)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ImageWarning,"UnableToTransformColorspace","`%s'",image->filename);
}
#endif
static MagickBooleanType SetsRGBImageProfile(Image *image)
{
static unsigned char
sRGBProfile[] =
{
0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00,
0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20,
0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a,
0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00,
0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6,
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99,
0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67,
0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70,
0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88,
0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c,
0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67,
0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24,
0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14,
0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24,
0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14,
0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14,
0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14,
0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14,
0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14,
0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f,
0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36,
0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76,
0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77,
0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39,
0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c,
0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31,
0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75,
0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77,
0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20,
0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66,
0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61,
0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d,
0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52,
0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f,
0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20,
0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57,
0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65,
0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e,
0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20,
0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69,
0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74,
0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e,
0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e,
0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e,
0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47,
0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61,
0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43,
0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44,
0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63,
0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20,
0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00,
0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36,
0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36,
0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c,
0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2,
0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d,
0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00,
0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0,
0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87,
0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4,
0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19,
0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37,
0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54,
0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72,
0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90,
0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae,
0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb,
0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb,
0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d,
0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32,
0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59,
0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83,
0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1,
0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1,
0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14,
0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b,
0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84,
0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1,
0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00,
0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43,
0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a,
0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3,
0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20,
0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71,
0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4,
0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c,
0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77,
0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5,
0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37,
0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d,
0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07,
0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74,
0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5,
0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a,
0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2,
0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f,
0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf,
0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54,
0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc,
0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69,
0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9,
0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e,
0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26,
0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3,
0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64,
0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09,
0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3,
0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61,
0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13,
0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9,
0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84,
0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43,
0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06,
0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce,
0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b,
0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c,
0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41,
0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b,
0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa,
0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd,
0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5,
0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2,
0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3,
0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99,
0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94,
0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94,
0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98,
0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1,
0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf,
0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2,
0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda,
0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7,
0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18,
0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f,
0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b,
0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b,
0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1,
0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c,
0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c,
0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91,
0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb,
0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a,
0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f,
0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8,
0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37,
0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c,
0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05,
0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74,
0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8,
0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61,
0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0,
0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64,
0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee,
0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d,
0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12,
0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab,
0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b,
0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0,
0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a,
0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a,
0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00,
0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb,
0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c,
0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42,
0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f,
0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0,
0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8,
0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95,
0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78,
0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61,
0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f,
0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43,
0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d,
0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d,
0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43,
0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f,
0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60,
0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78,
0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95,
0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8,
0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1,
0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11,
0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46,
0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81,
0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2,
0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a,
0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57,
0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab,
0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04,
0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64,
0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca,
0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36,
0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8,
0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20,
0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f,
0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24,
0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf,
0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40,
0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8,
0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76,
0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a,
0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4,
0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75,
0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d,
0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea,
0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae,
0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79,
0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a,
0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21,
0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff,
0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3,
0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce,
0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf,
0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7,
0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5,
0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba,
0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6,
0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8,
0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1,
0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10,
0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36,
0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63,
0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96,
0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0,
0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11,
0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58,
0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7,
0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb,
0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57,
0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba,
0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff
};
StringInfo
*profile;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (GetImageProfile(image,"icc") != (const StringInfo *) NULL)
return(MagickFalse);
profile=AcquireStringInfo(sizeof(sRGBProfile));
SetStringInfoDatum(profile,sRGBProfile);
status=SetImageProfile(image,"icc",profile);
profile=DestroyStringInfo(profile);
return(status);
}
MagickExport MagickBooleanType ProfileImage(Image *image,const char *name,
const void *datum,const size_t length,
const MagickBooleanType magick_unused(clone))
{
#define GetLCMSPixel(source_info,pixel) \
(source_info.scale*QuantumScale*(pixel)+source_info.translate)
#define ProfileImageTag "Profile/Image"
#define SetLCMSPixel(target_info,pixel) \
ClampToQuantum(target_info.scale*QuantumRange*(pixel)+target_info.translate)
#define ThrowProfileException(severity,tag,context) \
{ \
if (cms_context != (cmsContext) NULL) \
cmsDeleteContext(cms_context); \
if (source_info.profile != (cmsHPROFILE) NULL) \
(void) cmsCloseProfile(source_info.profile); \
if (target_info.profile != (cmsHPROFILE) NULL) \
(void) cmsCloseProfile(target_info.profile); \
ThrowBinaryException(severity,tag,context); \
}
MagickBooleanType
status;
StringInfo
*profile;
magick_unreferenced(clone);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(name != (const char *) NULL);
if ((datum == (const void *) NULL) || (length == 0))
{
char
*next;
/*
Delete image profile(s).
*/
ResetImageProfileIterator(image);
for (next=GetNextImageProfile(image); next != (const char *) NULL; )
{
if (IsOptionMember(next,name) != MagickFalse)
{
(void) DeleteImageProfile(image,next);
ResetImageProfileIterator(image);
}
next=GetNextImageProfile(image);
}
return(MagickTrue);
}
/*
Add a ICC, IPTC, or generic profile to the image.
*/
status=MagickTrue;
profile=AcquireStringInfo((size_t) length);
SetStringInfoDatum(profile,(unsigned char *) datum);
if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0))
status=SetImageProfile(image,name,profile);
else
{
const StringInfo
*icc_profile;
icc_profile=GetImageProfile(image,"icc");
if ((icc_profile != (const StringInfo *) NULL) &&
(CompareStringInfo(icc_profile,profile) == 0))
{
const char
*value;
value=GetImageProperty(image,"exif:ColorSpace");
(void) value;
if (LocaleCompare(value,"1") != 0)
(void) SetsRGBImageProfile(image);
value=GetImageProperty(image,"exif:InteroperabilityIndex");
if (LocaleCompare(value,"R98.") != 0)
(void) SetsRGBImageProfile(image);
icc_profile=GetImageProfile(image,"icc");
}
if ((icc_profile != (const StringInfo *) NULL) &&
(CompareStringInfo(icc_profile,profile) == 0))
{
profile=DestroyStringInfo(profile);
return(MagickTrue);
}
#if !defined(MAGICKCORE_LCMS_DELEGATE)
(void) ThrowMagickException(&image->exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (LCMS)",
image->filename);
#else
{
cmsContext
cms_context;
LCMSInfo
source_info,
target_info;
/*
Transform pixel colors as defined by the color profiles.
*/
cms_context=cmsCreateContext(NULL,image);
if (cms_context == (cmsContext) NULL)
ThrowBinaryImageException(ResourceLimitError,
"ColorspaceColorProfileMismatch",name);
cmsSetLogErrorHandlerTHR(cms_context,LCMSExceptionHandler);
source_info.profile=cmsOpenProfileFromMemTHR(cms_context,
GetStringInfoDatum(profile),(cmsUInt32Number)
GetStringInfoLength(profile));
if (source_info.profile == (cmsHPROFILE) NULL)
{
cmsDeleteContext(cms_context);
ThrowBinaryImageException(ResourceLimitError,
"ColorspaceColorProfileMismatch",name);
}
if ((cmsGetDeviceClass(source_info.profile) != cmsSigLinkClass) &&
(icc_profile == (StringInfo *) NULL))
status=SetImageProfile(image,name,profile);
else
{
CacheView
*image_view;
cmsColorSpaceSignature
signature;
cmsHTRANSFORM
*magick_restrict transform;
cmsUInt32Number
flags;
ExceptionInfo
*exception;
MagickOffsetType
progress;
ssize_t
y;
exception=(&image->exception);
target_info.profile=(cmsHPROFILE) NULL;
if (icc_profile != (StringInfo *) NULL)
{
target_info.profile=source_info.profile;
source_info.profile=cmsOpenProfileFromMemTHR(cms_context,
GetStringInfoDatum(icc_profile),(cmsUInt32Number)
GetStringInfoLength(icc_profile));
if (source_info.profile == (cmsHPROFILE) NULL)
ThrowProfileException(ResourceLimitError,
"ColorspaceColorProfileMismatch",name);
}
source_info.scale=1.0;
source_info.translate=0.0;
source_info.colorspace=sRGBColorspace;
source_info.channels=3;
switch (cmsGetColorSpace(source_info.profile))
{
case cmsSigCmykData:
{
source_info.colorspace=CMYKColorspace;
source_info.channels=4;
source_info.type=(cmsUInt32Number) TYPE_CMYK_DBL;
source_info.scale=100.0;
break;
}
case cmsSigGrayData:
{
source_info.colorspace=GRAYColorspace;
source_info.channels=1;
source_info.type=(cmsUInt32Number) TYPE_GRAY_DBL;
break;
}
case cmsSigLabData:
{
source_info.colorspace=LabColorspace;
source_info.type=(cmsUInt32Number) TYPE_Lab_DBL;
source_info.scale=100.0;
source_info.translate=(-0.5);
break;
}
case cmsSigRgbData:
{
source_info.colorspace=sRGBColorspace;
source_info.type=(cmsUInt32Number) TYPE_RGB_DBL;
break;
}
case cmsSigXYZData:
{
source_info.colorspace=XYZColorspace;
source_info.type=(cmsUInt32Number) TYPE_XYZ_DBL;
break;
}
default:
ThrowProfileException(ImageError,
"ColorspaceColorProfileMismatch",name);
}
signature=cmsGetPCS(source_info.profile);
if (target_info.profile != (cmsHPROFILE) NULL)
signature=cmsGetColorSpace(target_info.profile);
target_info.scale=1.0;
target_info.translate=0.0;
target_info.channels=3;
switch (signature)
{
case cmsSigCmykData:
{
target_info.colorspace=CMYKColorspace;
target_info.channels=4;
target_info.type=(cmsUInt32Number) TYPE_CMYK_DBL;
target_info.scale=0.01;
break;
}
case cmsSigGrayData:
{
target_info.colorspace=GRAYColorspace;
target_info.channels=1;
target_info.type=(cmsUInt32Number) TYPE_GRAY_DBL;
break;
}
case cmsSigLabData:
{
target_info.colorspace=LabColorspace;
target_info.type=(cmsUInt32Number) TYPE_Lab_DBL;
target_info.scale=0.01;
target_info.translate=0.5;
break;
}
case cmsSigRgbData:
{
target_info.colorspace=sRGBColorspace;
target_info.type=(cmsUInt32Number) TYPE_RGB_DBL;
break;
}
case cmsSigXYZData:
{
target_info.colorspace=XYZColorspace;
target_info.type=(cmsUInt32Number) TYPE_XYZ_DBL;
break;
}
default:
ThrowProfileException(ImageError,
"ColorspaceColorProfileMismatch",name);
}
switch (image->rendering_intent)
{
case AbsoluteIntent:
{
target_info.intent=INTENT_ABSOLUTE_COLORIMETRIC;
break;
}
case PerceptualIntent:
{
target_info.intent=INTENT_PERCEPTUAL;
break;
}
case RelativeIntent:
{
target_info.intent=INTENT_RELATIVE_COLORIMETRIC;
break;
}
case SaturationIntent:
{
target_info.intent=INTENT_SATURATION;
break;
}
default:
{
target_info.intent=INTENT_PERCEPTUAL;
break;
}
}
flags=cmsFLAGS_HIGHRESPRECALC;
#if defined(cmsFLAGS_BLACKPOINTCOMPENSATION)
if (image->black_point_compensation != MagickFalse)
flags|=cmsFLAGS_BLACKPOINTCOMPENSATION;
#endif
transform=AcquireTransformThreadSet(&source_info,&target_info,
flags,cms_context);
if (transform == (cmsHTRANSFORM *) NULL)
ThrowProfileException(ImageError,"UnableToCreateColorTransform",
name);
/*
Transform image as dictated by the source & target image profiles.
*/
source_info.pixels=AcquirePixelThreadSet(image->columns,
source_info.channels);
target_info.pixels=AcquirePixelThreadSet(image->columns,
target_info.channels);
if ((source_info.pixels == (double **) NULL) ||
(target_info.pixels == (double **) NULL))
{
target_info.pixels=DestroyPixelThreadSet(target_info.pixels);
source_info.pixels=DestroyPixelThreadSet(source_info.pixels);
transform=DestroyTransformThreadSet(transform);
ThrowProfileException(ResourceLimitError,
"MemoryAllocationFailed",image->filename);
}
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
target_info.pixels=DestroyPixelThreadSet(target_info.pixels);
source_info.pixels=DestroyPixelThreadSet(source_info.pixels);
transform=DestroyTransformThreadSet(transform);
if (source_info.profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(source_info.profile);
if (target_info.profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(target_info.profile);
return(MagickFalse);
}
if (target_info.colorspace == CMYKColorspace)
(void) SetImageColorspace(image,target_info.colorspace);
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register IndexPacket
*magick_restrict indexes;
register double
*p;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
p=source_info.pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
{
*p++=GetLCMSPixel(source_info,GetPixelRed(q));
if (source_info.channels > 1)
{
*p++=GetLCMSPixel(source_info,GetPixelGreen(q));
*p++=GetLCMSPixel(source_info,GetPixelBlue(q));
}
if (source_info.channels > 3)
{
*p=GetLCMSPixel(source_info,0);
if (indexes != (IndexPacket *) NULL)
*p=GetLCMSPixel(source_info,GetPixelIndex(indexes+x));
p++;
}
q++;
}
cmsDoTransform(transform[id],source_info.pixels[id],
target_info.pixels[id],(unsigned int) image->columns);
p=target_info.pixels[id];
q-=image->columns;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,SetLCMSPixel(target_info,*p));
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
p++;
if (target_info.channels > 1)
{
SetPixelGreen(q,SetLCMSPixel(target_info,*p));
p++;
SetPixelBlue(q,SetLCMSPixel(target_info,*p));
p++;
}
if (target_info.channels > 3)
{
if (indexes != (IndexPacket *) NULL)
SetPixelIndex(indexes+x,SetLCMSPixel(target_info,*p));
p++;
}
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ProfileImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
(void) SetImageColorspace(image,target_info.colorspace);
switch (signature)
{
case cmsSigRgbData:
{
image->type=image->matte == MagickFalse ? TrueColorType :
TrueColorMatteType;
break;
}
case cmsSigCmykData:
{
image->type=image->matte == MagickFalse ? ColorSeparationType :
ColorSeparationMatteType;
break;
}
case cmsSigGrayData:
{
image->type=image->matte == MagickFalse ? GrayscaleType :
GrayscaleMatteType;
break;
}
default:
break;
}
target_info.pixels=DestroyPixelThreadSet(target_info.pixels);
source_info.pixels=DestroyPixelThreadSet(source_info.pixels);
transform=DestroyTransformThreadSet(transform);
if ((status != MagickFalse) &&
(cmsGetDeviceClass(source_info.profile) != cmsSigLinkClass))
status=SetImageProfile(image,name,profile);
if (target_info.profile != (cmsHPROFILE) NULL)
(void) cmsCloseProfile(target_info.profile);
}
(void) cmsCloseProfile(source_info.profile);
cmsDeleteContext(cms_context);
}
#endif
}
profile=DestroyStringInfo(profile);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e m o v e I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RemoveImageProfile() removes a named profile from the image and returns its
% value.
%
% The format of the RemoveImageProfile method is:
%
% void *RemoveImageProfile(Image *image,const char *name)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name.
%
*/
MagickExport StringInfo *RemoveImageProfile(Image *image,const char *name)
{
StringInfo
*profile;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return((StringInfo *) NULL);
if (LocaleCompare(name,"icc") == 0)
{
/*
Continue to support deprecated color profile for now.
*/
image->color_profile.length=0;
image->color_profile.info=(unsigned char *) NULL;
}
if (LocaleCompare(name,"iptc") == 0)
{
/*
Continue to support deprecated IPTC profile for now.
*/
image->iptc_profile.length=0;
image->iptc_profile.info=(unsigned char *) NULL;
}
WriteTo8BimProfile(image,name,(StringInfo *) NULL);
profile=(StringInfo *) RemoveNodeFromSplayTree((SplayTreeInfo *)
image->profiles,name);
return(profile);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t P r o f i l e I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImageProfileIterator() resets the image profile iterator. Use it in
% conjunction with GetNextImageProfile() to iterate over all the profiles
% associated with an image.
%
% The format of the ResetImageProfileIterator method is:
%
% ResetImageProfileIterator(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void ResetImageProfileIterator(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->profiles == (SplayTreeInfo *) NULL)
return;
ResetSplayTreeIterator((SplayTreeInfo *) image->profiles);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e P r o f i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageProfile() adds a named profile to the image. If a profile with the
% same name already exists, it is replaced. This method differs from the
% ProfileImage() method in that it does not apply CMS color profiles.
%
% The format of the SetImageProfile method is:
%
% MagickBooleanType SetImageProfile(Image *image,const char *name,
% const StringInfo *profile)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o name: the profile name, for example icc, exif, and 8bim (8bim is the
% Photoshop wrapper for iptc profiles).
%
% o profile: A StringInfo structure that contains the named profile.
%
*/
static void *DestroyProfile(void *profile)
{
return((void *) DestroyStringInfo((StringInfo *) profile));
}
static inline const unsigned char *ReadResourceByte(const unsigned char *p,
unsigned char *quantum)
{
*quantum=(*p++);
return(p);
}
static inline const unsigned char *ReadResourceLong(const unsigned char *p,
unsigned int *quantum)
{
*quantum=(unsigned int) (*p++) << 24;
*quantum|=(unsigned int) (*p++) << 16;
*quantum|=(unsigned int) (*p++) << 8;
*quantum|=(unsigned int) (*p++);
return(p);
}
static inline const unsigned char *ReadResourceShort(const unsigned char *p,
unsigned short *quantum)
{
*quantum=(unsigned short) (*p++) << 8;
*quantum|=(unsigned short) (*p++);
return(p);
}
static inline void WriteResourceLong(unsigned char *p,
const unsigned int quantum)
{
unsigned char
buffer[4];
buffer[0]=(unsigned char) (quantum >> 24);
buffer[1]=(unsigned char) (quantum >> 16);
buffer[2]=(unsigned char) (quantum >> 8);
buffer[3]=(unsigned char) quantum;
(void) memcpy(p,buffer,4);
}
static void WriteTo8BimProfile(Image *image,const char *name,
const StringInfo *profile)
{
const unsigned char
*datum,
*q;
register const unsigned char
*p;
size_t
length;
StringInfo
*profile_8bim;
ssize_t
count;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id,
profile_id;
if (LocaleCompare(name,"icc") == 0)
profile_id=0x040f;
else
if (LocaleCompare(name,"iptc") == 0)
profile_id=0x0404;
else
if (LocaleCompare(name,"xmp") == 0)
profile_id=0x0424;
else
return;
profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,"8bim");
if (profile_8bim == (StringInfo *) NULL)
return;
datum=GetStringInfoDatum(profile_8bim);
length=GetStringInfoLength(profile_8bim);
for (p=datum; p < (datum+length-16); )
{
q=p;
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((count & 0x01) != 0)
count++;
if ((count < 0) || (p > (datum+length-count)) || (count > (ssize_t) length))
break;
if (id != profile_id)
p+=count;
else
{
size_t
extent,
offset;
ssize_t
extract_extent;
StringInfo
*extract_profile;
extract_extent=0;
extent=(datum+length)-(p+count);
if (profile == (StringInfo *) NULL)
{
offset=(q-datum);
extract_profile=AcquireStringInfo(offset+extent);
(void) memcpy(extract_profile->datum,datum,offset);
}
else
{
offset=(p-datum);
extract_extent=profile->length;
if ((extract_extent & 0x01) != 0)
extract_extent++;
extract_profile=AcquireStringInfo(offset+extract_extent+extent);
(void) memcpy(extract_profile->datum,datum,offset-4);
WriteResourceLong(extract_profile->datum+offset-4,(unsigned int)
profile->length);
(void) memcpy(extract_profile->datum+offset,
profile->datum,profile->length);
}
(void) memcpy(extract_profile->datum+offset+extract_extent,
p+count,extent);
(void) AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString("8bim"),CloneStringInfo(extract_profile));
extract_profile=DestroyStringInfo(extract_profile);
break;
}
}
}
static void GetProfilesFromResourceBlock(Image *image,
const StringInfo *resource_block)
{
const unsigned char
*datum;
register const unsigned char
*p;
size_t
length;
ssize_t
count;
StringInfo
*profile;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id;
datum=GetStringInfoDatum(resource_block);
length=GetStringInfoLength(resource_block);
for (p=datum; p < (datum+length-16); )
{
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((p > (datum+length-count)) || (count > (ssize_t) length) || (count < 0))
break;
switch (id)
{
case 0x03ed:
{
unsigned int
resolution;
unsigned short
units;
/*
Resolution.
*/
if (count < 10)
break;
p=ReadResourceLong(p,&resolution);
image->x_resolution=((double) resolution)/65536.0;
p=ReadResourceShort(p,&units)+2;
p=ReadResourceLong(p,&resolution)+4;
image->y_resolution=((double) resolution)/65536.0;
/*
Values are always stored as pixels per inch.
*/
if ((ResolutionType) units != PixelsPerCentimeterResolution)
image->units=PixelsPerInchResolution;
else
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution/=2.54;
image->y_resolution/=2.54;
}
break;
}
case 0x0404:
{
/*
IPTC Profile
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"iptc",profile,MagickTrue);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x040c:
{
/*
Thumbnail.
*/
p+=count;
break;
}
case 0x040f:
{
/*
ICC Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"icc",profile,MagickTrue);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x0422:
{
/*
EXIF Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"exif",profile,MagickTrue);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
case 0x0424:
{
/*
XMP Profile.
*/
profile=AcquireStringInfo(count);
SetStringInfoDatum(profile,p);
(void) SetImageProfileInternal(image,"xmp",profile,MagickTrue);
profile=DestroyStringInfo(profile);
p+=count;
break;
}
default:
{
p+=count;
break;
}
}
if ((count & 0x01) != 0)
p++;
}
}
#if defined(MAGICKCORE_XML_DELEGATE)
static MagickBooleanType ValidateXMPProfile(const StringInfo *profile)
{
xmlDocPtr
document;
/*
Parse XML profile.
*/
document=xmlReadMemory((const char *) GetStringInfoDatum(profile),(int)
GetStringInfoLength(profile),"xmp.xml",NULL,XML_PARSE_NOERROR |
XML_PARSE_NOWARNING);
if (document == (xmlDocPtr) NULL)
return(MagickFalse);
xmlFreeDoc(document);
return(MagickTrue);
}
#else
static MagickBooleanType ValidateXMPProfile(const StringInfo *profile)
{
return(MagickFalse);
}
#endif
static MagickBooleanType SetImageProfileInternal(Image *image,const char *name,
const StringInfo *profile,const MagickBooleanType recursive)
{
char
key[MaxTextExtent];
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((LocaleCompare(name,"xmp") == 0) &&
(ValidateXMPProfile(profile) == MagickFalse))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ImageWarning,"CorruptImageProfile","`%s'",name);
return(MagickTrue);
}
if (image->profiles == (SplayTreeInfo *) NULL)
image->profiles=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory,
DestroyProfile);
(void) CopyMagickString(key,name,MaxTextExtent);
LocaleLower(key);
status=AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString(key),CloneStringInfo(profile));
if ((status != MagickFalse) &&
((LocaleCompare(name,"icc") == 0) || (LocaleCompare(name,"icm") == 0)))
{
const StringInfo
*icc_profile;
/*
Continue to support deprecated color profile member.
*/
icc_profile=GetImageProfile(image,name);
if (icc_profile != (const StringInfo *) NULL)
{
image->color_profile.length=GetStringInfoLength(icc_profile);
image->color_profile.info=GetStringInfoDatum(icc_profile);
}
}
if ((status != MagickFalse) &&
((LocaleCompare(name,"iptc") == 0) || (LocaleCompare(name,"8bim") == 0)))
{
const StringInfo
*iptc_profile;
/*
Continue to support deprecated IPTC profile member.
*/
iptc_profile=GetImageProfile(image,name);
if (iptc_profile != (const StringInfo *) NULL)
{
image->iptc_profile.length=GetStringInfoLength(iptc_profile);
image->iptc_profile.info=GetStringInfoDatum(iptc_profile);
}
}
if (status != MagickFalse)
{
if (LocaleCompare(name,"8bim") == 0)
GetProfilesFromResourceBlock(image,profile);
else
if (recursive == MagickFalse)
WriteTo8BimProfile(image,name,profile);
}
return(status);
}
MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name,
const StringInfo *profile)
{
return(SetImageProfileInternal(image,name,profile,MagickFalse));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S y n c I m a g e P r o f i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImageProfiles() synchronizes image properties with the image profiles.
% Currently we only support updating the EXIF resolution and orientation.
%
% The format of the SyncImageProfiles method is:
%
% MagickBooleanType SyncImageProfiles(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static inline int ReadProfileByte(unsigned char **p,size_t *length)
{
int
c;
if (*length < 1)
return(EOF);
c=(int) (*(*p)++);
(*length)--;
return(c);
}
static inline signed short ReadProfileShort(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) buffer[1] << 8;
value|=(unsigned short) buffer[0];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
static inline signed int ReadProfileLong(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) buffer[3] << 24;
value|=(unsigned int) buffer[2] << 16;
value|=(unsigned int) buffer[1] << 8;
value|=(unsigned int) buffer[0];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
static inline signed int ReadProfileMSBLong(unsigned char **p,size_t *length)
{
signed int
value;
if (*length < 4)
return(0);
value=ReadProfileLong(MSBEndian,*p);
(*length)-=4;
*p+=4;
return(value);
}
static inline signed short ReadProfileMSBShort(unsigned char **p,
size_t *length)
{
signed short
value;
if (*length < 2)
return(0);
value=ReadProfileShort(MSBEndian,*p);
(*length)-=2;
*p+=2;
return(value);
}
static inline void WriteProfileLong(const EndianType endian,
const size_t value,unsigned char *p)
{
unsigned char
buffer[4];
if (endian == LSBEndian)
{
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
buffer[2]=(unsigned char) (value >> 16);
buffer[3]=(unsigned char) (value >> 24);
(void) memcpy(p,buffer,4);
return;
}
buffer[0]=(unsigned char) (value >> 24);
buffer[1]=(unsigned char) (value >> 16);
buffer[2]=(unsigned char) (value >> 8);
buffer[3]=(unsigned char) value;
(void) memcpy(p,buffer,4);
}
static void WriteProfileShort(const EndianType endian,
const unsigned short value,unsigned char *p)
{
unsigned char
buffer[2];
if (endian == LSBEndian)
{
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
(void) memcpy(p,buffer,2);
return;
}
buffer[0]=(unsigned char) (value >> 8);
buffer[1]=(unsigned char) value;
(void) memcpy(p,buffer,2);
}
static MagickBooleanType Sync8BimProfile(Image *image,StringInfo *profile)
{
size_t
length;
ssize_t
count;
unsigned char
*p;
unsigned short
id;
length=GetStringInfoLength(profile);
p=GetStringInfoDatum(profile);
while (length != 0)
{
if (ReadProfileByte(&p,&length) != 0x38)
continue;
if (ReadProfileByte(&p,&length) != 0x42)
continue;
if (ReadProfileByte(&p,&length) != 0x49)
continue;
if (ReadProfileByte(&p,&length) != 0x4D)
continue;
if (length < 7)
return(MagickFalse);
id=ReadProfileMSBShort(&p,&length);
count=(ssize_t) ReadProfileByte(&p,&length);
if ((count >= (ssize_t) length) || (count < 0))
return(MagickFalse);
p+=count;
length-=count;
if ((*p & 0x01) == 0)
(void) ReadProfileByte(&p,&length);
count=(ssize_t) ReadProfileMSBLong(&p,&length);
if ((count > (ssize_t) length) || (count < 0))
return(MagickFalse);
if ((id == 0x3ED) && (count == 16))
{
if (image->units == PixelsPerCentimeterResolution)
WriteProfileLong(MSBEndian,(unsigned int) (image->x_resolution*2.54*
65536.0),p);
else
WriteProfileLong(MSBEndian,(unsigned int) (image->x_resolution*
65536.0),p);
WriteProfileShort(MSBEndian,(unsigned short) image->units,p+4);
if (image->units == PixelsPerCentimeterResolution)
WriteProfileLong(MSBEndian,(unsigned int) (image->y_resolution*2.54*
65536.0),p+8);
else
WriteProfileLong(MSBEndian,(unsigned int) (image->y_resolution*
65536.0),p+8);
WriteProfileShort(MSBEndian,(unsigned short) image->units,p+12);
}
p+=count;
length-=count;
}
return(MagickTrue);
}
static MagickBooleanType SyncExifProfile(Image *image, StringInfo *profile)
{
#define MaxDirectoryStack 16
#define EXIF_DELIMITER "\n"
#define EXIF_NUM_FORMATS 12
#define TAG_EXIF_OFFSET 0x8769
#define TAG_INTEROP_OFFSET 0xa005
typedef struct _DirectoryInfo
{
unsigned char
*directory;
size_t
entry;
} DirectoryInfo;
DirectoryInfo
directory_stack[MaxDirectoryStack];
EndianType
endian;
size_t
entry,
length,
number_entries;
SplayTreeInfo
*exif_resources;
ssize_t
id,
level,
offset;
static int
format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8};
unsigned char
*directory,
*exif;
/*
Set EXIF resolution tag.
*/
length=GetStringInfoLength(profile);
exif=GetStringInfoDatum(profile);
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
if ((id != 0x4949) && (id != 0x4D4D))
{
while (length != 0)
{
if (ReadProfileByte(&exif,&length) != 0x45)
continue;
if (ReadProfileByte(&exif,&length) != 0x78)
continue;
if (ReadProfileByte(&exif,&length) != 0x69)
continue;
if (ReadProfileByte(&exif,&length) != 0x66)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
if (ReadProfileByte(&exif,&length) != 0x00)
continue;
break;
}
if (length < 16)
return(MagickFalse);
id=(ssize_t) ReadProfileShort(LSBEndian,exif);
}
endian=LSBEndian;
if (id == 0x4949)
endian=LSBEndian;
else
if (id == 0x4D4D)
endian=MSBEndian;
else
return(MagickFalse);
if (ReadProfileShort(endian,exif+2) != 0x002a)
return(MagickFalse);
/*
This the offset to the first IFD.
*/
offset=(ssize_t) ReadProfileLong(endian,exif+4);
if ((offset < 0) || ((size_t) offset >= length))
return(MagickFalse);
directory=exif+offset;
level=0;
entry=0;
exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL,
(void *(*)(void *)) NULL,(void *(*)(void *)) NULL);
do
{
if (level > 0)
{
level--;
directory=directory_stack[level].directory;
entry=directory_stack[level].entry;
}
if ((directory < exif) || (directory > (exif+length-2)))
break;
/*
Determine how many entries there are in the current IFD.
*/
number_entries=ReadProfileShort(endian,directory);
for ( ; entry < number_entries; entry++)
{
int
components;
register unsigned char
*p,
*q;
size_t
number_bytes;
ssize_t
format,
tag_value;
q=(unsigned char *) (directory+2+(12*entry));
if (q > (exif+length-12))
break; /* corrupt EXIF */
if (GetValueFromSplayTree(exif_resources,q) == q)
break;
(void) AddValueToSplayTree(exif_resources,q,q);
tag_value=(ssize_t) ReadProfileShort(endian,q);
format=(ssize_t) ReadProfileShort(endian,q+2);
if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS))
break;
components=(int) ReadProfileLong(endian,q+4);
if (components < 0)
break; /* corrupt EXIF */
number_bytes=(size_t) components*format_bytes[format];
if ((ssize_t) number_bytes < components)
break; /* prevent overflow */
if (number_bytes <= 4)
p=q+8;
else
{
/*
The directory entry contains an offset.
*/
offset=(ssize_t) ReadProfileLong(endian,q+8);
if ((offset < 0) || ((size_t) (offset+number_bytes) > length))
continue;
if (~length < number_bytes)
continue; /* prevent overflow */
p=(unsigned char *) (exif+offset);
}
switch (tag_value)
{
case 0x011a:
{
(void) WriteProfileLong(endian,(size_t) (image->x_resolution+0.5),p);
if (number_bytes == 8)
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x011b:
{
(void) WriteProfileLong(endian,(size_t) (image->y_resolution+0.5),p);
if (number_bytes == 8)
(void) WriteProfileLong(endian,1UL,p+4);
break;
}
case 0x0112:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) image->orientation,p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) image->orientation,
p);
break;
}
case 0x0128:
{
if (number_bytes == 4)
{
(void) WriteProfileLong(endian,(size_t) (image->units+1),p);
break;
}
(void) WriteProfileShort(endian,(unsigned short) (image->units+1),p);
break;
}
default:
break;
}
if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET))
{
offset=(ssize_t) ReadProfileLong(endian,p);
if (((size_t) offset < length) && (level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=directory;
entry++;
directory_stack[level].entry=entry;
level++;
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
if ((directory+2+(12*number_entries)) > (exif+length))
break;
offset=(ssize_t) ReadProfileLong(endian,directory+2+(12*
number_entries));
if ((offset != 0) && ((size_t) offset < length) &&
(level < (MaxDirectoryStack-2)))
{
directory_stack[level].directory=exif+offset;
directory_stack[level].entry=0;
level++;
}
}
break;
}
}
} while (level > 0);
exif_resources=DestroySplayTree(exif_resources);
return(MagickTrue);
}
MagickExport MagickBooleanType SyncImageProfiles(Image *image)
{
MagickBooleanType
status;
StringInfo
*profile;
status=MagickTrue;
profile=(StringInfo *) GetImageProfile(image,"8BIM");
if (profile != (StringInfo *) NULL)
if (Sync8BimProfile(image,profile) == MagickFalse)
status=MagickFalse;
profile=(StringInfo *) GetImageProfile(image,"EXIF");
if (profile != (StringInfo *) NULL)
if (SyncExifProfile(image,profile) == MagickFalse)
status=MagickFalse;
return(status);
}
|
GB_unaryop__abs_bool_uint64.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__abs_bool_uint64
// op(A') function: GB_tran__abs_bool_uint64
// C type: bool
// A type: uint64_t
// cast: bool cij = (bool) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
bool
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, x) \
bool z = (bool) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ABS || GxB_NO_BOOL || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_bool_uint64
(
bool *restrict Cx,
const uint64_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__abs_bool_uint64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
DRB003-antidep2-orig-yes.c | /*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov,
schordan1@llnl.gov, karlin1@llnl.gov)
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https://github.com/LLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
A two-level loop nest with loop carried anti-dependence on the outer level.
Data race pair: a[i][j]@67:7 vs. a[i+1][j]@67:18
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
int i, j;
int len = 20;
double a[20][20];
#pragma omp parallel for private(i ,j )
for (i=0; i< len; i++)
#pragma omp parallel for private(j )
for (j=0; j<len; j++)
a[i][j] = (i * len + j + 0.5);
for (i = 0; i < len - 1; i += 1) {
#pragma omp parallel for
for (j = 0; j < len ; j += 1) {
a[i][j] += a[i + 1][j];
}
}
for (i=0; i< len; i++)
for (j=0; j<len; j++)
printf("%lf",a[i][j]);
printf ("a[10][10]=%f\n", a[10][10]);
return 0;
}
|
GB_unop__erfc_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__erfc_fp32_fp32)
// op(A') function: GB (_unop_tran__erfc_fp32_fp32)
// C type: float
// A type: float
// cast: float cij = aij
// unaryop: cij = erfcf (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 = erfcf (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] = erfcf (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_ERFC || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__erfc_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] = erfcf (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] = erfcf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__erfc_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
|
LAGraph_grread.c | //------------------------------------------------------------------------------
// LAGraph_grread: read a matrix from a binary file
//------------------------------------------------------------------------------
/*
LAGraph: graph algorithms based on GraphBLAS
Copyright 2019 LAGraph Contributors.
(see Contributors.txt for a full list of Contributors; see
ContributionInstructions.txt for information on how you can Contribute to
this project).
All Rights Reserved.
NO WARRANTY. THIS MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. THE LAGRAPH
CONTRIBUTORS MAKE NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR
PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF
THE MATERIAL. THE CONTRIBUTORS DO NOT MAKE ANY WARRANTY OF ANY KIND WITH
RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT.
Released under a BSD license, please see the LICENSE file distributed with
this Software or contact permission@sei.cmu.edu for full terms.
Created, in part, with funding and support from the United States
Government. (see Acknowledgments.txt file).
This program includes and/or can make use of certain third party source
code, object code, documentation and other files ("Third Party Software").
See LICENSE file for more details.
*/
//------------------------------------------------------------------------------
// LAGraph_grread: read a matrix from a binary file.
// Contributed by Tim Davis, Texas A&M, based on the Galois graph reader
// file format.
// The file format consists of a header, with the following content:
// uint64_t version : either 1 or 2. 1: nodes are 2^32, 2: nodes are
// 64 bit. This value is returned to the caller, but is otherwise
// unused.
// uint64_t esize : the size of the edge weight, as sizeof (edgetype).
// For example, if the file contains edge weights of type int32_t,
// esize is sizeof (int32_t) == 4. The caller must specify the
// corresponding GrB_Type, and its size must match esize.
// uint64_t n : the number of node in the graph. The GrB_Matrix is
// n-by-n. Rectangular matrices are not supported by this format.
// uint64_t e : the number of edges in the graph
// This header is followed by a matrix in CSR format:
// Gp : an array of size ((n+1) * sizeof (uint64_t)) bytes, but Gp [0] = 0
// does not appear in the file. This section of the file is thus
// (n * sizeof (uint64_t)) bytes in length.
// Gj : an array of size (e * sizeof (int32_t)), containing the adjaceny
// lists. Note that the indices are 32 bit, not 64 bit, and thus
// this format is limited to graphs with n < 2^32.
// Gx : an array of size (e * esize), containing the edge weights.
// LAgraph_grread returns its status: GrB_SUCCESS if succesful,
// GrB_OUT_OF_MEMORY if out of memory, GrB_INVALID_VALUE if a file I/O error
// occurs or the edge size is not what was expected.
#include "LAGraph_internal.h"
//------------------------------------------------------------------------------
// gr_header
//------------------------------------------------------------------------------
// The gr_header specifies the first 4 * sizeof(uint64_t) bytes of the file.
typedef struct
{
uint64_t version ; // either 1 or 2.
// 1: node id's are in the range 0 to 2^32
// 2: node id's are in the range 0 to 2^64
uint64_t esize ; // sizeof (edgetype)
uint64_t n ; // # of nodes in the graph
uint64_t e ; // # of edges in the graph
}
gr_header ;
//------------------------------------------------------------------------------
// LAGraph_binary_read
//------------------------------------------------------------------------------
// Read a block of binary data from a file. Returns GrB_SUCCESS if successful,
// GrB_INVALID_VALUE otherwise.
static GrB_Info LAGraph_binary_read
(
char *name, // name of array being read in
FILE *fp, // file to read from
void *buffer, // buffer of size nbytes to read into
size_t n, // # of elements to read
size_t size // size of each element
)
{
if (fp == NULL)
{
fprintf (stderr, "LAGraph_grread: file I/O error\n") ;
return (GrB_INVALID_VALUE) ;
}
size_t n_read = fread (buffer, size, n, fp) ;
if (n_read != n)
{
fprintf (stderr, "LAGraph_grread: file I/O error; expected %g items"
", got %g, object %s, size %g\n", (double) n_read, (double) n,
name, (double) size) ;
return (GrB_INVALID_VALUE) ;
}
return (GrB_SUCCESS) ;
}
//------------------------------------------------------------------------------
// LAGRAPH_FREE_ALL
//------------------------------------------------------------------------------
// Free all allocated space; used only for error return.
#define LAGRAPH_FREE_ALL \
{ \
GrB_free (G) ; \
LAGRAPH_FREE (Gp) ; \
LAGRAPH_FREE (Gj) ; \
LAGRAPH_FREE (Gj_32) ; \
LAGRAPH_FREE (Gx) ; \
if (fp != NULL) fclose (fp) ; \
fp = NULL ; \
}
//------------------------------------------------------------------------------
// LAGraph_grread
//------------------------------------------------------------------------------
GrB_Info LAGraph_grread // read a matrix from a binary file
(
GrB_Matrix *G, // handle of matrix to create
uint64_t *G_version, // the version in the file
const char *filename, // name of file to open
GrB_Type gtype // type of matrix to read, NULL if no edge weights
// (in that case, G has type GrB_BOOL with all
// edge weights equal to 1).
)
{
#if defined ( GxB_SUITESPARSE_GRAPHBLAS ) && ( GxB_IMPLEMENTATION >= GxB_VERSION (5,0,0) )
printf ("v5.0.0 not supported\n") ;
return (GrB_PANIC) ;
#else
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GrB_Info info ;
GrB_Index *Gp = NULL ;
int32_t *Gj_32 = NULL ;
GrB_Index *Gj = NULL ;
void *Gx = NULL ;
FILE *fp = NULL ;
if (G == NULL || G_version == NULL || filename == NULL)
{
LAGRAPH_ERROR ("invalid input arguments", GrB_NULL_POINTER) ;
}
(*G) = NULL ;
(*G_version) = 0 ;
//--------------------------------------------------------------------------
// open the file
//--------------------------------------------------------------------------
fp = fopen (filename, "r") ;
if (fp == NULL)
{
fprintf (stderr, "LAGraph_grread: file not found: %s\n", filename) ;
LAGRAPH_ERROR ("input file not found", GrB_INVALID_VALUE) ;
}
//--------------------------------------------------------------------------
// open the file and read the gr_header
//--------------------------------------------------------------------------
gr_header header ;
LAGRAPH_OK (LAGraph_binary_read ("header",
fp, &header, 1, sizeof (gr_header))) ;
uint64_t version = header.version ; // version, 1 or 2
uint64_t esize = header.esize ; // sizeof (edge type)
uint64_t n = header.n ; // # of nodes
uint64_t e = header.e ; // # of edges
(*G_version) = version ;
size_t esize_expected = 0 ;
if (gtype != NULL)
{
LAGRAPH_OK (GxB_Type_size (&esize_expected, gtype)) ;
}
if (esize != esize_expected)
{
fprintf (stderr, "LAGraph_grread: esize in file (%g) does not match"
" gtype size (%g)\n", (double) esize, (double) esize_expected) ;
LAGRAPH_ERROR ("unexpected edge size", GrB_INVALID_VALUE) ;
}
if (! (version == 1 || version == 2))
{
LAGRAPH_ERROR ("invalid version, must be 1 or 2", GrB_INVALID_VALUE) ;
}
if (version == 1 && n > UINT32_MAX)
{
LAGRAPH_ERROR ("problem too large", GrB_INVALID_VALUE) ;
}
//--------------------------------------------------------------------------
// allocate and read in the pointers
//--------------------------------------------------------------------------
Gp = LAGraph_malloc (n+1, sizeof (GrB_Index)) ;
if (Gp == NULL)
{
LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ;
}
Gp [0] = 0 ;
LAGRAPH_OK (LAGraph_binary_read ("pointers",
fp, Gp+1, n, sizeof (GrB_Index))) ;
//--------------------------------------------------------------------------
// allocate and read in the indices
//--------------------------------------------------------------------------
Gj = LAGraph_malloc (e, sizeof (GrB_Index)) ;
if (Gj == NULL)
{
LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ;
}
if (version == 1)
{
//----------------------------------------------------------------------
// indices are in 32-bit format in the file
//----------------------------------------------------------------------
// allocate workspace for a single chunk
#define CHUNK (10 * 1024 * 1024)
int64_t chunk = LAGRAPH_MIN (CHUNK, e) ;
Gj_32 = LAGraph_malloc (chunk, sizeof (int32_t)) ;
if (Gj_32 == NULL)
{
LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ;
}
// read in the indices one chunk at a time
for (int64_t k = 0 ; k < e ; k += CHUNK)
{
// read in the next chunk
int64_t chunk = LAGRAPH_MIN (CHUNK, e-k) ;
LAGRAPH_OK (LAGraph_binary_read ("indices",
fp, Gj_32, chunk, sizeof (int32_t))) ;
// convert the chunk to 64-bit
#pragma omp parallel for schedule(static)
for (GrB_Index p = 0 ; p < chunk ; p++)
{
Gj [k + p] = (GrB_Index) Gj_32 [p] ;
}
}
LAGRAPH_FREE (Gj_32) ;
}
else
{
//----------------------------------------------------------------------
// indices are in 64-bit format in the file
//----------------------------------------------------------------------
LAGRAPH_OK (LAGraph_binary_read ("indices",
fp, Gj, e, sizeof (GrB_Index))) ;
}
//--------------------------------------------------------------------------
// read in the values
//--------------------------------------------------------------------------
bool no_edge_weights = (gtype == NULL) ;
if (no_edge_weights)
{
// the input file has no edge weights
gtype = GrB_BOOL ;
esize = sizeof (bool) ;
}
Gx = LAGraph_malloc (e, esize) ;
if (Gx == NULL) LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ;
if (no_edge_weights)
{
// set all edge weights to boolean true
bool *Gbool = (bool *) Gx ;
#pragma omp parallel for schedule(static)
for (GrB_Index p = 0 ; p < e ; p++)
{
Gbool [p] = true ;
}
}
else
{
// read in the edge weights
LAGRAPH_OK (LAGraph_binary_read ("edgeweights", fp, Gx, e, esize)) ;
}
//--------------------------------------------------------------------------
// import the data into the GrB_Matrix
//--------------------------------------------------------------------------
#if GxB_IMPLEMENTATION >= GxB_VERSION (4,0,1)
LAGRAPH_OK (GxB_Matrix_import_CSR (G, gtype, n, n,
&Gp, &Gj, &Gx, n+1, e, e, false, NULL)) ;
#elif GxB_IMPLEMENTATION == GxB_VERSION (4,0,0)
LAGRAPH_OK (GxB_Matrix_import_CSR (G, gtype, n, n, e, false, -1,
&Gp, &Gj, &Gx, NULL)) ;
#else
LAGRAPH_OK (GxB_Matrix_import_CSR (G, gtype, n, n, e, -1, &Gp, &Gj, &Gx,
NULL)) ;
#endif
//--------------------------------------------------------------------------
// close the file and return result
//--------------------------------------------------------------------------
fclose (fp) ;
return (GrB_SUCCESS) ;
#endif
}
|
lis_matvec_bsc.c | /* Copyright (C) 2002-2012 The SSI Project. 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 project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE SCALABLE SOFTWARE INFRASTRUCTURE PROJECT
``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 SCALABLE SOFTWARE INFRASTRUCTURE
PROJECT 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.
*/
#ifdef HAVE_CONFIG_H
#include "lis_config.h"
#else
#ifdef HAVE_CONFIG_WIN32_H
#include "lis_config_win32.h"
#endif
#endif
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#include <string.h>
#include <stdarg.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#ifdef USE_MPI
#include <mpi.h>
#endif
#include "lislib.h"
LIS_MATVEC_XXX lis_matvec_bsc_xxx[4][4] = {
{lis_matvec_bsc_1x1, lis_matvec_bsc_1x2, lis_matvec_bsc_1x3, lis_matvec_bsc_1x4},
{lis_matvec_bsc_2x1, lis_matvec_bsc_2x2, lis_matvec_bsc_2x3, lis_matvec_bsc_2x4},
{lis_matvec_bsc_3x1, lis_matvec_bsc_3x2, lis_matvec_bsc_3x3, lis_matvec_bsc_3x4},
{lis_matvec_bsc_4x1, lis_matvec_bsc_4x2, lis_matvec_bsc_4x3, lis_matvec_bsc_4x4}
};
void lis_matvec_bsc(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,k;
LIS_INT bi,bj,bc,bs;
LIS_INT nr,nc,bnr,bnc;
LIS_INT n;
LIS_SCALAR t;
n = A->n;
nr = A->nr;
nc = A->nc;
bnr = A->bnr;
bnc = A->bnc;
bs = bnr*bnc;
if( A->is_splited )
{
#ifdef _OPENMP
#pragma omp parallel for private(bi,i,j,t,k)
#endif
for(bi=0;bi<nr;bi++)
{
k = 0;
for(i=0;i<bnr;i++)
{
t = 0.0;
for(j=0;j<bnc;j++)
{
t += A->D->value[bi*bs+ j*bnr + i] * x[bi*bnr+j];
k++;
}
y[bi*bnr+i] = t;
}
}
#ifdef _OPENMP
#pragma omp parallel for private(i,j,k,bi,bj,bc)
#endif
for(bi=0;bi<nc;bi++)
{
for(bc=A->L->bptr[bi];bc<A->L->bptr[bi+1];bc++)
{
bj = A->L->bindex[bc] * bnr;
k = bc*bs;
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
y[bj+i] += A->L->value[k] * x[bi*bnc+j];
k++;
}
}
}
for(bc=A->U->bptr[bi];bc<A->U->bptr[bi+1];bc++)
{
bj = A->U->bindex[bc] * bnr;
k = bc*bs;
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
y[bj+i] += A->U->value[k] * x[bi*bnc+j];
k++;
}
}
}
}
}
else
{
#ifdef _OPENMP
#pragma omp parallel for private(i)
#endif
for(i=0; i<n; i++)
{
y[i] = 0.0;
}
#ifdef _OPENMP
#pragma omp parallel for private(i,j,k,bi,bj,bc)
#endif
for(bi=0;bi<nc;bi++)
{
for(bc=A->bptr[bi];bc<A->bptr[bi+1];bc++)
{
bj = A->bindex[bc] * bnr;
k = bc*bs;
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
y[bj+i] += A->value[k] * x[bi*bnc+j];
k++;
}
}
}
}
}
}
void lis_matvec_bsc_1x1(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j] * x[jj];
}
y[i] = t0;
}
}
void lis_matvec_bsc_1x2(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*2+0] * x[jj*2+0];
t0 += A->value[j*2+1] * x[jj*2+1];
}
y[i] = t0;
}
}
void lis_matvec_bsc_1x3(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*3+0] * x[jj*3+0];
t0 += A->value[j*3+1] * x[jj*3+1];
t0 += A->value[j*3+2] * x[jj*3+2];
}
y[i] = t0;
}
}
void lis_matvec_bsc_1x4(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*4+0] * x[jj*4+0];
t0 += A->value[j*4+1] * x[jj*4+1];
t0 += A->value[j*4+2] * x[jj*4+2];
t0 += A->value[j*4+3] * x[jj*4+3];
}
y[i] = t0;
}
}
void lis_matvec_bsc_2x2(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0,t1;
n = A->n;
nr = A->nr;
if( A->is_splited )
{
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1)
#endif
for(i=0; i<nr; i++)
{
t0 = A->D->value[4*i+0] * x[2*i+0] + A->D->value[4*i+2] * x[2*i+1];
t1 = A->D->value[4*i+1] * x[2*i+0] + A->D->value[4*i+3] * x[2*i+1];
js = A->L->bptr[i];
je = A->L->bptr[i+1];
for(j=js;j<je;j++)
{
jj = A->L->bindex[j];
t0 += A->L->value[j*4+0] * x[jj*2+0];
t1 += A->L->value[j*4+1] * x[jj*2+0];
t0 += A->L->value[j*4+2] * x[jj*2+1];
t1 += A->L->value[j*4+3] * x[jj*2+1];
}
js = A->U->bptr[i];
je = A->U->bptr[i+1];
for(j=js;j<je;j++)
{
jj = A->U->bindex[j];
t0 += A->U->value[j*4+0] * x[jj*2+0];
t1 += A->U->value[j*4+1] * x[jj*2+0];
t0 += A->U->value[j*4+2] * x[jj*2+1];
t1 += A->U->value[j*4+3] * x[jj*2+1];
}
y[2*i+0] = t0;
y[2*i+1] = t1;
}
}
else
{
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
t1 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*4+0] * x[jj*2+0];
t1 += A->value[j*4+1] * x[jj*2+0];
t0 += A->value[j*4+2] * x[jj*2+1];
t1 += A->value[j*4+3] * x[jj*2+1];
}
y[2*i+0] = t0;
y[2*i+1] = t1;
}
}
}
void lis_matvec_bsc_2x1(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0,t1;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
t1 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*2+0] * x[jj];
t1 += A->value[j*2+1] * x[jj];
}
y[2*i+0] = t0;
y[2*i+1] = t1;
}
}
void lis_matvec_bsc_2x3(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0,t1;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
t1 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*6+0] * x[jj*3+0];
t1 += A->value[j*6+1] * x[jj*3+0];
t0 += A->value[j*6+2] * x[jj*3+1];
t1 += A->value[j*6+3] * x[jj*3+1];
t0 += A->value[j*6+4] * x[jj*3+2];
t1 += A->value[j*6+5] * x[jj*3+2];
}
y[2*i+0] = t0;
y[2*i+1] = t1;
}
}
void lis_matvec_bsc_2x4(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0,t1;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
t1 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*8+0] * x[jj*4+0];
t1 += A->value[j*8+1] * x[jj*4+0];
t0 += A->value[j*8+2] * x[jj*4+1];
t1 += A->value[j*8+3] * x[jj*4+1];
t0 += A->value[j*8+4] * x[jj*4+2];
t1 += A->value[j*8+5] * x[jj*4+2];
t0 += A->value[j*8+6] * x[jj*4+3];
t1 += A->value[j*8+7] * x[jj*4+3];
}
y[2*i+0] = t0;
y[2*i+1] = t1;
}
}
void lis_matvec_bsc_3x3(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0,t1,t2;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1,t2)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
t1 = 0.0;
t2 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*9+0] * x[jj*3+0];
t1 += A->value[j*9+1] * x[jj*3+0];
t2 += A->value[j*9+2] * x[jj*3+0];
t0 += A->value[j*9+3] * x[jj*3+1];
t1 += A->value[j*9+4] * x[jj*3+1];
t2 += A->value[j*9+5] * x[jj*3+1];
t0 += A->value[j*9+6] * x[jj*3+2];
t1 += A->value[j*9+7] * x[jj*3+2];
t2 += A->value[j*9+8] * x[jj*3+2];
}
y[3*i+0] = t0;
y[3*i+1] = t1;
y[3*i+2] = t2;
}
}
void lis_matvec_bsc_3x1(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj,ii;
LIS_INT n,nr;
LIS_SCALAR t0,t1,t2;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1,t2,ii)
#endif
for(i=0; i<nr; i++)
{
ii = 3*i;
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
t1 = 0.0;
t2 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*3+0] * x[jj];
t1 += A->value[j*3+1] * x[jj];
t2 += A->value[j*3+2] * x[jj];
}
y[ii+0] = t0;
y[ii+1] = t1;
y[ii+2] = t2;
}
}
void lis_matvec_bsc_3x2(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0,t1,t2;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1,t2)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
t1 = 0.0;
t2 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*6+0] * x[jj*2+0];
t1 += A->value[j*6+1] * x[jj*2+0];
t2 += A->value[j*6+2] * x[jj*2+0];
t0 += A->value[j*6+3] * x[jj*2+1];
t1 += A->value[j*6+4] * x[jj*2+1];
t2 += A->value[j*6+5] * x[jj*2+1];
}
y[3*i+0] = t0;
y[3*i+1] = t1;
y[3*i+2] = t2;
}
}
void lis_matvec_bsc_3x4(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0,t1,t2;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1,t2)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
t1 = 0.0;
t2 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*12+ 0] * x[jj*4+0];
t1 += A->value[j*12+ 1] * x[jj*4+0];
t2 += A->value[j*12+ 2] * x[jj*4+0];
t0 += A->value[j*12+ 3] * x[jj*4+1];
t1 += A->value[j*12+ 4] * x[jj*4+1];
t2 += A->value[j*12+ 5] * x[jj*4+1];
t0 += A->value[j*12+ 6] * x[jj*4+2];
t1 += A->value[j*12+ 7] * x[jj*4+2];
t2 += A->value[j*12+ 8] * x[jj*4+2];
t0 += A->value[j*12+ 9] * x[jj*4+3];
t1 += A->value[j*12+10] * x[jj*4+3];
t2 += A->value[j*12+11] * x[jj*4+3];
}
y[3*i+0] = t0;
y[3*i+1] = t1;
y[3*i+2] = t2;
}
}
void lis_matvec_bsc_4x4(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0,t1,t2,t3;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1,t2,t3)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
t1 = 0.0;
t2 = 0.0;
t3 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*16+ 0] * x[jj*4+0];
t1 += A->value[j*16+ 1] * x[jj*4+0];
t2 += A->value[j*16+ 2] * x[jj*4+0];
t3 += A->value[j*16+ 3] * x[jj*4+0];
t0 += A->value[j*16+ 4] * x[jj*4+1];
t1 += A->value[j*16+ 5] * x[jj*4+1];
t2 += A->value[j*16+ 6] * x[jj*4+1];
t3 += A->value[j*16+ 7] * x[jj*4+1];
t0 += A->value[j*16+ 8] * x[jj*4+2];
t1 += A->value[j*16+ 9] * x[jj*4+2];
t2 += A->value[j*16+10] * x[jj*4+2];
t3 += A->value[j*16+11] * x[jj*4+2];
t0 += A->value[j*16+12] * x[jj*4+3];
t1 += A->value[j*16+13] * x[jj*4+3];
t2 += A->value[j*16+14] * x[jj*4+3];
t3 += A->value[j*16+15] * x[jj*4+3];
}
y[4*i+0] = t0;
y[4*i+1] = t1;
y[4*i+2] = t2;
y[4*i+3] = t3;
}
}
void lis_matvec_bsc_4x1(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0,t1,t2,t3;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1,t2,t3)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
t1 = 0.0;
t2 = 0.0;
t3 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*4+ 0] * x[jj];
t1 += A->value[j*4+ 1] * x[jj];
t2 += A->value[j*4+ 2] * x[jj];
t3 += A->value[j*4+ 3] * x[jj];
}
y[4*i+0] = t0;
y[4*i+1] = t1;
y[4*i+2] = t2;
y[4*i+3] = t3;
}
}
void lis_matvec_bsc_4x2(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0,t1,t2,t3;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1,t2,t3)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
t1 = 0.0;
t2 = 0.0;
t3 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*8+ 0] * x[jj*2+0];
t1 += A->value[j*8+ 1] * x[jj*2+0];
t2 += A->value[j*8+ 2] * x[jj*2+0];
t3 += A->value[j*8+ 3] * x[jj*2+0];
t0 += A->value[j*8+ 4] * x[jj*2+1];
t1 += A->value[j*8+ 5] * x[jj*2+1];
t2 += A->value[j*8+ 6] * x[jj*2+1];
t3 += A->value[j*8+ 7] * x[jj*2+1];
}
y[4*i+0] = t0;
y[4*i+1] = t1;
y[4*i+2] = t2;
y[4*i+3] = t3;
}
}
void lis_matvec_bsc_4x3(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,js,je,jj;
LIS_INT n,nr;
LIS_SCALAR t0,t1,t2,t3;
n = A->n;
nr = A->nr;
#ifdef _OPENMP
#pragma omp parallel for private(i,j,jj,js,je,t0,t1,t2,t3)
#endif
for(i=0; i<nr; i++)
{
js = A->bptr[i];
je = A->bptr[i+1];
t0 = 0.0;
t1 = 0.0;
t2 = 0.0;
t3 = 0.0;
for(j=js;j<je;j++)
{
jj = A->bindex[j];
t0 += A->value[j*12+ 0] * x[jj*3+0];
t1 += A->value[j*12+ 1] * x[jj*3+0];
t2 += A->value[j*12+ 2] * x[jj*3+0];
t3 += A->value[j*12+ 3] * x[jj*3+0];
t0 += A->value[j*12+ 4] * x[jj*3+1];
t1 += A->value[j*12+ 5] * x[jj*3+1];
t2 += A->value[j*12+ 6] * x[jj*3+1];
t3 += A->value[j*12+ 7] * x[jj*3+1];
t0 += A->value[j*12+ 8] * x[jj*3+2];
t1 += A->value[j*12+ 9] * x[jj*3+2];
t2 += A->value[j*12+10] * x[jj*3+2];
t3 += A->value[j*12+11] * x[jj*3+2];
}
y[4*i+0] = t0;
y[4*i+1] = t1;
y[4*i+2] = t2;
y[4*i+3] = t3;
}
}
void lis_matvect_bsc(LIS_MATRIX A, LIS_SCALAR x[], LIS_SCALAR y[])
{
LIS_INT i,j,k;
LIS_INT bi,bj,bc,bs;
LIS_INT nr,nc,bnr,bnc;
LIS_INT n,np;
#ifdef _OPENMP
LIS_INT nprocs,my_rank;
LIS_SCALAR t;
LIS_SCALAR *w;
#endif
n = A->n;
np = A->np;
nr = A->nr;
nc = A->nc;
bnr = A->bnr;
bnc = A->bnc;
bs = bnr*bnc;
if( A->is_splited )
{
for(i=0;i<n;i++)
{
y[i] = 0.0;
}
for(bi=0;bi<nr;bi++)
{
k = bi*bs;
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
y[bi*bnr+j] += A->D->value[k++] * x[bi*bnr+i];
}
}
}
for(bi=0;bi<nc;bi++)
{
for(bc=A->L->bptr[bi];bc<A->L->bptr[bi+1];bc++)
{
bj = A->L->bindex[bc] * bnr;
k = bc*bs;
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
y[bj+j] += A->L->value[k] * x[bi*bnr+i];
k++;
}
}
}
for(bc=A->U->bptr[bi];bc<A->U->bptr[bi+1];bc++)
{
bj = A->U->bindex[bc] * bnr;
k = bc*bs;
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
y[bj+j] += A->U->value[k] * x[bi*bnr+i];
k++;
}
}
}
}
}
else
{
#ifdef _OPENMP
nprocs = omp_get_max_threads();
w = (LIS_SCALAR *)lis_malloc( nprocs*np*sizeof(LIS_SCALAR),"lis_matvect_bsc::w" );
#pragma omp parallel private(bi,bc,bj,i,j,k,my_rank)
{
my_rank = omp_get_thread_num();
#pragma omp for
for(j=0;j<nprocs;j++)
{
memset( &w[j*np], 0, np*sizeof(LIS_SCALAR) );
}
#pragma omp for
for(bi=0;bi<nc;bi++)
{
for(bc=A->bptr[bi];bc<A->bptr[bi+1];bc++)
{
bj = A->bindex[bc] * bnr;
k = bc*bs;
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
w[bi*bnc+j] += A->value[k] * x[bj+i];
k++;
}
}
}
}
#pragma omp barrier
#pragma omp for
for(i=0;i<np;i++)
{
t = 0.0;
for(j=0;j<nprocs;j++)
{
t += w[j*np+i];
}
y[i] = t;
}
}
lis_free(w);
#else
for(i=0; i<n; i++)
{
y[i] = 0.0;
}
for(bi=0;bi<nc;bi++)
{
for(bc=A->bptr[bi];bc<A->bptr[bi+1];bc++)
{
bj = A->bindex[bc] * bnr;
k = bc*bs;
for(j=0;j<bnc;j++)
{
for(i=0;i<bnr;i++)
{
y[bi*bnc+j] += A->value[k] * x[bj+i];
k++;
}
}
}
}
#endif
}
}
|
tvl1flow_lib.c |
// This program is free software: you can use, modify and/or redistribute it
// under the terms of the simplified BSD License. You should have received a
// copy of this license along this program. If not, see
// <http://www.opensource.org/licenses/bsd-license.html>.
//
// Copyright (C) 2011, Javier Sánchez Pérez <jsanchez@dis.ulpgc.es>
// All rights reserved.
#ifndef DUAL_TVL1_OPTIC_FLOW_H
#define DUAL_TVL1_OPTIC_FLOW_H
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "mask.c"
#include "bicubic_interpolation.c"
#include "zoom.c"
#define MAX_ITERATIONS 300
#define PRESMOOTHING_SIGMA 0.8
#define GRAD_IS_ZERO 1E-10
/**
* Implementation of the Zach, Pock and Bischof dual TV-L1 optic flow method
*
* see reference:
* [1] C. Zach, T. Pock and H. Bischof, "A Duality Based Approach for Realtime
* TV-L1 Optical Flow", In Proceedings of Pattern Recognition (DAGM),
* Heidelberg, Germany, pp. 214-223, 2007
*
*
* Details on the total variation minimization scheme can be found in:
* [2] A. Chambolle, "An Algorithm for Total Variation Minimization and
* Applications", Journal of Mathematical Imaging and Vision, 20: 89-97, 2004
**/
/**
*
* Function to compute the optical flow in one scale
*
**/
void Dual_TVL1_optic_flow(
float *I0, // source image
float *I1, // target image
float *u1, // x component of the optical flow
float *u2, // y component of the optical flow
const int nx, // image width
const int ny, // image height
const float tau, // time step
const float lambda, // weight parameter for the data term
const float theta, // weight parameter for (u - v)²
const int warps, // number of warpings per scale
const float epsilon, // tolerance for numerical convergence
const bool verbose // enable/disable the verbose mode
)
{
const int size = nx * ny;
const float l_t = lambda * theta;
size_t sf = sizeof(float);
float *I1x = malloc(size*sf);
float *I1y = xmalloc(size*sf);
float *I1w = xmalloc(size*sf);
float *I1wx = xmalloc(size*sf);
float *I1wy = xmalloc(size*sf);
float *rho_c = xmalloc(size*sf);
float *v1 = xmalloc(size*sf);
float *v2 = xmalloc(size*sf);
float *p11 = xmalloc(size*sf);
float *p12 = xmalloc(size*sf);
float *p21 = xmalloc(size*sf);
float *p22 = xmalloc(size*sf);
float *div = xmalloc(size*sf);
float *grad = xmalloc(size*sf);
float *div_p1 = xmalloc(size*sf);
float *div_p2 = xmalloc(size*sf);
float *u1x = xmalloc(size*sf);
float *u1y = xmalloc(size*sf);
float *u2x = xmalloc(size*sf);
float *u2y = xmalloc(size*sf);
centered_gradient(I1, I1x, I1y, nx, ny);
// initialization of p
for (int i = 0; i < size; i++)
{
p11[i] = p12[i] = 0.0;
p21[i] = p22[i] = 0.0;
}
for (int warpings = 0; warpings < warps; warpings++)
{
// compute the warping of the target image and its derivatives
bicubic_interpolation_warp(I1, u1, u2, I1w, nx, ny, true);
bicubic_interpolation_warp(I1x, u1, u2, I1wx, nx, ny, true);
bicubic_interpolation_warp(I1y, u1, u2, I1wy, nx, ny, true);
#pragma omp parallel for
for (int i = 0; i < size; i++)
{
const float Ix2 = I1wx[i] * I1wx[i];
const float Iy2 = I1wy[i] * I1wy[i];
// store the |Grad(I1)|^2
grad[i] = (Ix2 + Iy2);
// compute the constant part of the rho function
rho_c[i] = (I1w[i] - I1wx[i] * u1[i]
- I1wy[i] * u2[i] - I0[i]);
}
int n = 0;
float error = INFINITY;
while (error > epsilon * epsilon && n < MAX_ITERATIONS)
{
n++;
// estimate the values of the variable (v1, v2)
// (thresholding opterator TH)
#pragma omp parallel for
for (int i = 0; i < size; i++)
{
const float rho = rho_c[i]
+ (I1wx[i] * u1[i] + I1wy[i] * u2[i]);
float d1, d2;
if (rho < - l_t * grad[i])
{
d1 = l_t * I1wx[i];
d2 = l_t * I1wy[i];
}
else
{
if (rho > l_t * grad[i])
{
d1 = -l_t * I1wx[i];
d2 = -l_t * I1wy[i];
}
else
{
if (grad[i] < GRAD_IS_ZERO)
d1 = d2 = 0;
else
{
float fi = -rho/grad[i];
d1 = fi * I1wx[i];
d2 = fi * I1wy[i];
}
}
}
v1[i] = u1[i] + d1;
v2[i] = u2[i] + d2;
}
// compute the divergence of the dual variable (p1, p2)
divergence(p11, p12, div_p1, nx ,ny);
divergence(p21, p22, div_p2, nx ,ny);
// estimate the values of the optical flow (u1, u2)
error = 0.0;
#pragma omp parallel for reduction(+:error)
for (int i = 0; i < size; i++)
{
const float u1k = u1[i];
const float u2k = u2[i];
u1[i] = v1[i] + theta * div_p1[i];
u2[i] = v2[i] + theta * div_p2[i];
error += (u1[i] - u1k) * (u1[i] - u1k) +
(u2[i] - u2k) * (u2[i] - u2k);
}
error /= size;
// compute the gradient of the optical flow (Du1, Du2)
forward_gradient(u1, u1x, u1y, nx ,ny);
forward_gradient(u2, u2x, u2y, nx ,ny);
// estimate the values of the dual variable (p1, p2)
#pragma omp parallel for
for (int i = 0; i < size; i++)
{
const float taut = tau / theta;
const float g1 = hypot(u1x[i], u1y[i]);
const float g2 = hypot(u2x[i], u2y[i]);
const float ng1 = 1.0 + taut * g1;
const float ng2 = 1.0 + taut * g2;
p11[i] = (p11[i] + taut * u1x[i]) / ng1;
p12[i] = (p12[i] + taut * u1y[i]) / ng1;
p21[i] = (p21[i] + taut * u2x[i]) / ng2;
p22[i] = (p22[i] + taut * u2y[i]) / ng2;
}
}
if (verbose)
fprintf(stderr, "Warping: %d, "
"Iterations: %d, "
"Error: %f\n", warpings, n, error);
}
// delete allocated memory
free(I1x);
free(I1y);
free(I1w);
free(I1wx);
free(I1wy);
free(rho_c);
free(v1);
free(v2);
free(p11);
free(p12);
free(p21);
free(p22);
free(div);
free(grad);
free(div_p1);
free(div_p2);
free(u1x);
free(u1y);
free(u2x);
free(u2y);
}
/**
*
* Compute the max and min of an array
*
**/
static void getminmax(
float *min, // output min
float *max, // output max
const float *x, // input array
int n // array size
)
{
*min = *max = x[0];
for (int i = 1; i < n; i++) {
if (x[i] < *min)
*min = x[i];
if (x[i] > *max)
*max = x[i];
}
}
/**
*
* Function to normalize the images between 0 and 255
*
**/
void image_normalization(
const float *I0, // input image0
const float *I1, // input image1
float *I0n, // normalized output image0
float *I1n, // normalized output image1
int size // size of the image
)
{
float max0, max1, min0, min1;
// obtain the max and min of each image
getminmax(&min0, &max0, I0, size);
getminmax(&min1, &max1, I1, size);
// obtain the max and min of both images
const float max = (max0 > max1)? max0 : max1;
const float min = (min0 < min1)? min0 : min1;
const float den = max - min;
if (den > 0)
// normalize both images
for (int i = 0; i < size; i++)
{
I0n[i] = 255.0 * (I0[i] - min) / den;
I1n[i] = 255.0 * (I1[i] - min) / den;
}
else
// copy the original images
for (int i = 0; i < size; i++)
{
I0n[i] = I0[i];
I1n[i] = I1[i];
}
}
/**
*
* Function to compute the optical flow using multiple scales
*
**/
void Dual_TVL1_optic_flow_multiscale(
float *I0, // source image
float *I1, // target image
float *u1, // x component of the optical flow
float *u2, // y component of the optical flow
const int nxx, // image width
const int nyy, // image height
const float tau, // time step
const float lambda, // weight parameter for the data term
const float theta, // weight parameter for (u - v)²
const int nscales, // number of scales
const float zfactor, // factor for building the image piramid
const int warps, // number of warpings per scale
const float epsilon, // tolerance for numerical convergence
const bool verbose // enable/disable the verbose mode
)
{
int size = nxx * nyy;
// allocate memory for the pyramid structure
float **I0s = xmalloc(nscales * sizeof(float*));
float **I1s = xmalloc(nscales * sizeof(float*));
float **u1s = xmalloc(nscales * sizeof(float*));
float **u2s = xmalloc(nscales * sizeof(float*));
int *nx = xmalloc(nscales * sizeof(int));
int *ny = xmalloc(nscales * sizeof(int));
I0s[0] = xmalloc(size*sizeof(float));
I1s[0] = xmalloc(size*sizeof(float));
u1s[0] = u1;
u2s[0] = u2;
nx [0] = nxx;
ny [0] = nyy;
// normalize the images between 0 and 255
image_normalization(I0, I1, I0s[0], I1s[0], size);
// pre-smooth the original images
gaussian(I0s[0], nx[0], ny[0], PRESMOOTHING_SIGMA);
gaussian(I1s[0], nx[0], ny[0], PRESMOOTHING_SIGMA);
// create the scales
for (int s = 1; s < nscales; s++)
{
zoom_size(nx[s-1], ny[s-1], &nx[s], &ny[s], zfactor);
const int sizes = nx[s] * ny[s];
// allocate memory
I0s[s] = xmalloc(sizes*sizeof(float));
I1s[s] = xmalloc(sizes*sizeof(float));
u1s[s] = xmalloc(sizes*sizeof(float));
u2s[s] = xmalloc(sizes*sizeof(float));
// zoom in the images to create the pyramidal structure
zoom_out(I0s[s-1], I0s[s], nx[s-1], ny[s-1], zfactor);
zoom_out(I1s[s-1], I1s[s], nx[s-1], ny[s-1], zfactor);
}
// initialize the flow at the coarsest scale
for (int i = 0; i < nx[nscales-1] * ny[nscales-1]; i++)
u1s[nscales-1][i] = u2s[nscales-1][i] = 0.0;
// pyramidal structure for computing the optical flow
for (int s = nscales-1; s >= 0; s--)
{
if (verbose)
fprintf(stderr, "Scale %d: %dx%d\n", s, nx[s], ny[s]);
// compute the optical flow at the current scale
Dual_TVL1_optic_flow(
I0s[s], I1s[s], u1s[s], u2s[s], nx[s], ny[s],
tau, lambda, theta, warps, epsilon, verbose
);
// if this was the last scale, finish now
if (!s) break;
// otherwise, upsample the optical flow
// zoom the optical flow for the next finer scale
zoom_in(u1s[s], u1s[s-1], nx[s], ny[s], nx[s-1], ny[s-1]);
zoom_in(u2s[s], u2s[s-1], nx[s], ny[s], nx[s-1], ny[s-1]);
// scale the optical flow with the appropriate zoom factor
for (int i = 0; i < nx[s-1] * ny[s-1]; i++)
{
u1s[s-1][i] *= (float) 1.0 / zfactor;
u2s[s-1][i] *= (float) 1.0 / zfactor;
}
}
// delete allocated memory
for (int i = 1; i < nscales; i++)
{
free(I0s[i]);
free(I1s[i]);
free(u1s[i]);
free(u2s[i]);
}
free(I0s[0]);
free(I1s[0]);
free(I0s);
free(I1s);
free(u1s);
free(u2s);
free(nx);
free(ny);
}
#endif//DUAL_TVL1_OPTIC_FLOW_H
|
GB_binop__minus_uint8.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__minus_uint8)
// A.*B function (eWiseMult): GB (_AemultB_08__minus_uint8)
// A.*B function (eWiseMult): GB (_AemultB_02__minus_uint8)
// A.*B function (eWiseMult): GB (_AemultB_04__minus_uint8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__minus_uint8)
// A*D function (colscale): GB (_AxD__minus_uint8)
// D*A function (rowscale): GB (_DxB__minus_uint8)
// C+=B function (dense accum): GB (_Cdense_accumB__minus_uint8)
// C+=b function (dense accum): GB (_Cdense_accumb__minus_uint8)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__minus_uint8)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__minus_uint8)
// C=scalar+B GB (_bind1st__minus_uint8)
// C=scalar+B' GB (_bind1st_tran__minus_uint8)
// C=A+scalar GB (_bind2nd__minus_uint8)
// C=A'+scalar GB (_bind2nd_tran__minus_uint8)
// C type: uint8_t
// A type: uint8_t
// A pattern? 0
// B type: uint8_t
// B pattern? 0
// BinaryOp: cij = (aij - bij)
#define GB_ATYPE \
uint8_t
#define GB_BTYPE \
uint8_t
#define GB_CTYPE \
uint8_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
uint8_t aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint8_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint8_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (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_MINUS || GxB_NO_UINT8 || GxB_NO_MINUS_UINT8)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__minus_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__minus_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__minus_uint8)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__minus_uint8)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint8_t
uint8_t bwork = (*((uint8_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__minus_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__minus_uint8)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *restrict Cx = (uint8_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__minus_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
uint8_t alpha_scalar ;
uint8_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint8_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__minus_uint8)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__minus_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__minus_uint8)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__minus_uint8)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__minus_uint8)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t x = (*((uint8_t *) x_input)) ;
uint8_t *Bx = (uint8_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint8_t bij = GBX (Bx, p, false) ;
Cx [p] = (x - bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__minus_uint8)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint8_t *Cx = (uint8_t *) Cx_output ;
uint8_t *Ax = (uint8_t *) Ax_input ;
uint8_t y = (*((uint8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint8_t aij = GBX (Ax, p, false) ;
Cx [p] = (aij - y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x - aij) ; \
}
GrB_Info GB (_bind1st_tran__minus_uint8)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t x = (*((const uint8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint8_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij - y) ; \
}
GrB_Info GB (_bind2nd_tran__minus_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint8_t y = (*((const uint8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
orderedConstruct.c | int main() {
int x = 10;
#pragma omp parallel
{
int localX, localY;
#pragma omp for
for(localX = 0; local < 10; localX++) {
#pragma omp ordered
{
localY = x;
}
}
localX = 20;
}
x = 30;
}
|
misc_avx2.c | //sum.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/timeb.h>
#include <malloc.h>
#define N_RUNS 1000
#define N 120000
// read timer in second
double read_timer() {
struct timeb tm;
ftime(&tm);
return (double) tm.time + (double) tm.millitm / 1000.0;
}
//Create a matrix and a vector and fill with random numbers
void init(int *X) {
for (int i = 0; i<N; i++) {
X[i] = (int)rand()/(int)(RAND_MAX/10.0);
}
}
//Our sum function- what it does is pretty straight-forward.
int sum(int *X, int *Y, int *answer) {
int result = 0;
#pragma omp simd simdlen(8)
for (int i = 0; i<N; i++) {
answer[i] = X[i] + Y[i] * 2;
}
return result;
}
// Debug functions
int sum_serial(int *X, int *Y, int *answer) {
int result = 0;
for (int i = 0; i<N; i++) {
answer[i] = X[i] + Y[i] * 2;
}
return result;
}
void print_vector(int *vector) {
printf("[");
for (int i = 0; i<8; i++) {
printf("%d ", vector[i]);
}
puts("]");
}
int check(int *serial, int *SIMD) {
int diff = 0;
for (int i = 0; i<N; i++) diff += serial[i] - SIMD[i];
return diff;
}
int main(int argc, char **argv) {
//Set everything up
int *X = malloc(sizeof(int)*N);
int *Y = malloc(sizeof(int)*N);
int *answer = malloc(sizeof(int)*N);
int *answer_serial = malloc(sizeof(int)*N);
srand(time(NULL));
init(X);
init(Y);
double start = read_timer();
for (int i = 0; i<N_RUNS; i++)
sum(X, Y, answer);
double t = (read_timer() - start);
double start_serial = read_timer();
for (int i = 0; i<N_RUNS; i++)
sum_serial(X, Y, answer_serial);
double t_serial = (read_timer() - start_serial);
printf("X: ");
print_vector(X);
puts("+");
printf("Y: ");
print_vector(Y);
puts("=\n");
printf("SIMD:\n");
print_vector(answer);
puts("---------------------------------");
printf("Serial:\n");
print_vector(answer_serial);
double gflops = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t);
double gflops_serial = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t_serial);
printf("==================================================================\n");
printf("Performance:\t\t\tRuntime (s)\t GFLOPS\n");
printf("------------------------------------------------------------------\n");
printf("Sum (SIMD):\t\t%4f\t%4f\n", t, gflops);
printf("Sum (Serial):\t\t%4f\t%4f\n", t_serial, gflops_serial);
printf("Correctness:\t\t%d\n", check(answer_serial, answer));
free(X);
free(Y);
free(answer);
free(answer_serial);
return 0;
}
|
ft_ao.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.
*
* Fourier transformed AO pair
* \int e^{-i Gv \cdot r} i(r) * j(r) dr^3
*
* eval_gz, b, gxyz, gs:
* - when eval_gz is GTO_Gv_uniform_orth
* > b (reciprocal vectors) is diagonal 3x3 matrix
* > Gv k-space grids = dot(b.T,gxyz)
* > gxyz[3,nGv] = (kx[:nGv], ky[:nGv], kz[:nGv])
* > gs[3]: The number of G-vectors along each direction (nGv=gs[0]*gs[1]*gs[2]).
* - when eval_gz is GTO_Gv_uniform_nonorth
* > b is 3x3 matrix = 2\pi * scipy.linalg.inv(cell.lattice_vectors).T
* > Gv k-space grids = dot(b.T,gxyz)
* > gxyz[3,nGv] = (kx[:nGv], ky[:nGv], kz[:nGv])
* > gs[3]: The number of *positive* G-vectors along each direction.
* - when eval_gz is GTO_Gv_general
* only Gv is needed
* - when eval_gz is GTO_Gv_nonuniform_orth
* > b is the basic G value for each cartesian component
* Gx = b[:gs[0]]
* Gy = b[gs[0]:gs[0]+gs[1]]
* Gz = b[gs[0]+gs[1]:]
* > gs[3]: Number of basic G values along each direction.
* > gxyz[3,nGv] are used to index the basic G value
* > Gv is not used
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <complex.h>
#include "config.h"
#include "cint.h"
#include "gto/gto.h"
#include "gto/ft_ao.h"
#include "np_helper/np_helper.h"
#define SQRTPI 1.7724538509055160272981674833411451
#define EXP_CUTOFF 100
double CINTsquare_dist(const double *r1, const double *r2);
double CINTcommon_fac_sp(int l);
/*
* Pyscf-1.5 (and older) use libcint function CINTinit_int1e_EnvVars and
* CINTg1e_index_xyz. It's unsafe since the CINTEnvVars type was redefined
* in ft_ao.h. Copy the contents of CINTinit_int1e_EnvVars and
* CINTg1e_index_xyz here.
*/
#define IINC 0
#define JINC 1
#define GSHIFT 4
#define POS_E1 5
#define RYS_ROOTS 6
#define TENSOR 7
void GTO_ft_init1e_envs(CINTEnvVars *envs, int *ng, int *shls,
int *atm, int natm, int *bas, int nbas, double *env)
{
envs->natm = natm;
envs->nbas = nbas;
envs->atm = atm;
envs->bas = bas;
envs->env = env;
envs->shls = shls;
const int i_sh = shls[0];
const int j_sh = shls[1];
envs->i_l = bas(ANG_OF, i_sh);
envs->j_l = bas(ANG_OF, j_sh);
envs->x_ctr[0] = bas(NCTR_OF, i_sh);
envs->x_ctr[1] = bas(NCTR_OF, j_sh);
envs->nfi = (envs->i_l+1)*(envs->i_l+2)/2;
envs->nfj = (envs->j_l+1)*(envs->j_l+2)/2;
envs->nf = envs->nfi * envs->nfj;
envs->common_factor = 1;
envs->gbits = ng[GSHIFT];
envs->ncomp_e1 = ng[POS_E1];
envs->ncomp_tensor = ng[TENSOR];
envs->li_ceil = envs->i_l + ng[IINC];
envs->lj_ceil = envs->j_l + ng[JINC];
if (ng[RYS_ROOTS] > 0) {
envs->nrys_roots = ng[RYS_ROOTS];
} else {
envs->nrys_roots = (envs->li_ceil + envs->lj_ceil)/2 + 1;
}
envs->ri = env + atm(PTR_COORD, bas(ATOM_OF, i_sh));
envs->rj = env + atm(PTR_COORD, bas(ATOM_OF, j_sh));
int dli, dlj;
if (envs->li_ceil < envs->lj_ceil) {
dli = envs->li_ceil + 1;
dlj = envs->li_ceil + envs->lj_ceil + 1;
} else {
dli = envs->li_ceil + envs->lj_ceil + 1;
dlj = envs->lj_ceil + 1;
}
envs->g_stride_i = 1;
envs->g_stride_j = dli;
envs->g_size = dli * dlj;
envs->lk_ceil = 1;
envs->ll_ceil = 1;
envs->g_stride_k = 0;
envs->g_stride_l = 0;
}
void CINTcart_comp(int *nx, int *ny, int *nz, const int lmax);
static void _g2c_index_xyz(int *idx, const CINTEnvVars *envs)
{
int i_l = envs->i_l;
int j_l = envs->j_l;
int nfi = envs->nfi;
int nfj = envs->nfj;
int di = envs->g_stride_i;
int dj = envs->g_stride_j;
int i, j, n;
int ofx, ofjx;
int ofy, ofjy;
int ofz, ofjz;
int i_nx[CART_MAX], i_ny[CART_MAX], i_nz[CART_MAX];
int j_nx[CART_MAX], j_ny[CART_MAX], j_nz[CART_MAX];
CINTcart_comp(i_nx, i_ny, i_nz, i_l);
CINTcart_comp(j_nx, j_ny, j_nz, j_l);
ofx = 0;
ofy = envs->g_size;
ofz = envs->g_size * 2;
n = 0;
for (j = 0; j < nfj; j++) {
ofjx = ofx + dj * j_nx[j];
ofjy = ofy + dj * j_ny[j];
ofjz = ofz + dj * j_nz[j];
for (i = 0; i < nfi; i++) {
idx[n+0] = ofjx + di * i_nx[i];
idx[n+1] = ofjy + di * i_ny[i];
idx[n+2] = ofjz + di * i_nz[i];
n += 3;
}
}
}
static const int _LEN_CART[] = {
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136
};
static const int _CUM_LEN_CART[] = {
1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364, 455, 560, 680, 816,
};
/*
* WHEREX_IF_L_INC1 = [xyz2addr(x,y,z) for x,y,z in loopcart(L_MAX) if x > 0]
* WHEREY_IF_L_INC1 = [xyz2addr(x,y,z) for x,y,z in loopcart(L_MAX) if y > 0]
* WHEREZ_IF_L_INC1 = [xyz2addr(x,y,z) for x,y,z in loopcart(L_MAX) if z > 0]
*/
static const int _UPIDY[] = {
1,
3, 4,
6, 7, 8,
10, 11, 12, 13,
15, 16, 17, 18, 19,
21, 22, 23, 24, 25, 26,
28, 29, 30, 31, 32, 33, 34,
36, 37, 38, 39, 40, 41, 42, 43,
45, 46, 47, 48, 49, 50, 51, 52, 53,
55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,
105,106,107,108,109,110,111,112,113,114,115,116,117,118,
120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,
};
static const int _UPIDZ[] = {
2,
4, 5,
7, 8, 9,
11, 12, 13, 14,
16, 17, 18, 19, 20,
22, 23, 24, 25, 26, 27,
29, 30, 31, 32, 33, 34, 35,
37, 38, 39, 40, 41, 42, 43, 44,
46, 47, 48, 49, 50, 51, 52, 53, 54,
56, 57, 58, 59, 60, 61, 62, 63, 64, 65,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,
106,107,108,109,110,111,112,113,114,115,116,117,118,119,
121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,
};
/*
* _DOWN_XYZ, _DOWN_XYZ_ORDER, _DOWN1, _DOWN2 labels the index in the 1D
* recursive relation f_{i+1} = i/2a * f_{i-1} + X * f_{i}
* _DOWN_XYZ_ORDER i in i/2a
* _DOWN2 index of f_{i-1}
* _DOWN_XYZ index of X
* _DOWN1 index of f_{i}
*/
static const int _DOWN1[] = {
-1,
0, 0, 0,
0, 1, 2, 1, 2, 2,
0, 0, 0, 3, 4, 5, 3, 3, 5, 5,
0, 0, 0, 3, 2, 5, 6, 7, 8, 9, 6, 6, 8, 9, 9,
0, 0, 0, 3, 2, 5, 6, 3, 5, 9, 10, 11, 12, 13, 14, 10, 10, 12, 13, 14, 14,
0, 0, 0, 3, 2, 5, 6, 3, 5, 9, 10, 6, 12, 9, 14, 15, 16, 17, 18, 19, 20, 15, 15, 17, 18, 19, 20, 20,
0, 0, 0, 3, 2, 5, 6, 3, 5, 9, 10, 6, 12, 9, 14, 15, 10, 17, 18, 14, 20, 21, 22, 23, 24, 25, 26, 27, 21, 21, 23, 24, 25, 26, 27, 27,
0, 0, 0, 3, 2, 5, 6, 3, 5, 9, 10, 6, 12, 9, 14, 15, 10, 17, 18, 14, 20, 21, 15, 23, 24, 25, 20, 27, 28, 29, 30, 31, 32, 33, 34, 35, 28, 28, 30, 31, 32, 33, 34, 35, 35,
0, 0, 0, 3, 2, 5, 6, 3, 5, 9, 10, 6, 12, 9, 14, 15, 10, 17, 18, 14, 20, 21, 15, 23, 24, 25, 20, 27, 28, 21, 30, 31, 32, 33, 27, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 36, 36, 38, 39, 40, 41, 42, 43, 44, 44,
0, 0, 0, 3, 2, 5, 6, 3, 5, 9, 10, 6, 12, 9, 14, 15, 10, 17, 18, 14, 20, 21, 15, 23, 24, 25, 20, 27, 28, 21, 30, 31, 32, 33, 27, 35, 36, 28, 38, 39, 40, 41, 42, 35, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 45, 45, 47, 48, 49, 50, 51, 52, 53, 54, 54,
0, 0, 0, 3, 2, 5, 6, 3, 5, 9, 10, 6, 12, 9, 14, 15, 10, 17, 18, 14, 20, 21, 15, 23, 24, 25, 20, 27, 28, 21, 30, 31, 32, 33, 27, 35, 36, 28, 38, 39, 40, 41, 42, 35, 44, 45, 36, 47, 48, 49, 50, 51, 52, 44, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 55, 55, 57, 58, 59, 60, 61, 62, 63, 64, 65, 65,
0, 0, 0, 3, 2, 5, 6, 3, 5, 9, 10, 6, 12, 9, 14, 15, 10, 17, 18, 14, 20, 21, 15, 23, 24, 25, 20, 27, 28, 21, 30, 31, 32, 33, 27, 35, 36, 28, 38, 39, 40, 41, 42, 35, 44, 45, 36, 47, 48, 49, 50, 51, 52, 44, 54, 55, 45, 57, 58, 59, 60, 61, 62, 63, 54, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 66, 66, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 77,
0, 0, 0, 3, 2, 5, 6, 3, 5, 9, 10, 6, 12, 9, 14, 15, 10, 17, 18, 14, 20, 21, 15, 23, 24, 25, 20, 27, 28, 21, 30, 31, 32, 33, 27, 35, 36, 28, 38, 39, 40, 41, 42, 35, 44, 45, 36, 47, 48, 49, 50, 51, 52, 44, 54, 55, 45, 57, 58, 59, 60, 61, 62, 63, 54, 65, 66, 55, 68, 69, 70, 71, 72, 73, 74, 75, 65, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 78, 78, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 90,
0, 0, 0, 3, 2, 5, 6, 3, 5, 9, 10, 6, 12, 9, 14, 15, 10, 17, 18, 14, 20, 21, 15, 23, 24, 25, 20, 27, 28, 21, 30, 31, 32, 33, 27, 35, 36, 28, 38, 39, 40, 41, 42, 35, 44, 45, 36, 47, 48, 49, 50, 51, 52, 44, 54, 55, 45, 57, 58, 59, 60, 61, 62, 63, 54, 65, 66, 55, 68, 69, 70, 71, 72, 73, 74, 75, 65, 77, 78, 66, 80, 81, 82, 83, 84, 85, 86, 87, 88, 77, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 91, 91, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 104,
0, 0, 0, 3, 2, 5, 6, 3, 5, 9, 10, 6, 12, 9, 14, 15, 10, 17, 18, 14, 20, 21, 15, 23, 24, 25, 20, 27, 28, 21, 30, 31, 32, 33, 27, 35, 36, 28, 38, 39, 40, 41, 42, 35, 44, 45, 36, 47, 48, 49, 50, 51, 52, 44, 54, 55, 45, 57, 58, 59, 60, 61, 62, 63, 54, 65, 66, 55, 68, 69, 70, 71, 72, 73, 74, 75, 65, 77, 78, 66, 80, 81, 82, 83, 84, 85, 86, 87, 88, 77, 90, 91, 78, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 90, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 105, 105, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 119,
};
static const int _DOWN2[] = {
-1,
-1, -1, -1,
0, -1, -1, 0, -1, 0,
0, -1, -1, -1, -1, -1, 1, -1, -1, 2,
0, -1, -1, 3, -1, 5, -1, -1, -1, -1, 3, -1, 5, -1, 5,
0, -1, -1, 3, -1, 5, 6, -1, -1, 9, -1, -1, -1, -1, -1, 6, -1, 8, 9, -1, 9,
0, -1, -1, 3, -1, 5, 6, -1, -1, 9, 10, -1, 12, -1, 14, -1, -1, -1, -1, -1, -1, 10, -1, 12, 13, 14, -1, 14,
0, -1, -1, 3, -1, 5, 6, -1, -1, 9, 10, -1, 12, -1, 14, 15, -1, 17, 18, -1, 20, -1, -1, -1, -1, -1, -1, -1, 15, -1, 17, 18, 19, 20, -1, 20,
0, -1, -1, 3, -1, 5, 6, -1, -1, 9, 10, -1, 12, -1, 14, 15, -1, 17, 18, -1, 20, 21, -1, 23, 24, 25, -1, 27, -1, -1, -1, -1, -1, -1, -1, -1, 21, -1, 23, 24, 25, 26, 27, -1, 27,
0, -1, -1, 3, -1, 5, 6, -1, -1, 9, 10, -1, 12, -1, 14, 15, -1, 17, 18, -1, 20, 21, -1, 23, 24, 25, -1, 27, 28, -1, 30, 31, 32, 33, -1, 35, -1, -1, -1, -1, -1, -1, -1, -1, -1, 28, -1, 30, 31, 32, 33, 34, 35, -1, 35,
0, -1, -1, 3, -1, 5, 6, -1, -1, 9, 10, -1, 12, -1, 14, 15, -1, 17, 18, -1, 20, 21, -1, 23, 24, 25, -1, 27, 28, -1, 30, 31, 32, 33, -1, 35, 36, -1, 38, 39, 40, 41, 42, -1, 44, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 36, -1, 38, 39, 40, 41, 42, 43, 44, -1, 44,
0, -1, -1, 3, -1, 5, 6, -1, -1, 9, 10, -1, 12, -1, 14, 15, -1, 17, 18, -1, 20, 21, -1, 23, 24, 25, -1, 27, 28, -1, 30, 31, 32, 33, -1, 35, 36, -1, 38, 39, 40, 41, 42, -1, 44, 45, -1, 47, 48, 49, 50, 51, 52, -1, 54, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 45, -1, 47, 48, 49, 50, 51, 52, 53, 54, -1, 54,
0, -1, -1, 3, -1, 5, 6, -1, -1, 9, 10, -1, 12, -1, 14, 15, -1, 17, 18, -1, 20, 21, -1, 23, 24, 25, -1, 27, 28, -1, 30, 31, 32, 33, -1, 35, 36, -1, 38, 39, 40, 41, 42, -1, 44, 45, -1, 47, 48, 49, 50, 51, 52, -1, 54, 55, -1, 57, 58, 59, 60, 61, 62, 63, -1, 65, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 55, -1, 57, 58, 59, 60, 61, 62, 63, 64, 65, -1, 65,
0, -1, -1, 3, -1, 5, 6, -1, -1, 9, 10, -1, 12, -1, 14, 15, -1, 17, 18, -1, 20, 21, -1, 23, 24, 25, -1, 27, 28, -1, 30, 31, 32, 33, -1, 35, 36, -1, 38, 39, 40, 41, 42, -1, 44, 45, -1, 47, 48, 49, 50, 51, 52, -1, 54, 55, -1, 57, 58, 59, 60, 61, 62, 63, -1, 65, 66, -1, 68, 69, 70, 71, 72, 73, 74, 75, -1, 77, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 66, -1, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, -1, 77,
0, -1, -1, 3, -1, 5, 6, -1, -1, 9, 10, -1, 12, -1, 14, 15, -1, 17, 18, -1, 20, 21, -1, 23, 24, 25, -1, 27, 28, -1, 30, 31, 32, 33, -1, 35, 36, -1, 38, 39, 40, 41, 42, -1, 44, 45, -1, 47, 48, 49, 50, 51, 52, -1, 54, 55, -1, 57, 58, 59, 60, 61, 62, 63, -1, 65, 66, -1, 68, 69, 70, 71, 72, 73, 74, 75, -1, 77, 78, -1, 80, 81, 82, 83, 84, 85, 86, 87, 88, -1, 90, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 78, -1, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, -1, 90,
0, -1, -1, 3, -1, 5, 6, -1, -1, 9, 10, -1, 12, -1, 14, 15, -1, 17, 18, -1, 20, 21, -1, 23, 24, 25, -1, 27, 28, -1, 30, 31, 32, 33, -1, 35, 36, -1, 38, 39, 40, 41, 42, -1, 44, 45, -1, 47, 48, 49, 50, 51, 52, -1, 54, 55, -1, 57, 58, 59, 60, 61, 62, 63, -1, 65, 66, -1, 68, 69, 70, 71, 72, 73, 74, 75, -1, 77, 78, -1, 80, 81, 82, 83, 84, 85, 86, 87, 88, -1, 90, 91, -1, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, -1, 104, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 91, -1, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, -1, 104,
};
static const int _DOWN_XYZ[] = {
2,
0, 1, 2,
0, 0, 0, 1, 1, 2,
0, 1, 2, 0, 0, 0, 1, 2, 1, 2,
0, 1, 2, 0, 1, 0, 0, 0, 0, 0, 1, 2, 1, 1, 2,
0, 1, 2, 0, 1, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 1, 2,
0, 1, 2, 0, 1, 0, 0, 2, 1, 0, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 1, 1, 2,
0, 1, 2, 0, 1, 0, 0, 2, 1, 0, 0, 2, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 1, 1, 1, 2,
0, 1, 2, 0, 1, 0, 0, 2, 1, 0, 0, 2, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 1, 1, 1, 1, 2,
0, 1, 2, 0, 1, 0, 0, 2, 1, 0, 0, 2, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 2, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2,
0, 1, 2, 0, 1, 0, 0, 2, 1, 0, 0, 2, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 2, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2,
0, 1, 2, 0, 1, 0, 0, 2, 1, 0, 0, 2, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 2, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
0, 1, 2, 0, 1, 0, 0, 2, 1, 0, 0, 2, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 2, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
0, 1, 2, 0, 1, 0, 0, 2, 1, 0, 0, 2, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 2, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
0, 1, 2, 0, 1, 0, 0, 2, 1, 0, 0, 2, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 2, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
0, 1, 2, 0, 1, 0, 0, 2, 1, 0, 0, 2, 0, 1, 0, 0, 2, 0, 0, 1, 0, 0, 2, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
};
static const int _DOWN_XYZ_ORDER[] = {
0,
0, 0, 0,
1, 0, 0, 1, 0, 1,
2, 0, 0, 0, 0, 0, 2, 0, 0, 2,
3, 0, 0, 1, 0, 1, 0, 0, 0, 0, 3, 0, 1, 0, 3,
4, 0, 0, 2, 0, 2, 1, 0, 0, 1, 0, 0, 0, 0, 0, 4, 0, 2, 1, 0, 4,
5, 0, 0, 3, 0, 3, 2, 0, 0, 2, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 5, 0, 3, 2, 1, 0, 5,
6, 0, 0, 4, 0, 4, 3, 0, 0, 3, 2, 0, 2, 0, 2, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 6, 0, 4, 3, 2, 1, 0, 6,
7, 0, 0, 5, 0, 5, 4, 0, 0, 4, 3, 0, 3, 0, 3, 2, 0, 2, 2, 0, 2, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 5, 4, 3, 2, 1, 0, 7,
8, 0, 0, 6, 0, 6, 5, 0, 0, 5, 4, 0, 4, 0, 4, 3, 0, 3, 3, 0, 3, 2, 0, 2, 2, 2, 0, 2, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 6, 5, 4, 3, 2, 1, 0, 8,
9, 0, 0, 7, 0, 7, 6, 0, 0, 6, 5, 0, 5, 0, 5, 4, 0, 4, 4, 0, 4, 3, 0, 3, 3, 3, 0, 3, 2, 0, 2, 2, 2, 2, 0, 2, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 7, 6, 5, 4, 3, 2, 1, 0, 9,
10, 0, 0, 8, 0, 8, 7, 0, 0, 7, 6, 0, 6, 0, 6, 5, 0, 5, 5, 0, 5, 4, 0, 4, 4, 4, 0, 4, 3, 0, 3, 3, 3, 3, 0, 3, 2, 0, 2, 2, 2, 2, 2, 0, 2, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 8, 7, 6, 5, 4, 3, 2, 1, 0, 10,
11, 0, 0, 9, 0, 9, 8, 0, 0, 8, 7, 0, 7, 0, 7, 6, 0, 6, 6, 0, 6, 5, 0, 5, 5, 5, 0, 5, 4, 0, 4, 4, 4, 4, 0, 4, 3, 0, 3, 3, 3, 3, 3, 0, 3, 2, 0, 2, 2, 2, 2, 2, 2, 0, 2, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 11,
12, 0, 0, 10, 0, 10, 9, 0, 0, 9, 8, 0, 8, 0, 8, 7, 0, 7, 7, 0, 7, 6, 0, 6, 6, 6, 0, 6, 5, 0, 5, 5, 5, 5, 0, 5, 4, 0, 4, 4, 4, 4, 4, 0, 4, 3, 0, 3, 3, 3, 3, 3, 3, 0, 3, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 12,
13, 0, 0, 11, 0, 11, 10, 0, 0, 10, 9, 0, 9, 0, 9, 8, 0, 8, 8, 0, 8, 7, 0, 7, 7, 7, 0, 7, 6, 0, 6, 6, 6, 6, 0, 6, 5, 0, 5, 5, 5, 5, 5, 0, 5, 4, 0, 4, 4, 4, 4, 4, 4, 0, 4, 3, 0, 3, 3, 3, 3, 3, 3, 3, 0, 3, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 13,
14, 0, 0, 12, 0, 12, 11, 0, 0, 11, 10, 0, 10, 0, 10, 9, 0, 9, 9, 0, 9, 8, 0, 8, 8, 8, 0, 8, 7, 0, 7, 7, 7, 7, 0, 7, 6, 0, 6, 6, 6, 6, 6, 0, 6, 5, 0, 5, 5, 5, 5, 5, 5, 0, 5, 4, 0, 4, 4, 4, 4, 4, 4, 4, 0, 4, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 14,
};
#define WHEREX_IF_L_INC1(i) i
#define WHEREY_IF_L_INC1(i) _UPIDY[i]
#define WHEREZ_IF_L_INC1(i) _UPIDZ[i]
#define STARTX_IF_L_DEC1(i) 0
#define STARTY_IF_L_DEC1(i) ((i<2)?0:_LEN_CART[i-2])
#define STARTZ_IF_L_DEC1(i) (_LEN_CART[i-1]-1)
#define ADDR_IF_L_DEC1(l,m) _DOWN1[_CUM_LEN_CART[l-1]+m]
#define ADDR_IF_L_DEC2(l,m) _DOWN2[_CUM_LEN_CART[l-1]+m]
#define DEC1_XYZ(l,m) _DOWN_XYZ[_CUM_LEN_CART[l-1]+m]
#define DEC1_XYZ_ORDER(l,m) _DOWN_XYZ_ORDER[_CUM_LEN_CART[l-1]+m]
static int vrr1d_withGv(double complex *g, double *rijri, double aij,
double *Gv, int topl, size_t NGv)
{
int cumxyz = 1;
if (topl == 0) {
return cumxyz;
}
double *kx = Gv;
double *ky = kx + NGv;
double *kz = ky + NGv;
int i, n, m, l;
double a2;
double complex *p0, *p1, *p2, *dec1, *dec2;
double *ka2 = malloc(sizeof(double) * NGv*3);
double *kxa2 = ka2;
double *kya2 = kxa2 + NGv;
double *kza2 = kya2 + NGv;
a2 = .5 / aij;
for (n = 0; n < NGv; n++) {
kxa2[n] = kx[n] * a2;
kya2[n] = ky[n] * a2;
kza2[n] = kz[n] * a2;
}
p0 = g + NGv;
for (n = 0; n < NGv; n++) {
p0[ n] = (rijri[0] - kxa2[n]*_Complex_I) * g[n];
p0[NGv +n] = (rijri[1] - kya2[n]*_Complex_I) * g[n];
p0[NGv*2+n] = (rijri[2] - kza2[n]*_Complex_I) * g[n];
}
cumxyz += 3;
for (l = 1; l < topl; l++) {
p0 = g + cumxyz * NGv;
dec1 = p0 - _LEN_CART[l ] * NGv;
dec2 = dec1 - _LEN_CART[l-1] * NGv;
for (i = 0; i < _LEN_CART[l+1]; i++) {
m = DEC1_XYZ(l+1,i);
kxa2 = ka2 + m * NGv;
p1 = dec1 + ADDR_IF_L_DEC1(l+1,i) * NGv;
p2 = dec2 + ADDR_IF_L_DEC2(l+1,i) * NGv;
if (ADDR_IF_L_DEC2(l+1,i) < 0) {
for (n = 0; n < NGv; n++) {
p0[n] = (rijri[m]-kxa2[n]*_Complex_I)*p1[n];
}
} else {
a2 = .5/aij * DEC1_XYZ_ORDER(l+1,i);
for (n = 0; n < NGv; n++) {
p0[n] = a2*p2[n] + (rijri[m]-kxa2[n]*_Complex_I)*p1[n];
}
}
p0 += NGv;
}
cumxyz += _LEN_CART[l+1];
}
free(ka2);
return cumxyz;
}
/*
* if li = 3, lj = 1
* (10 + X*00 -> 01):
* gs + X*fs -> fp
*/
static void vrr2d_ket_inc1_withGv(double complex *out, const double complex *g,
double *rirj, int li, int lj, size_t NGv)
{
if (lj == 0) {
NPzcopy(out, g, _LEN_CART[li]*NGv);
return;
}
const int row_10 = _LEN_CART[li+1];
const int row_00 = _LEN_CART[li ];
const int col_00 = _LEN_CART[lj-1];
const double complex *g00 = g;
const double complex *g10 = g + row_00*col_00*NGv;
int i, j, n;
const double complex *p00, *p10;
double complex *p01 = out;
for (j = STARTX_IF_L_DEC1(lj); j < _LEN_CART[lj-1]; j++) {
for (i = 0; i < row_00; i++) {
p00 = g00 + (j*row_00+i) * NGv;
p10 = g10 + (j*row_10+WHEREX_IF_L_INC1(i)) * NGv;
for (n = 0; n < NGv; n++) {
p01[n] = p10[n] + rirj[0] * p00[n];
}
p01 += NGv;
} }
for (j = STARTY_IF_L_DEC1(lj); j < _LEN_CART[lj-1]; j++) {
for (i = 0; i < row_00; i++) {
p00 = g00 + (j*row_00+i) * NGv;
p10 = g10 + (j*row_10+WHEREY_IF_L_INC1(i)) * NGv;
for (n = 0; n < NGv; n++) {
p01[n] = p10[n] + rirj[1] * p00[n];
}
p01 += NGv;
} }
j = STARTZ_IF_L_DEC1(lj);
if (j < _LEN_CART[lj-1]) {
for (i = 0; i < row_00; i++) {
p00 = g00 + (j*row_00+i) * NGv;
p10 = g10 + (j*row_10+WHEREZ_IF_L_INC1(i)) * NGv;
for (n = 0; n < NGv; n++) {
p01[n] = p10[n] + rirj[2] * p00[n];
}
p01 += NGv;
} }
}
/*
* transpose i, j when storing into out
*/
static void vrr2d_inc1_swapij(double complex *out, const double complex *g,
double *rirj, int li, int lj, size_t NGv)
{
if (lj == 0) {
NPzcopy(out, g, _LEN_CART[li]*NGv);
return;
}
const int row_01 = _LEN_CART[lj];
const int row_10 = _LEN_CART[li+1];
const int row_00 = _LEN_CART[li ];
const int col_00 = _LEN_CART[lj-1];
const double complex *g00 = g;
const double complex *g10 = g + row_00*col_00*NGv;
int i, j, n;
const double complex *p00, *p10;
double complex *p01 = out;
for (j = STARTX_IF_L_DEC1(lj); j < _LEN_CART[lj-1]; j++) {
for (i = 0; i < row_00; i++) {
p00 = g00 + (j*row_00+i) * NGv;
p10 = g10 + (j*row_10+WHEREX_IF_L_INC1(i)) * NGv;
p01 = out + i*row_01 * NGv;
for (n = 0; n < NGv; n++) {
p01[n] = p10[n] + rirj[0] * p00[n];
}
}
out += NGv;
}
for (j = STARTY_IF_L_DEC1(lj); j < _LEN_CART[lj-1]; j++) {
for (i = 0; i < row_00; i++) {
p00 = g00 + (j*row_00+i) * NGv;
p10 = g10 + (j*row_10+WHEREY_IF_L_INC1(i)) * NGv;
p01 = out + i*row_01 * NGv;
for (n = 0; n < NGv; n++) {
p01[n] = p10[n] + rirj[1] * p00[n];
}
}
out += NGv;
}
j = STARTZ_IF_L_DEC1(lj);
if (j < _LEN_CART[lj-1]) {
for (i = 0; i < row_00; i++) {
p00 = g00 + (j*row_00+i) * NGv;
p10 = g10 + (j*row_10+WHEREZ_IF_L_INC1(i)) * NGv;
p01 = out + i*row_01 * NGv;
for (n = 0; n < NGv; n++) {
p01[n] = p10[n] + rirj[2] * p00[n];
}
}
}
}
static void vrr2d_withGv(double complex *out, double complex *g,
double complex *gbuf2, const int li, const int lj,
const double *ri, const double *rj, size_t NGv)
{
const int nmax = li + lj;
double complex *g00, *g01, *gswap, *pg00, *pg01;
int row_01, col_01, row_00, col_00;
int i, j;
double rirj[3];
rirj[0] = ri[0] - rj[0];
rirj[1] = ri[1] - rj[1];
rirj[2] = ri[2] - rj[2];
g00 = gbuf2;
g01 = g;
for (j = 1; j < lj; j++) {
gswap = g00;
g00 = g01;
g01 = gswap;
pg00 = g00;
pg01 = g01;
for (i = li; i <= nmax-j; i++) {
vrr2d_ket_inc1_withGv(pg01, pg00, rirj, i, j, NGv);
row_01 = _LEN_CART[i];
col_01 = _LEN_CART[j];
row_00 = _LEN_CART[i ];
col_00 = _LEN_CART[j-1];
pg00 += row_00*col_00 * NGv;
pg01 += row_01*col_01 * NGv;
}
}
vrr2d_ket_inc1_withGv(out, g01, rirj, li, lj, NGv);
}
/* (0,li+lj) => (li,lj) */
static void hrr2d_withGv(double complex *out, double complex *g,
double complex *gbuf2, const int li, const int lj,
const double *ri, const double *rj, size_t NGv)
{
const int nmax = li + lj;
double complex *g00, *g01, *gswap, *pg00, *pg01;
int row_01, col_01, row_00, col_00;
int i, j;
double rjri[3];
rjri[0] = rj[0] - ri[0];
rjri[1] = rj[1] - ri[1];
rjri[2] = rj[2] - ri[2];
g00 = gbuf2;
g01 = g;
for (i = 1; i < li; i++) {
gswap = g00;
g00 = g01;
g01 = gswap;
pg00 = g00;
pg01 = g01;
for (j = lj; j <= nmax-i; j++) {
vrr2d_ket_inc1_withGv(pg01, pg00, rjri, j, i, NGv);
row_01 = _LEN_CART[j];
col_01 = _LEN_CART[i];
row_00 = _LEN_CART[j ];
col_00 = _LEN_CART[i-1];
pg00 += row_00*col_00 * NGv;
pg01 += row_01*col_01 * NGv;
}
}
vrr2d_inc1_swapij(out, g01, rjri, lj, li, NGv);
}
/*
* Recursive relation
*/
static void aopair_rr_igtj_early(double complex *g, double ai, double aj,
CINTEnvVars *envs, FPtr_eval_gz eval_gz,
double complex fac, double *Gv, double *b,
int *gxyz, int *gs, size_t NGv, double *cache)
{
const int topl = envs->li_ceil + envs->lj_ceil;
const double aij = ai + aj;
const double *ri = envs->ri;
const double *rj = envs->rj;
double rij[3], rijri[3];
rij[0] = (ai * ri[0] + aj * rj[0]) / aij;
rij[1] = (ai * ri[1] + aj * rj[1]) / aij;
rij[2] = (ai * ri[2] + aj * rj[2]) / aij;
rijri[0] = rij[0] - ri[0];
rijri[1] = rij[1] - ri[1];
rijri[2] = rij[2] - ri[2];
(*eval_gz)(g, aij, rij, fac, Gv, b, gxyz, gs, NGv, cache);
vrr1d_withGv(g, rijri, aij, Gv, topl, NGv);
}
static void aopair_rr_iltj_early(double complex *g, double ai, double aj,
CINTEnvVars *envs, FPtr_eval_gz eval_gz,
double complex fac, double *Gv, double *b,
int *gxyz, int *gs, size_t NGv, double *cache)
{
const int topl = envs->li_ceil + envs->lj_ceil;
const double aij = ai + aj;
const double *ri = envs->ri;
const double *rj = envs->rj;
double rij[3], rijrj[3];
rij[0] = (ai * ri[0] + aj * rj[0]) / aij;
rij[1] = (ai * ri[1] + aj * rj[1]) / aij;
rij[2] = (ai * ri[2] + aj * rj[2]) / aij;
rijrj[0] = rij[0] - rj[0];
rijrj[1] = rij[1] - rj[1];
rijrj[2] = rij[2] - rj[2];
(*eval_gz)(g, aij, rij, fac, Gv, b, gxyz, gs, NGv, cache);
vrr1d_withGv(g, rijrj, aij, Gv, topl, NGv);
}
static void aopair_rr_igtj_lazy(double complex *g, double ai, double aj,
CINTEnvVars *envs, FPtr_eval_gz eval_gz,
double complex fac, double *Gv, double *b,
int *gxyz, int *gs, size_t NGv, double *cache)
{
const int nmax = envs->li_ceil + envs->lj_ceil;
const int lj = envs->lj_ceil;
const int dj = envs->g_stride_j;
const double aij = ai + aj;
const double a2 = .5 / aij;
const double *ri = envs->ri;
const double *rj = envs->rj;
double rij[3], rirj[3], rijri[3];
double complex *gx = g;
double complex *gy = gx + envs->g_size * NGv;
double complex *gz = gy + envs->g_size * NGv;
double *kx = Gv;
double *ky = kx + NGv;
double *kz = ky + NGv;
size_t off0, off1, off2;
int i, j, n, ptr;
double ia2;
rirj[0] = ri[0] - rj[0];
rirj[1] = ri[1] - rj[1];
rirj[2] = ri[2] - rj[2];
rij[0] = (ai * ri[0] + aj * rj[0]) / aij;
rij[1] = (ai * ri[1] + aj * rj[1]) / aij;
rij[2] = (ai * ri[2] + aj * rj[2]) / aij;
rijri[0] = rij[0] - ri[0];
rijri[1] = rij[1] - ri[1];
rijri[2] = rij[2] - ri[2];
for (n = 0; n < NGv; n++) {
gx[n] = 1;
gy[n] = 1;
}
(*eval_gz)(gz, aij, rij, fac, Gv, b, gxyz, gs, NGv, cache);
if (nmax > 0) {
for (n = 0; n < NGv; n++) {
if (gz[n] != 0) {
gx[NGv+n] = (rijri[0] - kx[n]*a2*_Complex_I) * gx[n];
gy[NGv+n] = (rijri[1] - ky[n]*a2*_Complex_I) * gy[n];
gz[NGv+n] = (rijri[2] - kz[n]*a2*_Complex_I) * gz[n];
}
}
}
for (i = 1; i < nmax; i++) {
off0 = (i-1) * NGv;
off1 = i * NGv;
off2 = (i+1) * NGv;
ia2 = i * a2;
for (n = 0; n < NGv; n++) {
if (gz[n] != 0) {
gx[off2+n] = ia2 * gx[off0+n] + (rijri[0] - kx[n]*a2*_Complex_I) * gx[off1+n];
gy[off2+n] = ia2 * gy[off0+n] + (rijri[1] - ky[n]*a2*_Complex_I) * gy[off1+n];
gz[off2+n] = ia2 * gz[off0+n] + (rijri[2] - kz[n]*a2*_Complex_I) * gz[off1+n];
}
}
}
for (j = 1; j <= lj; j++) {
ptr = dj * j;
for (i = ptr; i <= ptr + nmax - j; i++) {
off0 = i * NGv - dj * NGv; // [i, j-1]
off1 = (i+1) * NGv - dj * NGv; // [i+1,j-1]
off2 = i * NGv; // [i, j ]
for (n = 0; n < NGv; n++) {
if (gz[n] != 0) {
gx[off2+n] = gx[off1+n] + rirj[0] * gx[off0+n];
gy[off2+n] = gy[off1+n] + rirj[1] * gy[off0+n];
gz[off2+n] = gz[off1+n] + rirj[2] * gz[off0+n];
}
}
}
}
}
static void aopair_rr_iltj_lazy(double complex *g, double ai, double aj,
CINTEnvVars *envs, FPtr_eval_gz eval_gz,
double complex fac, double *Gv, double *b,
int *gxyz, int *gs, size_t NGv, double *cache)
{
const int nmax = envs->li_ceil + envs->lj_ceil;
const int li = envs->li_ceil;
const int dj = envs->g_stride_j;
const double aij = ai + aj;
const double a2 = .5 / aij;
const double *ri = envs->ri;
const double *rj = envs->rj;
double rij[3], rirj[3], rijrj[3];
double complex *gx = g;
double complex *gy = gx + envs->g_size * NGv;
double complex *gz = gy + envs->g_size * NGv;
double *kx = Gv;
double *ky = kx + NGv;
double *kz = ky + NGv;
size_t off0, off1, off2;
int i, j, n;
double ia2;
rirj[0] = rj[0] - ri[0];
rirj[1] = rj[1] - ri[1];
rirj[2] = rj[2] - ri[2];
rij[0] = (ai * ri[0] + aj * rj[0]) / aij;
rij[1] = (ai * ri[1] + aj * rj[1]) / aij;
rij[2] = (ai * ri[2] + aj * rj[2]) / aij;
rijrj[0] = rij[0] - rj[0];
rijrj[1] = rij[1] - rj[1];
rijrj[2] = rij[2] - rj[2];
for (n = 0; n < NGv; n++) {
gx[n] = 1;
gy[n] = 1;
}
(*eval_gz)(gz, aij, rij, fac, Gv, b, gxyz, gs, NGv, cache);
if (nmax > 0) {
off0 = dj * NGv;
for (n = 0; n < NGv; n++) {
if (gz[n] != 0) {
gx[off0+n] = (rijrj[0] - kx[n]*a2*_Complex_I) * gx[n];
gy[off0+n] = (rijrj[1] - ky[n]*a2*_Complex_I) * gy[n];
gz[off0+n] = (rijrj[2] - kz[n]*a2*_Complex_I) * gz[n];
}
}
}
for (i = 1; i < nmax; i++) {
off0 = (i-1) * dj * NGv;
off1 = i * dj * NGv;
off2 = (i+1) * dj * NGv;
ia2 = i * a2;
for (n = 0; n < NGv; n++) {
if (gz[n] != 0) {
gx[off2+n] = ia2 * gx[off0+n] + (rijrj[0] - kx[n]*a2*_Complex_I) * gx[off1+n];
gy[off2+n] = ia2 * gy[off0+n] + (rijrj[1] - ky[n]*a2*_Complex_I) * gy[off1+n];
gz[off2+n] = ia2 * gz[off0+n] + (rijrj[2] - kz[n]*a2*_Complex_I) * gz[off1+n];
}
}
}
for (i = 1; i <= li; i++) {
for (j = 0; j <= nmax - i; j++) {
off0 = (i-1) * NGv + j * dj * NGv; // [i-1,j ]
off1 = (i-1) * NGv + (j+1) * dj * NGv; // [i-1,j+1]
off2 = i * NGv + j * dj * NGv; // [i ,j ]
for (n = 0; n < NGv; n++) {
if (gz[n] != 0) {
gx[off2+n] = gx[off1+n] + rirj[0] * gx[off0+n];
gy[off2+n] = gy[off1+n] + rirj[1] * gy[off0+n];
gz[off2+n] = gz[off1+n] + rirj[2] * gz[off0+n];
}
}
}
}
}
static void inner_prod(double complex *g, double complex *gout,
int *idx, const CINTEnvVars *envs,
double *Gv, size_t NGv, int empty)
{
int ix, iy, iz, n, k;
double complex *gz = g + envs->g_size * NGv * 2;
if (empty) {
for (n = 0; n < envs->nf; n++) {
ix = idx[n*3+0];
iy = idx[n*3+1];
iz = idx[n*3+2];
for (k = 0; k < NGv; k++) {
if (gz[k] != 0) {
gout[n*NGv+k] = g[ix*NGv+k] * g[iy*NGv+k] * g[iz*NGv+k];
} else {
gout[n*NGv+k] = 0;
}
}
}
} else {
for (n = 0; n < envs->nf; n++) {
ix = idx[n*3+0];
iy = idx[n*3+1];
iz = idx[n*3+2];
for (k = 0; k < NGv; k++) {
if (gz[k] != 0) {
gout[n*NGv+k] += g[ix*NGv+k] * g[iy*NGv+k] * g[iz*NGv+k];
}
}
}
}
}
static void prim_to_ctr(double complex *gc, const size_t nf, double complex *gp,
const int nprim, const int nctr, const double *coeff,
int empty)
{
size_t n, i;
double c;
if (empty) {
for (n = 0; n < nctr; n++) {
c = coeff[nprim*n];
for (i = 0; i < nf; i++) {
gc[i] = gp[i] * c;
}
gc += nf;
}
} else {
for (n = 0; n < nctr; n++) {
c = coeff[nprim*n];
if (c != 0) {
for (i = 0; i < nf; i++) {
gc[i] += gp[i] * c;
}
}
gc += nf;
}
}
}
static void transpose(double complex *out, double complex *in,
int nf, int comp, size_t NGv)
{
size_t n, k, ic;
double complex *pin;
for (ic = 0; ic < comp; ic++) {
for (n = 0; n < nf; n++) {
pin = in + (n*comp+ic) * NGv;
for (k = 0; k < NGv; k++) {
out[n*NGv+k] = pin[k];
}
}
out += nf * NGv;
}
}
static const int _GBUFSIZE[] = {
1, 4, 10, 10, 20, 48, 20, 35, 75, 150, 35, 56, 108, 216, 384,
56, 84, 147, 294, 510, 850, 84, 120, 192, 384, 654, 1090, 1640,
120, 165, 243, 486, 816, 1360, 2040, 3030
};
#define bufsize(i,j) _GBUFSIZE[((i>=j) ? (i*(i+1)/2+j) : (j*(j+1)/2+i))]
int GTO_aopair_early_contract(double complex *out, CINTEnvVars *envs,
FPtr_eval_gz eval_gz, double complex fac,
double *Gv, double *b, int *gxyz, int *gs,
size_t NGv, double *cache)
{
const int *shls = envs->shls;
const int *bas = envs->bas;
const double *env = envs->env;
const int i_sh = shls[0];
const int j_sh = shls[1];
const int i_l = envs->i_l;
const int j_l = envs->j_l;
const int i_ctr = envs->x_ctr[0];
const int j_ctr = envs->x_ctr[1];
const int i_prim = bas(NPRIM_OF, i_sh);
const int j_prim = bas(NPRIM_OF, j_sh);
const int nf = envs->nf;
const double *ri = envs->ri;
const double *rj = envs->rj;
const double *ai = env + bas(PTR_EXP, i_sh);
const double *aj = env + bas(PTR_EXP, j_sh);
const double *ci = env + bas(PTR_COEFF, i_sh);
const double *cj = env + bas(PTR_COEFF, j_sh);
double fac1i, fac1j;
double aij, dij, eij;
int ip, jp, n;
int empty[2] = {1, 1};
int *jempty = empty + 0;
int *iempty = empty + 1;
const size_t len1 = bufsize(i_l,j_l) * NGv;
const size_t leni = len1 * i_ctr;
const size_t lenj = len1 * i_ctr * j_ctr;
double complex *gctrj = malloc(sizeof(double complex)*(lenj+leni+len1));
if (gctrj == NULL) {
fprintf(stderr, "gctrj = malloc(%zu) falied in GTO_aopair_early_contractv\n",
sizeof(double complex) * (lenj + leni + len1));
}
double complex *g = gctrj + lenj;
double complex *gctri, *g1d;
if (j_ctr == 1) {
gctri = gctrj;
iempty = jempty;
} else {
gctri = g;
g += leni;
}
g1d = g;
void (*aopair_rr)();
int offset_g1d;
if (i_l >= j_l) {
aopair_rr = aopair_rr_igtj_early;
offset_g1d = _CUM_LEN_CART[i_l] - _LEN_CART[i_l];
} else {
aopair_rr = aopair_rr_iltj_early;
offset_g1d = _CUM_LEN_CART[j_l] - _LEN_CART[j_l];
}
int len_g1d = _CUM_LEN_CART[i_l+j_l] - offset_g1d;
double rrij = CINTsquare_dist(ri, rj);
double fac1 = SQRTPI * M_PI * CINTcommon_fac_sp(i_l) * CINTcommon_fac_sp(j_l);
*jempty = 1;
for (jp = 0; jp < j_prim; jp++) {
if (j_ctr == 1) {
fac1j = fac1 * cj[jp];
} else {
fac1j = fac1;
*iempty = 1;
}
for (ip = 0; ip < i_prim; ip++) {
aij = ai[ip] + aj[jp];
eij = (ai[ip] * aj[jp] / aij) * rrij;
if (eij > EXP_CUTOFF) {
continue;
}
dij = exp(-eij) / (aij * sqrt(aij));
fac1i = fac1j * dij;
(*aopair_rr)(g, ai[ip], aj[jp], envs, eval_gz,
fac*fac1i, Gv, b, gxyz, gs, NGv, cache);
prim_to_ctr(gctri, len_g1d*NGv, g1d+offset_g1d*NGv,
i_prim, i_ctr, ci+ip, *iempty);
*iempty = 0;
}
if (!*iempty) {
if (j_ctr > 1) {
prim_to_ctr(gctrj, i_ctr*len_g1d*NGv, gctri,
j_prim,j_ctr, cj+jp, *jempty);
}
*jempty = 0;
}
}
if (!*jempty) {
g1d = gctrj;
for (n = 0; n < i_ctr*j_ctr; n++) {
if (i_l >= j_l) {
vrr2d_withGv(out+n*nf*NGv, g1d, gctrj+lenj,
envs->li_ceil, envs->lj_ceil, ri, rj, NGv);
} else {
hrr2d_withGv(out+n*nf*NGv, g1d, gctrj+lenj,
envs->li_ceil, envs->lj_ceil, ri, rj, NGv);
}
g1d += len_g1d * NGv;
}
}
free(gctrj);
return !*jempty;
}
int GTO_aopair_lazy_contract(double complex *gctr, CINTEnvVars *envs,
FPtr_eval_gz eval_gz, double complex fac,
double *Gv, double *b, int *gxyz, int *gs,
size_t NGv, double *cache)
{
const int *shls = envs->shls;
const int *bas = envs->bas;
const double *env = envs->env;
const int i_sh = shls[0];
const int j_sh = shls[1];
const int i_l = envs->i_l;
const int j_l = envs->j_l;
const int i_ctr = envs->x_ctr[0];
const int j_ctr = envs->x_ctr[1];
const int i_prim = bas(NPRIM_OF, i_sh);
const int j_prim = bas(NPRIM_OF, j_sh);
const int n_comp = envs->ncomp_e1 * envs->ncomp_tensor;
const int nf = envs->nf;
const double *ri = envs->ri;
const double *rj = envs->rj;
const double *ai = env + bas(PTR_EXP, i_sh);
const double *aj = env + bas(PTR_EXP, j_sh);
const double *ci = env + bas(PTR_COEFF, i_sh);
const double *cj = env + bas(PTR_COEFF, j_sh);
double fac1i, fac1j;
double aij, dij, eij;
int ip, jp;
int empty[3] = {1, 1, 1};
int *jempty = empty + 0;
int *iempty = empty + 1;
int *gempty = empty + 2;
const size_t len1 = envs->g_size * 3 * (1<<envs->gbits) * NGv;
const size_t leng = nf * n_comp * NGv;
const size_t leni = nf * i_ctr * n_comp * NGv;
size_t lenj = 0;
if (n_comp > 1) {
lenj = nf * i_ctr * j_ctr * n_comp * NGv;
}
double complex *g = malloc(sizeof(double complex) * (len1+leng+leni+lenj));
if (g == NULL) {
fprintf(stderr, "g = malloc(%zu) falied in GTO_aopair_lazy_contract\n",
sizeof(double complex) * (len1 + leng + leni + lenj));
}
double complex *g1 = g + len1;
double complex *gout, *gctri, *gctrj;
if (n_comp == 1) {
gctrj = gctr;
} else {
gctrj = g1;
g1 += lenj;
}
if (j_ctr == 1) {
gctri = gctrj;
iempty = jempty;
} else {
gctri = g1;
g1 += leni;
}
if (i_ctr == 1) {
gout = gctri;
gempty = iempty;
} else {
gout = g1;
}
void (*aopair_rr)();
if (i_l >= j_l) {
aopair_rr = aopair_rr_igtj_lazy;
} else {
aopair_rr = aopair_rr_iltj_lazy;
}
int *idx = malloc(sizeof(int) * nf * 3);
_g2c_index_xyz(idx, envs);
double rrij = CINTsquare_dist(ri, rj);
double fac1 = SQRTPI * M_PI * CINTcommon_fac_sp(i_l) * CINTcommon_fac_sp(j_l);
*jempty = 1;
for (jp = 0; jp < j_prim; jp++) {
envs->aj[0] = aj[jp];
if (j_ctr == 1) {
fac1j = fac1 * cj[jp];
} else {
fac1j = fac1;
*iempty = 1;
}
for (ip = 0; ip < i_prim; ip++) {
envs->ai[0] = ai[ip];
aij = ai[ip] + aj[jp];
eij = (ai[ip] * aj[jp] / aij) * rrij;
if (eij > EXP_CUTOFF) {
continue;
}
dij = exp(-eij) / (aij * sqrt(aij));
if (i_ctr == 1) {
fac1i = fac1j * dij * ci[ip];
} else {
fac1i = fac1j * dij;
}
(*aopair_rr)(g, ai[ip], aj[jp], envs, eval_gz,
fac*fac1i, Gv, b, gxyz, gs, NGv, cache);
(*envs->f_gout)(g, gout, idx, envs, Gv, NGv, *gempty);
if (i_ctr > 1) {
prim_to_ctr(gctri, nf*n_comp*NGv, gout,
i_prim, i_ctr, ci+ip, *iempty);
}
*iempty = 0;
}
if (!*iempty) {
if (j_ctr > 1) {
prim_to_ctr(gctrj, i_ctr*nf*n_comp*NGv, gctri,
j_prim, j_ctr, cj+jp, *jempty);
}
*jempty = 0;
}
}
if (n_comp > 1 && !*jempty) {
transpose(gctr, gctrj, nf*i_ctr*j_ctr, n_comp, NGv);
}
free(g);
free(idx);
return !*jempty;
}
void GTO_Gv_general(double complex *out, double aij, double *rij,
double complex fac, double *Gv, double *b,
int *gxyz, int *gs, size_t NGv, double *cache)
{
double *kx = Gv;
double *ky = kx + NGv;
double *kz = ky + NGv;
const double cutoff = EXP_CUTOFF * aij * 4;
int n;
double kR, kk;
for (n = 0; n < NGv; n++) {
kk = kx[n] * kx[n] + ky[n] * ky[n] + kz[n] * kz[n];
if (kk < cutoff) {
kR = kx[n] * rij[0] + ky[n] * rij[1] + kz[n] * rij[2];
out[n] = exp(-.25*kk/aij) * fac * (cos(kR) - sin(kR)*_Complex_I);
} else {
out[n] = 0;
}
}
}
/*
* Gv = dot(b.T,gxyz) + kpt
* kk = dot(Gv, Gv)
* kr = dot(rij, Gv) = dot(rij,b.T, gxyz) + dot(rij,kpt) = dot(br, gxyz) + dot(rij,kpt)
* out = fac * exp(-.25 * kk / aij) * (cos(kr) - sin(kr) * _Complex_I);
*
* b: the first 9 elements are 2\pi*inv(a^T), then 3 elements for k_{ij},
* followed by 3*NGv floats for Gbase
*/
void GTO_Gv_orth(double complex *out, double aij, double *rij,
double complex fac, double *Gv, double *b,
int *gxyz, int *gs, size_t NGv, double *cache)
{
const int nx = gs[0];
const int ny = gs[1];
const int nz = gs[2];
double br[3]; // dot(rij, b)
br[0] = rij[0] * b[0];
br[1] = rij[1] * b[4];
br[2] = rij[2] * b[8];
double *kpt = b + 9;
double kr[3];
kr[0] = rij[0] * kpt[0];
kr[1] = rij[1] * kpt[1];
kr[2] = rij[2] * kpt[2];
double *Gxbase = b + 12;
double *Gybase = Gxbase + nx;
double *Gzbase = Gybase + ny;
double *kx = Gv;
double *ky = kx + NGv;
double *kz = ky + NGv;
double *kkpool = cache;
double *kkx = kkpool;
double *kky = kkx + nx;
double *kkz = kky + ny;
double complex *zbuf = (double complex *)(kkz + nz);
double complex *csx = zbuf;
double complex *csy = csx + nx;
double complex *csz = csy + ny;
int *gx = gxyz;
int *gy = gx + NGv;
int *gz = gy + NGv;
const double cutoff = EXP_CUTOFF * aij * 4;
int n, ix, iy, iz;
double Gr;
for (n = 0; n < nx+ny+nz; n++) {
kkpool[n] = -1;
}
for (n = 0; n < NGv; n++) {
ix = gx[n];
iy = gy[n];
iz = gz[n];
if (kkx[ix] < 0) {
Gr = Gxbase[ix] * br[0] + kr[0];
kkx[ix] = .25 * kx[n]*kx[n] / aij;
csx[ix] = exp(-kkx[ix]) * (cos(Gr)-sin(Gr)*_Complex_I);
}
if (kky[iy] < 0) {
Gr = Gybase[iy] * br[1] + kr[1];
kky[iy] = .25 * ky[n]*ky[n] / aij;
csy[iy] = exp(-kky[iy]) * (cos(Gr)-sin(Gr)*_Complex_I);
}
if (kkz[iz] < 0) {
Gr = Gzbase[iz] * br[2] + kr[2];
kkz[iz] = .25 * kz[n]*kz[n] / aij;
csz[iz] = fac * exp(-kkz[iz]) * (cos(Gr)-sin(Gr)*_Complex_I);
}
if (kkx[ix] + kky[iy] + kkz[iz] < cutoff) {
out[n] = csx[ix] * csy[iy] * csz[iz];
} else {
out[n] = 0;
}
}
}
void GTO_Gv_nonorth(double complex *out, double aij, double *rij,
double complex fac, double *Gv, double *b,
int *gxyz, int *gs, size_t NGv, double *cache)
{
const int nx = gs[0];
const int ny = gs[1];
const int nz = gs[2];
double br[3]; // dot(rij, b)
br[0] = rij[0] * b[0];
br[0] += rij[1] * b[1];
br[0] += rij[2] * b[2];
br[1] = rij[0] * b[3];
br[1] += rij[1] * b[4];
br[1] += rij[2] * b[5];
br[2] = rij[0] * b[6];
br[2] += rij[1] * b[7];
br[2] += rij[2] * b[8];
double *kpt = b + 9;
double kr[3];
kr[0] = rij[0] * kpt[0];
kr[1] = rij[1] * kpt[1];
kr[2] = rij[2] * kpt[2];
double *Gxbase = b + 12;
double *Gybase = Gxbase + nx;
double *Gzbase = Gybase + ny;
double *kx = Gv;
double *ky = kx + NGv;
double *kz = ky + NGv;
double complex *zbuf = (double complex *)cache;
double complex *csx = zbuf;
double complex *csy = csx + nx;
double complex *csz = csy + ny;
int n;
char *empty = (char *)(csz + nz);
char *xempty = empty;
char *yempty = xempty + nx;
char *zempty = yempty + ny;
for (n = 0; n < nx+ny+nz; n++) {
empty[n] = 1;
}
int *gx = gxyz;
int *gy = gx + NGv;
int *gz = gy + NGv;
const double cutoff = EXP_CUTOFF * aij * 4;
int ix, iy, iz;
double Gr, kk;
for (n = 0; n < NGv; n++) {
ix = gx[n];
iy = gy[n];
iz = gz[n];
kk = kx[n] * kx[n] + ky[n] * ky[n] + kz[n] * kz[n];
if (kk < cutoff) {
ix = gx[n];
iy = gy[n];
iz = gz[n];
if (xempty[ix]) {
Gr = Gxbase[ix] * br[0] + kr[0];
csx[ix] = cos(Gr)-sin(Gr)*_Complex_I;
xempty[ix] = 0;
}
if (yempty[iy]) {
Gr = Gybase[iy] * br[1] + kr[1];
csy[iy] = cos(Gr)-sin(Gr)*_Complex_I;
yempty[iy] = 0;
}
if (zempty[iz]) {
Gr = Gzbase[iz] * br[2] + kr[2];
csz[iz] = fac * (cos(Gr)-sin(Gr)*_Complex_I);
zempty[iz] = 0;
}
out[n] = exp(-.25*kk/aij) * csx[ix]*csy[iy]*csz[iz];
} else {
out[n] = 0;
}
}
}
static void zcopy_ij(double complex *out, const double complex *gctr,
const int mi, const int mj, const int ni, const size_t NGv)
{
int i, j, k;
for (j = 0; j < mj; j++) {
for (i = 0; i < mi; i++) {
for (k = 0; k < NGv; k++) {
out[i*NGv+k] = gctr[i*NGv+k];
}
}
out += ni * NGv;
gctr += mi * NGv;
}
}
void GTO_ft_c2s_cart(double complex *out, double complex *gctr,
int *dims, CINTEnvVars *envs, size_t NGv)
{
const int i_ctr = envs->x_ctr[0];
const int j_ctr = envs->x_ctr[1];
const int nfi = envs->nfi;
const int nfj = envs->nfj;
const int ni = nfi*i_ctr;
const int nj = nfj*j_ctr;
const int nf = envs->nf;
int ic, jc;
double complex *pout;
for (jc = 0; jc < nj; jc += nfj) {
for (ic = 0; ic < ni; ic += nfi) {
pout = out + (dims[0] * jc + ic) * NGv;
zcopy_ij(pout, gctr, nfi, nfj, dims[0], NGv);
gctr += nf * NGv;
} }
}
#define C2S(sph, nket, cart, l) \
(double complex *)CINTc2s_ket_sph((double *)(sph), nket, (double *)(cart), l)
#define OF_CMPLX 2
void GTO_ft_c2s_sph(double complex *out, double complex *gctr,
int *dims, CINTEnvVars *envs, size_t NGv)
{
const int i_l = envs->i_l;
const int j_l = envs->j_l;
const int i_ctr = envs->x_ctr[0];
const int j_ctr = envs->x_ctr[1];
const int di = i_l * 2 + 1;
const int dj = j_l * 2 + 1;
const int ni = di*i_ctr;
const int nj = dj*j_ctr;
const int nfi = envs->nfi;
const int nf = envs->nf;
int ic, jc, k;
const int buflen = nfi*dj;
double complex *buf1 = malloc(sizeof(double complex) * buflen*2 * NGv);
if (buf1 == NULL) {
fprintf(stderr, "buf1 = malloc(%zu) falied in GTO_ft_c2s_sph\n",
sizeof(double complex) * buflen*2 * NGv);
}
double complex *buf2 = buf1 + buflen * NGv;
double complex *pout, *pij, *buf;
for (jc = 0; jc < nj; jc += dj) {
for (ic = 0; ic < ni; ic += di) {
buf = C2S(buf1, nfi*NGv*OF_CMPLX, gctr, j_l);
pij = C2S(buf2, NGv*OF_CMPLX, buf, i_l);
for (k = NGv; k < dj*NGv; k+=NGv) {
pout = C2S(buf2+k*di, NGv*OF_CMPLX, buf+k*nfi, i_l);
}
pout = out + (dims[0] * jc + ic) * NGv;
zcopy_ij(pout, pij, di, dj, dims[0], NGv);
gctr += nf * NGv;
} }
free(buf1);
}
static void _ft_zset0(double complex *out, int *dims, int *counts,
int comp, size_t NGv)
{
double complex *pout;
int i, j, k, ic;
for (ic = 0; ic < comp; ic++) {
for (j = 0; j < counts[1]; j++) {
pout = out + j * dims[0] * NGv;
for (i = 0; i < counts[0]; i++) {
for (k = 0; k < NGv; k++) {
pout[i*NGv+k] = 0;
}
}
}
out += dims[0] * dims[1] * NGv;
}
}
/*************************************************
*
* eval_aopair is one of GTO_aopair_early_contract,
* GTO_aopair_lazy_contract
*
* eval_gz is one of GTO_Gv_general, GTO_Gv_uniform_orth,
* GTO_Gv_uniform_nonorth, GTO_Gv_nonuniform_orth
*
*************************************************/
int GTO_ft_aopair_drv(double complex *out, int *dims,
int (*eval_aopair)(), FPtr_eval_gz eval_gz, void (*f_c2s)(),
double complex fac, double *Gv, double *b, int *gxyz,
int *gs, size_t NGv, CINTEnvVars *envs)
{
const int i_ctr = envs->x_ctr[0];
const int j_ctr = envs->x_ctr[1];
const int n_comp = envs->ncomp_e1 * envs->ncomp_tensor;
const size_t nc = envs->nf * i_ctr * j_ctr * NGv;
double complex *gctr = malloc(sizeof(double complex) * nc * n_comp);
if (gctr == NULL) {
fprintf(stderr, "gctr = malloc(%zu) falied in GTO_ft_aopair_drv\n",
sizeof(double complex) * nc * n_comp);
}
double *cache = malloc(sizeof(double) * (gs[0] + gs[1] + gs[2]) * 3);
if (cache == NULL) {
fprintf(stderr, "cache = malloc(%zu) falied in GTO_ft_aopair_drv\n",
sizeof(double complex) * (gs[0] + gs[1] + gs[2]) * 3);
}
if (eval_gz == NULL) {
eval_gz = GTO_Gv_general;
}
if (eval_gz != GTO_Gv_general) {
assert(gxyz != NULL);
}
if (eval_aopair == NULL) {
const int *shls = envs->shls;
const int *bas = envs->bas;
const int i_sh = shls[0];
const int j_sh = shls[1];
const int i_prim = bas(NPRIM_OF, i_sh);
const int j_prim = bas(NPRIM_OF, j_sh);
if (i_prim*j_prim < i_ctr*j_ctr*3) {
eval_aopair = GTO_aopair_lazy_contract;
} else {
eval_aopair = GTO_aopair_early_contract;
}
}
int has_value = (*eval_aopair)(gctr, envs, eval_gz,
fac, Gv, b, gxyz, gs, NGv, cache);
int counts[4];
if (f_c2s == >O_ft_c2s_sph) {
counts[0] = (envs->i_l*2+1) * i_ctr;
counts[1] = (envs->j_l*2+1) * j_ctr;
} else { // f_c2s == >O_ft_c2s_cart
counts[0] = envs->nfi * i_ctr;
counts[1] = envs->nfj * j_ctr;
}
if (dims == NULL) {
dims = counts;
}
size_t nout = dims[0] * dims[1] * NGv;
int n;
if (has_value) {
for (n = 0; n < n_comp; n++) {
(*f_c2s)(out+nout*n, gctr+nc*n, dims, envs, NGv);
}
} else {
_ft_zset0(out, dims, counts, n_comp, NGv);
}
free(gctr);
free(cache);
return has_value;
}
int GTO_ft_ovlp_cart(double complex *out, int *shls, int *dims,
int (*eval_aopair)(), FPtr_eval_gz eval_gz, double complex fac,
double *Gv, double *b, int *gxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
CINTEnvVars envs;
int ng[] = {0, 0, 0, 0, 0, 1, 0, 1};
GTO_ft_init1e_envs(&envs, ng, shls, atm, natm, bas, nbas, env);
envs.f_gout = &inner_prod;
return GTO_ft_aopair_drv(out, dims, eval_aopair, eval_gz, >O_ft_c2s_cart,
fac, Gv, b, gxyz, gs, nGv, &envs);
}
int GTO_ft_ovlp_sph(double complex *out, int *shls, int *dims,
int (*eval_aopair)(), FPtr_eval_gz eval_gz, double complex fac,
double *Gv, double *b, int *gxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
CINTEnvVars envs;
int ng[] = {0, 0, 0, 0, 0, 1, 0, 1};
GTO_ft_init1e_envs(&envs, ng, shls, atm, natm, bas, nbas, env);
envs.f_gout = &inner_prod;
return GTO_ft_aopair_drv(out, dims, eval_aopair, eval_gz, >O_ft_c2s_sph,
fac, Gv, b, gxyz, gs, nGv, &envs);
}
/*************************************************
*
*************************************************/
static void zcopy_s2_igtj(double complex *out, double complex *in, size_t NGv,
int comp, int nij, int ip, int di, int dj)
{
const size_t ip1 = ip + 1;
int i, j, n, ic;
double complex *pin, *pout;
for (ic = 0; ic < comp; ic++) {
pout = out + ic * nij * NGv;
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
pin = in + NGv * (j*di+i);
for (n = 0; n < NGv; n++) {
pout[j*NGv+n] = pin[n];
}
}
pout += (ip1 + i) * NGv;
}
}
}
static void zcopy_s2_ieqj(double complex *out, double complex *in, size_t NGv,
int comp, int nij, int ip, int di, int dj)
{
const size_t ip1 = ip + 1;
int i, j, n, ic;
double complex *pin, *pout;
for (ic = 0; ic < comp; ic++) {
pout = out + ic * nij * NGv;
for (i = 0; i < di; i++) {
for (j = 0; j <= i; j++) {
pin = in + NGv * (j*di+i);
for (n = 0; n < NGv; n++) {
pout[j*NGv+n] = pin[n];
}
}
pout += (ip1 + i) * NGv;
}
}
}
void GTO_ft_fill_s1(int (*intor)(), int (*eval_aopair)(), FPtr_eval_gz eval_gz,
double complex *mat, int comp, int ish, int jsh,
double complex *buf,
int *shls_slice, int *ao_loc, double complex fac,
double *Gv, double *b, int *gxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
ish += ish0;
jsh += jsh0;
const int nrow = ao_loc[ish1] - ao_loc[ish0];
const int ncol = ao_loc[jsh1] - ao_loc[jsh0];
const size_t off = ao_loc[ish] - ao_loc[ish0] + (ao_loc[jsh] - ao_loc[jsh0]) * nrow;
int shls[2] = {ish, jsh};
int dims[2] = {nrow, ncol};
(*intor)(mat+off*nGv, shls, dims, eval_aopair, eval_gz,
fac, Gv, b, gxyz, gs, nGv, atm, natm, bas, nbas, env);
}
void GTO_ft_fill_s1hermi(int (*intor)(), int (*eval_aopair)(), FPtr_eval_gz eval_gz,
double complex *mat, int comp, int ish, int jsh,
double complex *buf,
int *shls_slice, int *ao_loc, double complex fac,
double *Gv, double *b, int *gxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
ish += ish0;
jsh += jsh0;
const int ip = ao_loc[ish] - ao_loc[ish0];
const int jp = ao_loc[jsh] - ao_loc[jsh0];
if (ip < jp) {
return;
}
const int nrow = ao_loc[ish1] - ao_loc[ish0];
const int ncol = ao_loc[jsh1] - ao_loc[jsh0];
const size_t off = ao_loc[ish] - ao_loc[ish0] + (ao_loc[jsh] - ao_loc[jsh0]) * nrow;
const size_t NGv = nGv;
int shls[2] = {ish, jsh};
int dims[2] = {nrow, ncol};
(*intor)(mat+off*NGv, shls, dims, eval_aopair, eval_gz,
fac, Gv, b, gxyz, gs, nGv, atm, natm, bas, nbas, env);
if (ip != jp && ish0 == jsh0 && ish1 == jsh1) {
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
double complex *in = mat + off * NGv;
double complex *out = mat + (ao_loc[jsh] - ao_loc[jsh0] +
(ao_loc[ish] - ao_loc[ish0]) * nrow) * NGv;
int i, j, n, ic;
double complex *pout, *pin;
for (ic = 0; ic < comp; ic++) {
for (i = 0; i < di; i++) {
for (j = 0; j < dj; j++) {
pin = in + NGv * (j*nrow+i);
pout = out + NGv * (i*nrow+j);
for (n = 0; n < nGv; n++) {
pout[n] = pin[n];
}
}
}
out += nrow * ncol * NGv;
}
}
}
void GTO_ft_fill_s2(int (*intor)(), int (*eval_aopair)(), FPtr_eval_gz eval_gz,
double complex *mat, int comp, int ish, int jsh,
double complex *buf,
int *shls_slice, int *ao_loc, double complex fac,
double *Gv, double *b, int *gxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
ish += ish0;
jsh += jsh0;
const int ip = ao_loc[ish];
const int jp = ao_loc[jsh] - ao_loc[jsh0];
if (ip < jp) {
return;
}
const int di = ao_loc[ish+1] - ao_loc[ish];
const int dj = ao_loc[jsh+1] - ao_loc[jsh];
const int i0 = ao_loc[ish0];
const size_t off0 = i0 * (i0 + 1) / 2;
const size_t off = ip * (ip + 1) / 2 - off0 + jp;
const size_t nij = ao_loc[ish1] * (ao_loc[ish1] + 1) / 2 - off0;
const size_t NGv = nGv;
int shls[2] = {ish, jsh};
int dims[2] = {di, dj};
(*intor)(buf, shls, dims, eval_aopair, eval_gz,
fac, Gv, b, gxyz, gs, nGv, atm, natm, bas, nbas, env);
if (ip != jp) {
zcopy_s2_igtj(mat+off*NGv, buf, NGv, comp, nij, ip, di, dj);
} else {
zcopy_s2_ieqj(mat+off*NGv, buf, NGv, comp, nij, ip, di, dj);
}
}
/*
* Fourier transform AO pairs and add to mat (inplace)
*/
void GTO_ft_fill_drv(int (*intor)(), FPtr_eval_gz eval_gz, void (*fill)(),
double complex *mat, int comp,
int *shls_slice, int *ao_loc, double phase,
double *Gv, double *b, int *gxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
const int ish0 = shls_slice[0];
const int ish1 = shls_slice[1];
const int jsh0 = shls_slice[2];
const int jsh1 = shls_slice[3];
const int nish = ish1 - ish0;
const int njsh = jsh1 - jsh0;
const double complex fac = cos(phase) + sin(phase)*_Complex_I;
int (*eval_aopair)() = NULL;
if (intor != >O_ft_ovlp_cart && intor != >O_ft_ovlp_sph) {
eval_aopair = >O_aopair_lazy_contract;
}
size_t di = GTOmax_shell_dim(ao_loc, shls_slice , 1);
size_t dj = GTOmax_shell_dim(ao_loc, shls_slice+2, 1);
#pragma omp parallel
{
int i, j, ij;
double complex *buf = malloc(sizeof(double complex)
* di*dj*comp*(size_t)nGv);
if (buf == NULL) {
fprintf(stderr, "buf = malloc(%zu) falied in GTO_ft_fill_drv\n",
di*dj*comp*(size_t)nGv);
}
#pragma omp for schedule(dynamic)
for (ij = 0; ij < nish*njsh; ij++) {
i = ij / njsh;
j = ij % njsh;
(*fill)(intor, eval_aopair, eval_gz, mat,
comp, i, j, buf, shls_slice, ao_loc, fac,
Gv, b, gxyz, gs, nGv, atm, natm, bas, nbas, env);
}
free(buf);
}
}
/*
* Given npair of shls in shls_lst, FT their AO pair value and add to
* out (inplace)
*/
void GTO_ft_fill_shls_drv(int (*intor)(), FPtr_eval_gz eval_gz,
double complex *out, int comp,
int npair, int *shls_lst, int *ao_loc, double phase,
double *Gv, double *b, int *gxyz, int *gs, int nGv,
int *atm, int natm, int *bas, int nbas, double *env)
{
int n, di, dj, ish, jsh;
int *ijloc = malloc(sizeof(int) * npair);
ijloc[0] = 0;
for (n = 1; n < npair; n++) {
ish = shls_lst[n*2-2];
jsh = shls_lst[n*2-1];
di = ao_loc[ish+1] - ao_loc[ish];
dj = ao_loc[jsh+1] - ao_loc[jsh];
ijloc[n] = ijloc[n-1] + di*dj;
}
const double complex fac = cos(phase) + sin(phase)*_Complex_I;
const size_t NGv = nGv;
int (*eval_aopair)() = NULL;
if (intor != >O_ft_ovlp_cart && intor != >O_ft_ovlp_sph) {
eval_aopair = >O_aopair_lazy_contract;
}
#pragma omp parallel private(n)
{
int ish, jsh;
int dims[2];
#pragma omp for schedule(dynamic)
for (n = 0; n < npair; n++) {
ish = shls_lst[n*2 ];
jsh = shls_lst[n*2+1];
dims[0] = ao_loc[ish+1] - ao_loc[ish];
dims[1] = ao_loc[jsh+1] - ao_loc[jsh];
(*intor)(out+ijloc[n]*comp*NGv, shls_lst+n*2, dims,
eval_aopair, eval_gz, fac, Gv, b, gxyz, gs, nGv,
atm, natm, bas, nbas, env);
}
}
free(ijloc);
}
/*
* Reversed vrr2d. They are used by numint_uniform_grid.c
*/
void GTOplain_vrr2d_ket_inc1(double *out, const double *g,
double *rirj, int li, int lj)
{
if (lj == 0) {
NPdcopy(out, g, _LEN_CART[li]);
return;
}
const int row_10 = _LEN_CART[li+1];
const int row_00 = _LEN_CART[li ];
const int col_00 = _LEN_CART[lj-1];
const double *g00 = g;
const double *g10 = g + row_00*col_00;
int i, j;
const double *p00, *p10;
double *p01 = out;
for (j = STARTX_IF_L_DEC1(lj); j < _LEN_CART[lj-1]; j++) {
for (i = 0; i < row_00; i++) {
p00 = g00 + (j*row_00+i);
p10 = g10 + (j*row_10+WHEREX_IF_L_INC1(i));
p01[i] = p10[0] + rirj[0] * p00[0];
}
p01 += row_00;
}
for (j = STARTY_IF_L_DEC1(lj); j < _LEN_CART[lj-1]; j++) {
for (i = 0; i < row_00; i++) {
p00 = g00 + (j*row_00+i);
p10 = g10 + (j*row_10+WHEREY_IF_L_INC1(i));
p01[i] = p10[0] + rirj[1] * p00[0];
}
p01 += row_00;
}
j = STARTZ_IF_L_DEC1(lj);
if (j < _LEN_CART[lj-1]) {
for (i = 0; i < row_00; i++) {
p00 = g00 + (j*row_00+i);
p10 = g10 + (j*row_10+WHEREZ_IF_L_INC1(i));
p01[i] = p10[0] + rirj[2] * p00[0];
}
}
}
void GTOreverse_vrr2d_ket_inc1(double *g01, double *g00,
double *rirj, int li, int lj)
{
const int row_10 = _LEN_CART[li+1];
const int row_00 = _LEN_CART[li ];
const int col_00 = _LEN_CART[lj-1];
double *g10 = g00 + row_00*col_00;
double *p00, *p10;
int i, j;
for (j = STARTX_IF_L_DEC1(lj); j < _LEN_CART[lj-1]; j++) {
for (i = 0; i < row_00; i++) {
p00 = g00 + (j*row_00+i);
p10 = g10 + (j*row_10+WHEREX_IF_L_INC1(i));
p10[0] += g01[i];
p00[0] += g01[i] * rirj[0];
}
g01 += row_00;
}
for (j = STARTY_IF_L_DEC1(lj); j < _LEN_CART[lj-1]; j++) {
for (i = 0; i < row_00; i++) {
p00 = g00 + (j*row_00+i);
p10 = g10 + (j*row_10+WHEREY_IF_L_INC1(i));
p10[0] += g01[i];
p00[0] += g01[i] * rirj[1];
}
g01 += row_00;
}
j = STARTZ_IF_L_DEC1(lj);
if (j < _LEN_CART[lj-1]) {
for (i = 0; i < row_00; i++) {
p00 = g00 + (j*row_00+i);
p10 = g10 + (j*row_10+WHEREZ_IF_L_INC1(i));
p10[0] += g01[i];
p00[0] += g01[i] * rirj[2];
}
}
}
|
facedetectcnn.h | /*
By downloading, copying, installing or using the software you agree to this license.
If you do not agree to this license, do not download, install,
copy or use the software.
License Agreement For libfacedetection
(3-clause BSD License)
Copyright (c) 2018-2020, Shiqi Yu, all rights reserved.
shiqi.yu@gmail.com
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 names of the copyright holders nor the names of the 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 copyright holders 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.
*/
#pragma once
#include "facedetection_export.h"
//#define _ENABLE_AVX512 //Please enable it if X64 CPU
//#define _ENABLE_AVX2 //Please enable it if X64 CPU
//#define _ENABLE_NEON //Please enable it if ARM CPU
FACEDETECTION_EXPORT int *facedetect_cnn(
unsigned char *result_buffer, //buffer memory for storing face detection results, !!its size must be 0x20000 Bytes!!
unsigned char *rgb_image_data, int width, int height,
int step); //input image, it must be BGR (three channels) insteed of RGB image!
/*
DO NOT EDIT the following code if you don't really understand it.
*/
#if defined(_ENABLE_AVX512) || defined(_ENABLE_AVX2)
#include <immintrin.h>
#endif
#if defined(_ENABLE_NEON)
#include "arm_neon.h"
//NEON does not support UINT8*INT8 dot product
//to conver the input data to range [0, 127],
//and then use INT8*INT8 dot product
#define _MAX_UINT8_VALUE 127
#else
#define _MAX_UINT8_VALUE 255
#endif
#if defined(_ENABLE_AVX512)
#define _MALLOC_ALIGN 512
#elif defined(_ENABLE_AVX2)
#define _MALLOC_ALIGN 256
#else
#define _MALLOC_ALIGN 128
#endif
#if defined(_ENABLE_AVX512) && defined(_ENABLE_NEON)
#error Cannot enable the two of AVX512 and NEON at the same time.
#endif
#if defined(_ENABLE_AVX2) && defined(_ENABLE_NEON)
#error Cannot enable the two of AVX and NEON at the same time.
#endif
#if defined(_ENABLE_AVX512) && defined(_ENABLE_AVX2)
#error Cannot enable the two of AVX512 and AVX2 at the same time.
#endif
#if defined(_OPENMP)
#include <omp.h>
#endif
#include <string.h>
#include <vector>
#include <iostream>
#include <typeinfo>
using namespace std;
void *myAlloc(size_t size);
void myFree_(void *ptr);
#define myFree(ptr) (myFree_(*(ptr)), *(ptr)=0);
#ifndef MIN
# define MIN(a, b) ((a) > (b) ? (b) : (a))
#endif
#ifndef MAX
# define MAX(a, b) ((a) < (b) ? (b) : (a))
#endif
typedef struct FaceRect_ {
float score;
int x;
int y;
int w;
int h;
int lm[10];
} FaceRect;
typedef struct ConvInfoStruct_ {
int pad;
int stride;
int kernel_size;
int channels;
int num;
float scale;
signed char *pWeights;
signed int *pBias;
} ConvInfoStruct;
template<class T>
class CDataBlob {
public:
T *data;
int width;
int height;
int channels;
int channelStep;
float scale;
//when the datablob is a filter, the bias is 0 by default
//if it is the filted data, the bias is 1 by default
int bias;
public:
CDataBlob() {
data = 0;
width = 0;
height = 0;
channels = 0;
channelStep = 0;
scale = 1.0f;
bias = 0;
}
CDataBlob(int w, int h, int c) {
data = 0;
create(w, h, c);
}
~CDataBlob() {
setNULL();
}
void setNULL() {
if (data)
myFree(&data);
width = height = channels = channelStep = 0;
scale = 1.0f;
}
bool create(int w, int h, int c) {
setNULL();
width = w;
height = h;
channels = c;
bias = 0;
//alloc space for int8 array
int remBytes = (sizeof(T) * channels) % (_MALLOC_ALIGN / 8);
if (remBytes == 0)
this->channelStep = channels * sizeof(T);
else
this->channelStep = (channels * sizeof(T)) + (_MALLOC_ALIGN / 8) - remBytes;
data = (T *) myAlloc(size_t(width) * height * this->channelStep);
if (data == NULL) {
cerr << "Failed to alloc memeory for uint8 data blob: "
<< width << "*"
<< height << "*"
<< channels << endl;
return false;
}
//memset(data, 0, width * height * channelStep);
//the following code is faster than memset
//but not only the padding bytes are set to zero.
//BE CAREFUL!!!
//#if defined(_OPENMP)
//#pragma omp parallel for
//#endif
for (int r = 0; r < this->height; r++) {
for (int c = 0; c < this->width; c++) {
int pixel_end = this->channelStep / sizeof(T);
T *pI = (this->data +
(size_t(r) * this->width + c) * this->channelStep / sizeof(T));
for (int ch = this->channels; ch < pixel_end; ch++)
pI[ch] = 0;
}
}
return true;
}
bool setInt8FilterData(signed char *pData, int bias, int dataWidth, int dataHeight,
int dataChannels) {
if (pData == NULL) {
cerr << "The input image data is null." << endl;
return false;
}
if (typeid(signed char) != typeid(T)) {
cerr << "Data must be signed char, the same with the source data." << endl;
return false;
}
if (dataWidth != this->width ||
dataHeight != this->height ||
dataChannels != this->channels) {
cerr << "The dimension of the data can not match that of the Blob." << endl;
return false;
}
for (int row = 0; row < height; row++)
for (int col = 0; col < width; col++) {
T *p = (this->data + (size_t(width) * row + col) * channelStep / sizeof(T));
for (int ch = 0; ch < channels; ch++) {
p[ch] = pData[ch * height * width + row * width + col];
}
}
this->bias = bias;
return true;
}
bool
setDataFrom3x3S2P1to1x1S1P0FromImage(const unsigned char *imgData, int imgWidth, int imgHeight,
int imgChannels, int imgWidthStep) {
if (imgData == NULL) {
cerr << "The input image data is null." << endl;
return false;
}
if (typeid(unsigned char) != typeid(T)) {
cerr << "Data must be unsigned char, the same with the source data." << endl;
return false;
}
if (imgChannels != 3) {
cerr << "The input image must be a 3-channel RGB image." << endl;
return false;
}
create((imgWidth + 1) / 2, (imgHeight + 1) / 2, 27);
//since the pixel assignment cannot fill all the elements in the blob.
//some elements in the blob should be initialized to 0
memset(data, 0, size_t(width) * height * channelStep);
#if defined(_OPENMP)
#pragma omp parallel for
#endif
for (int r = 0; r < this->height; r++) {
for (int c = 0; c < this->width; c++) {
T *pData = (unsigned char *) this->data +
(size_t(r) * this->width + c) * this->channelStep;
for (int fy = -1; fy <= 1; fy++) {
int srcy = r * 2 + fy;
if (srcy < 0 || srcy >= imgHeight) //out of the range of the image
continue;
for (int fx = -1; fx <= 1; fx++) {
int srcx = c * 2 + fx;
if (srcx < 0 || srcx >= imgWidth) //out of the range of the image
continue;
const unsigned char *pImgData =
imgData + size_t(imgWidthStep) * srcy + imgChannels * srcx;
int output_channel_offset =
((fy + 1) * 3 + fx + 1) * 3; //3x3 filters, 3-channel image
#if defined(_ENABLE_NEON)
pData[output_channel_offset] = (pImgData[0] / 2);
pData[output_channel_offset + 1] = (pImgData[1] / 2);
pData[output_channel_offset + 2] = (pImgData[2] / 2);
#else
pData[output_channel_offset] = (pImgData[0]);
pData[output_channel_offset + 1] = (pImgData[1]);
pData[output_channel_offset + 2] = (pImgData[2]);
#endif
}
}
}
}
#if defined(_ENABLE_NEON)
this->bias = 1; // 1/2 = 0
this->scale = 0.5f;
#else
this->bias = 1;
this->scale = 1.0f;
#endif
return true;
}
T getElement(int x, int y, int channel) {
if (this->data) {
if (x >= 0 && x < this->width &&
y >= 0 && y < this->height &&
channel >= 0 && channel < this->channels) {
T *p = this->data + (size_t(y) * this->width + x) * this->channelStep / sizeof(T);
return (p[channel]);
}
}
return (T) (0);
}
friend ostream &operator<<(ostream &output, const CDataBlob &dataBlob) {
output << "DataBlob Size (Width, Height, Channel, scale) = ("
<< dataBlob.width
<< ", " << dataBlob.height
<< ", " << dataBlob.channels
<< ", " << dataBlob.scale
<< ", " << dataBlob.bias
<< ")" << endl;
for (int ch = 0; ch < dataBlob.channels; ch++) {
output << "Channel " << ch << ": " << endl;
for (int row = 0; row < dataBlob.height; row++) {
output << "(";
for (int col = 0; col < dataBlob.width; col++) {
T *p = (dataBlob.data +
(dataBlob.width * row + col) * dataBlob.channelStep / sizeof(T));
if (sizeof(T) < 4)
output << (int) (p[ch]);
else
output << p[ch];
if (col != dataBlob.width - 1)
output << ", ";
}
output << ")" << endl;
}
}
return output;
}
};
class Filters {
public:
vector<CDataBlob<signed char> *> filters;
int pad;
int stride;
float scale; //element * scale = original value
Filters() {
pad = 0;
stride = 0;
scale = 0;
}
~Filters() {
for (int i = 0; i < filters.size(); i++) {
delete filters[i];
filters[i] = 0;
}
}
};
bool convertInt2Float(CDataBlob<int> *inputData, CDataBlob<float> *outputData);
bool convolution(CDataBlob<unsigned char> *inputData, const Filters *filters,
CDataBlob<int> *outputData);
bool convolution_relu(CDataBlob<unsigned char> *inputData, const Filters *filters,
CDataBlob<unsigned char> *outputData);
bool
maxpooling2x2S2(const CDataBlob<unsigned char> *inputData, CDataBlob<unsigned char> *outputData);
bool priorbox(const CDataBlob<unsigned char> *featureData, int img_width, int img_height, int step,
int num_sizes, float *pWinSizes, CDataBlob<float> *outputData);
template<typename T>
bool concat4(const CDataBlob<T> *inputData1, const CDataBlob<T> *inputData2,
const CDataBlob<T> *inputData3, const CDataBlob<T> *inputData4,
CDataBlob<T> *outputData);
/* the input data for softmax must be a vector, the data stored in a multi-channel blob with size 1x1 */
template<typename T>
bool blob2vector(const CDataBlob<T> *inputData, CDataBlob<T> *outputData);
bool softmax1vector2class(CDataBlob<float> *inputOutputData);
bool detection_output(const CDataBlob<float> *priorbox, const CDataBlob<float> *loc,
const CDataBlob<float> *conf, float overlap_threshold,
float confidence_threshold, int top_k, int keep_top_k,
CDataBlob<float> *outputData);
vector <FaceRect> objectdetect_cnn(unsigned char *rgbImageData, int with, int height, int step);
|
symm_x_dia_u_lo_col_conj.c | #include "alphasparse/kernel.h"
#include "alphasparse/util.h"
#include "alphasparse/opt.h"
#ifdef _OPENMP
#include <omp.h>
#endif
alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_DIA *mat, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, const ALPHA_Number beta, ALPHA_Number *y, const ALPHA_INT ldy)
{
#ifdef COMPLEX
ALPHA_INT num_threads = alpha_get_thread_num();
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_threads)
#endif
for(ALPHA_INT c = 0; c < columns; c++)
for (ALPHA_INT r = 0; r < mat->rows; r++){
alpha_mul(y[index2(c,r,ldy)],y[index2(c,r,ldy)],beta);
alpha_madde(y[index2(c,r,ldy)],x[index2(c,r,ldx)],alpha);
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_threads)
#endif
for (ALPHA_INT cc = 0; cc < columns; ++cc)
{
ALPHA_Number* Y = &y[index2(cc,0,ldy)];
const ALPHA_Number* X = &x[index2(cc,0,ldx)];
for(ALPHA_INT di = 0; di < mat->ndiag;++di){
ALPHA_INT d = mat->distance[di];
if(d < 0){
ALPHA_INT ars = alpha_max(0,-d);
ALPHA_INT acs = alpha_max(0,d);
ALPHA_INT an = alpha_min(mat->rows - ars,mat->cols - acs);
for(ALPHA_INT i = 0; i < an; ++i){
ALPHA_INT ar = ars + i;
ALPHA_INT ac = acs + i;
ALPHA_Number val;
alpha_mul_2c(val,mat->values[index2(di,ar,mat->lval)],alpha);
alpha_madde(Y[ar],val,X[ac]);
alpha_madde(Y[ac],val,X[ar]);
}
}
}
}
return ALPHA_SPARSE_STATUS_SUCCESS;
#else
return ALPHA_SPARSE_STATUS_INVALID_VALUE;
#endif
}
|
GB_dense_subassign_22_template.c | //------------------------------------------------------------------------------
// GB_dense_subassign_22_template: C += b where C is dense and b is a scalar
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
{
//--------------------------------------------------------------------------
// get C
//--------------------------------------------------------------------------
GB_CTYPE *restrict Cx = (GB_CTYPE *) C->x ;
const int64_t cnz = GB_nnz (C) ;
ASSERT (!C->iso) ;
//--------------------------------------------------------------------------
// C += b where C is dense and b is a scalar
//--------------------------------------------------------------------------
int64_t pC ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (pC = 0 ; pC < cnz ; pC++)
{
GB_BINOP (GB_CX (pC), GB_CX (pC), bwork, 0, 0) ;
}
}
|
threading.c | /*BHEADER**********************************************************************
* See the file COPYRIGHT_and_DISCLAIMER for a complete copyright
* notice, contact person, and disclaimer.
*
* $Revision$
*********************************************************************EHEADER*/
#include <stdlib.h>
#include <stdio.h>
#include "utilities.h"
#if defined(HYPRE_USING_OPENMP) || defined (HYPRE_USING_PGCC_SMP)
int
hypre_NumThreads( )
{
int num_threads;
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel
num_threads = omp_get_num_threads();
#endif
#ifdef HYPRE_USING_PGCC_SMP
num_threads = 2;
#endif
return num_threads;
}
#endif
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
/* The pthreads stuff needs to be reworked */
#define HYPRE_THREAD_GLOBALS
#ifdef HYPRE_USE_PTHREADS
#ifdef HYPRE_USE_UMALLOC
#include "umalloc_local.h"
#endif
int iteration_counter = 0;
volatile int hypre_thread_counter;
volatile int work_continue = 1;
int HYPRE_InitPthreads( int num_threads )
{
int err;
int i;
hypre_qptr =
(hypre_workqueue_t) malloc(sizeof(struct hypre_workqueue_struct));
hypre_NumThreads = num_threads;
initial_thread = pthread_self();
if (hypre_qptr != NULL) {
pthread_mutex_init(&hypre_qptr->lock, NULL);
pthread_cond_init(&hypre_qptr->work_wait, NULL);
pthread_cond_init(&hypre_qptr->finish_wait, NULL);
hypre_qptr->n_working = hypre_qptr->n_waiting = hypre_qptr->n_queue = 0;
hypre_qptr->inp = hypre_qptr->outp = 0;
for (i=0; i < hypre_NumThreads; i++) {
#ifdef HYPRE_USE_UMALLOC
/* Get initial area to start heap */
assert ((_uinitial_block[i] = malloc(INITIAL_HEAP_SIZE))!=NULL);
/* Create a user heap */
assert ((_uparam[i].myheap = _ucreate(initial_block[i],
INITIAL_HEAP_SIZE,
_BLOCK_CLEAN,
_HEAP_REGULAR,
_uget_fn,
_urelease_fn)) != NULL);
#endif
err=pthread_create(&hypre_thread[i], NULL,
(void *(*)(void *))hypre_pthread_worker,
(void *)i);
assert(err == 0);
}
}
pthread_mutex_init(&hypre_mutex_boxloops, NULL);
pthread_mutex_init(&mpi_mtx, NULL);
pthread_mutex_init(&talloc_mtx, NULL);
pthread_mutex_init(&time_mtx, NULL);
pthread_mutex_init(&worker_mtx, NULL);
hypre_thread_counter = 0;
hypre_thread_release = 0;
return (err);
}
void hypre_StopWorker(void *i)
{
work_continue = 0;
}
void HYPRE_DestroyPthreads( void )
{
int i;
void *status;
for (i=0; i < hypre_NumThreads; i++) {
hypre_work_put(hypre_StopWorker, (void *) &i);
}
#ifdef HYPRE_USE_UMALLOC
for (i=0; i<hypre_NumThreads; i++)
{
_udestroy (_uparam[i].myheap, _FORCE);
}
#endif
for (i=0; i<hypre_NumThreads; i++)
pthread_join(hypre_thread[i], &status);
pthread_mutex_destroy(&hypre_qptr->lock);
pthread_mutex_destroy(&hypre_mutex_boxloops);
pthread_mutex_destroy(&mpi_mtx);
pthread_mutex_destroy(&talloc_mtx);
pthread_mutex_destroy(&time_mtx);
pthread_mutex_destroy(&worker_mtx);
pthread_cond_destroy(&hypre_qptr->work_wait);
pthread_cond_destroy(&hypre_qptr->finish_wait);
free (hypre_qptr);
}
void hypre_pthread_worker( int threadid )
{
void *argptr;
hypre_work_proc_t funcptr;
pthread_mutex_lock(&hypre_qptr->lock);
hypre_qptr->n_working++;
while(work_continue) {
while (hypre_qptr->n_queue == 0) {
if (--hypre_qptr->n_working == 0)
pthread_cond_signal(&hypre_qptr->finish_wait);
hypre_qptr->n_waiting++;
pthread_cond_wait(&hypre_qptr->work_wait, &hypre_qptr->lock);
hypre_qptr->n_waiting--;
hypre_qptr->n_working++;
}
hypre_qptr->n_queue--;
funcptr = hypre_qptr->worker_proc_queue[hypre_qptr->outp];
argptr = hypre_qptr->argqueue[hypre_qptr->outp];
hypre_qptr->outp = (hypre_qptr->outp + 1) % MAX_QUEUE;
pthread_mutex_unlock(&hypre_qptr->lock);
(*funcptr)(argptr);
hypre_barrier(&worker_mtx, 0);
if (work_continue)
pthread_mutex_lock(&hypre_qptr->lock);
}
}
void
hypre_work_put( hypre_work_proc_t funcptr, void *argptr )
{
pthread_mutex_lock(&hypre_qptr->lock);
if (hypre_qptr->n_waiting) {
/* idle workers to be awakened */
pthread_cond_signal(&hypre_qptr->work_wait);
}
assert(hypre_qptr->n_queue != MAX_QUEUE);
hypre_qptr->n_queue++;
hypre_qptr->worker_proc_queue[hypre_qptr->inp] = funcptr;
hypre_qptr->argqueue[hypre_qptr->inp] = argptr;
hypre_qptr->inp = (hypre_qptr->inp + 1) % MAX_QUEUE;
pthread_mutex_unlock(&hypre_qptr->lock);
}
/* Wait until all work is done and workers quiesce. */
void
hypre_work_wait( void )
{
pthread_mutex_lock(&hypre_qptr->lock);
while(hypre_qptr->n_queue !=0 || hypre_qptr->n_working != 0)
pthread_cond_wait(&hypre_qptr->finish_wait, &hypre_qptr->lock);
pthread_mutex_unlock(&hypre_qptr->lock);
}
int
hypre_fetch_and_add( int *w )
{
int temp;
temp = *w;
*w += 1;
return temp;
}
int
ifetchadd( int *w, pthread_mutex_t *mutex_fetchadd )
{
int n;
pthread_mutex_lock(mutex_fetchadd);
n = *w;
*w += 1;
pthread_mutex_unlock(mutex_fetchadd);
return n;
}
static volatile int thb_count = 0;
static volatile int thb_release = 0;
void hypre_barrier(pthread_mutex_t *mtx, int unthreaded)
{
if (!unthreaded) {
pthread_mutex_lock(mtx);
thb_count++;
if (thb_count < hypre_NumThreads) {
pthread_mutex_unlock(mtx);
while (!thb_release);
pthread_mutex_lock(mtx);
thb_count--;
pthread_mutex_unlock(mtx);
while (thb_release);
}
else if (thb_count == hypre_NumThreads) {
thb_count--;
pthread_mutex_unlock(mtx);
thb_release++;
while (thb_count);
thb_release = 0;
}
}
}
int
hypre_GetThreadID( void )
{
int i;
if (pthread_equal(pthread_self(), initial_thread))
return hypre_NumThreads;
for (i = 0; i < hypre_NumThreads; i++)
{
if (pthread_equal(pthread_self(), hypre_thread[i]))
return i;
}
return -1;
}
#endif
/*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
|
GB_unop__identity_fp32_int32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__identity_fp32_int32
// op(A') function: GB_unop_tran__identity_fp32_int32
// C type: float
// A type: int32_t
// cast: float cij = (float) aij
// unaryop: cij = aij
#define GB_ATYPE \
int32_t
#define GB_CTYPE \
float
// 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) \
float z = (float) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
float z = (float) aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FP32 || GxB_NO_INT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_fp32_int32
(
float *Cx, // Cx and Ax may be aliased
const int32_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int32_t aij = Ax [p] ;
float z = (float) 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_fp32_int32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
dgemm.c | #include <assert.h>
#include <errno.h>
#include <getopt.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <sched.h>
#ifdef USE_CBLAS
#include "cblas.h"
#elif defined(USE_NVBLAS)
#include "nvblas.h"
#elif defined(USE_MKL)
#include "mkl.h"
#endif
#include "dgemm.h"
static void do_dgemm(
double *matrixA,
double *matrixB,
double *matrixC,
int N,
double alpha,
double beta,
int repeats)
{
int i, j, k, r;
// ------------------------------------------------------- //
// VENDOR NOTIFICATION: START MODIFIABLE REGION
//
// Vendor is able to change the lines below to call optimized
// DGEMM or other matrix multiplication routines. Do *NOT*
// change any lines above this statement.
// ------------------------------------------------------- //
double sum = 0;
// Repeat multiple times
for(r = 0; r < repeats; r++) {
#if defined( USE_MKL ) || defined (USE_CBLAS)
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
N, N, N, alpha, matrixA, N, matrixB, N, beta, matrixC, N);
#elif defined( USE_NVBLAS )
char transA = 'N';
char transB = 'N';
dgemm(&transA, &transB, &N, &N, &N, &alpha, matrixA, &N,
matrixB, &N, &beta, matrixC, &N);
#else
// #pragma omp parallel for private(sum)
for(i = 0; i < N; i++) {
for(j = 0; j < N; j++) {
sum = 0;
for(k = 0; k < N; k++) {
sum += matrixA[i*N + k] * matrixB[k*N + j];
}
matrixC[i*N + j] = (alpha * sum) + (beta * matrixC[i*N + j]);
}
}
#endif
}
// ------------------------------------------------------- //
// VENDOR NOTIFICATION: END MODIFIABLE REGION
// ------------------------------------------------------- //
}
typedef struct {
double *restrict matrixA;
double *restrict matrixB;
double *restrict matrixC;
double alpha;
double beta;
int N;
int repeats;
} dgemm_thread_args_t;
static unsigned N;
static unsigned repeats = 8192;
static void dgemm_init(int argc, char *argv[],
const benchmark_config_t *const config) {
N = tune_size(dgemm_ops.name, config, sizeof(double), 3, 2);
static struct option longopts[] = {
{"dgemm-rounds", required_argument, NULL, 'r'}, {NULL, 0, NULL, 0}};
while (1) {
int c = getopt_long(argc, argv, "-", longopts, NULL);
if (c == -1)
break;
errno = 0;
switch (c) {
case 'r': {
unsigned long tmp = strtoul(optarg, NULL, 0);
if (errno == EINVAL || errno == ERANGE || tmp > INT_MAX) {
fprintf(stderr, "Could not parse --dgemm-rounds argument '%s': %s\n", optarg,
strerror(errno));
}
repeats = (unsigned)tmp;
} break;
case ':':
default:;
}
}
}
static void *init_argument(void *arg_) {
assert(arg_ == NULL);
dgemm_thread_args_t *arg =
(dgemm_thread_args_t *)malloc(sizeof(dgemm_thread_args_t));
arg->N = (int)N;
arg->repeats = (int)repeats;
arg->alpha = 1.0;
arg->beta = 1.0;
arg->matrixA = (double *)malloc(sizeof(double) * N * N);
arg->matrixB = (double *)malloc(sizeof(double) * N * N);
arg->matrixC = (double *)malloc(sizeof(double) * N * N);
for (unsigned j = 0; j < N; j++) {
for (unsigned k = 0; k < N; k++) {
arg->matrixA[j * N + k] = 2.0;
arg->matrixB[j * N + k] = 0.5;
arg->matrixC[j * N + k] = 1.0;
}
}
return arg;
}
static void destroy_argument(void *arg_) {
dgemm_thread_args_t *arg = (dgemm_thread_args_t *)arg_;
free(arg->matrixA);
free(arg->matrixB);
free(arg->matrixC);
free(arg);
}
static void *call_work(void *arg_) {
dgemm_thread_args_t *arg = (dgemm_thread_args_t *)arg_;
do_dgemm(arg->matrixA, arg->matrixB, arg->matrixC, arg->N, arg->alpha,
arg->beta, arg->repeats);
return NULL;
}
benchmark_t dgemm_ops = {
.name = "dgemm",
.init = dgemm_init,
.init_arg = init_argument,
.reset_arg = NULL,
.free_arg = destroy_argument,
.call = call_work,
.state = NULL,
};
#if 0
double init_and_do_dgemm(
char *hostname,
double *matrixA,
double *matrixB,
double *matrixC,
int N,
double alpha,
double beta,
int repeats)
{
int i, j, k, r;
int cpu;
cpu = sched_getcpu();
#pragma omp parallel for
for(i = 0; i < N; i++) {
for(j = 0; j < N; j++) {
matrixA[i*N + j] = 2.0;
matrixB[i*N + j] = 0.5;
matrixC[i*N + j] = 1.0;
}
}
// Do a warm up round
do_dgemm(matrixA, matrixB, matrixC, N, alpha, beta, 1);
printf("Performing multiplication...\n");
const double start = get_seconds();
do_dgemm(matrixA, matrixB, matrixC, N, alpha, beta, repeats);
// ------------------------------------------------------- //
// DO NOT CHANGE CODE BELOW
// ------------------------------------------------------- //
const double end = get_seconds();
// Account for warm up round
++repeats;
printf("Calculating matrix check...\n");
double final_sum = 0;
long long int count = 0;
#pragma omp parallel for reduction(+:final_sum, count)
for(i = 0; i < N; i++) {
for(j = 0; j < N; j++) {
final_sum += matrixC[i*N + j];
count++;
}
}
double N_dbl = (double) N;
double matrix_memory = (3 * N_dbl * N_dbl) * ((double) sizeof(double));
printf("\n");
printf("===============================================================\n");
const double count_dbl = (double) count;
const double scaled_result = (final_sum / (count_dbl * repeats));
printf("Final Sum is: %f\n", scaled_result);
const double check_sum = N_dbl + (1.0 / (double) (repeats));
const double allowed_margin = 1.0e-8;
if( (check_sum >= (scaled_result - allowed_margin)) &&
(check_sum <= (scaled_result + allowed_margin)) ) {
printf(" -> Solution check PASSED successfully.\n");
} else {
printf(" -> Solution check FAILED.\n");
}
printf("Memory for Matrices: %f MB\n",
(matrix_memory / (1024 * 1024)));
const double time_taken = (end - start);
printf("Multiply time: %f seconds\n", time_taken);
const double flops_computed = (N_dbl * N_dbl * N_dbl * 2.0 * (double)(repeats)) +
(N_dbl * N_dbl * 2 * (double)(repeats));
printf("FLOPs computed: %f\n", flops_computed);
double gflopsps = (flops_computed / time_taken) / 1000000000.0;
printf("%s, CPU: %d, GFLOP/s rate: %f GF/s\n",
hostname, cpu, gflopsps);
printf("===============================================================\n");
printf("\n");
return gflopsps;
}
// ------------------------------------------------------- //
// Function: main
//
// Modify only in permitted regions (see comments in the
// function)
// ------------------------------------------------------- //
int main(int argc, char* argv[]) {
// ------------------------------------------------------- //
// DO NOT CHANGE CODE BELOW
// ------------------------------------------------------- //
int N = 256;
int repeats = 30;
double alpha = 1.0;
double beta = 1.0;
char hostname[1024];
char filename[1024];
cpu_set_t cpuset;
int cpu, nr_cpus;
FILE *lf;
int rank;
#if 0
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif
if (gethostname(hostname, sizeof(hostname)) < 0) {
perror("error: obtaining hostname\n");
exit(-1);
}
memset(&cpuset, 0, sizeof(cpuset));
if ((sched_getaffinity(0, sizeof(cpu_set_t), &cpuset)) < 0) {
perror("error: sched_getaffinity");
exit(-1);
}
nr_cpus = 0;
for (cpu = 0; cpu < (8 * sizeof(cpuset)); cpu++) {
if (!CPU_ISSET(cpu, &cpuset)) {
continue;
}
++nr_cpus;
}
sprintf(filename, "%s-rank_%d-nr_cpus_%d.csv", hostname, rank, nr_cpus);
lf = fopen(filename, "wb+");
if (!lf) {
perror("error: fopen");
exit(-1);
}
if(argc > 1) {
N = atoi(argv[1]);
printf("Matrix size input by command line: %d\n", N);
if(argc > 2) {
repeats = atoi(argv[2]);
if(repeats < 30) {
fprintf(stderr, "Error: repeats must be at least 30, setting is: %d\n", repeats);
exit(-1);
}
printf("Repeat multiply %d times.\n", repeats);
if(argc > 3) {
alpha = (double) atof(argv[3]);
if(argc > 4) {
beta = (double) atof(argv[4]);
}
}
} else {
printf("Repeat multiply defaulted to %d\n", repeats);
}
} else {
printf("Matrix size defaulted to %d\n", N);
}
printf("Alpha = %f\n", alpha);
printf("Beta = %f\n", beta);
/*
if(N < 128) {
printf("Error: N (%d) is less than 128, the matrix is too small.\n", N);
exit(-1);
}
*/
printf("Allocating Matrices...\n");
double* DGEMM_RESTRICT matrixA = (double*) malloc(sizeof(double) * N * N);
double* DGEMM_RESTRICT matrixB = (double*) malloc(sizeof(double) * N * N);
double* DGEMM_RESTRICT matrixC = (double*) malloc(sizeof(double) * N * N);
//printf("Allocation complete, populating with values...\n");
for (cpu = 0; cpu < (8 * sizeof(cpuset)); cpu++) {
cpu_set_t target_cpu;
double gflopsps;
int iter;
if (!CPU_ISSET(cpu, &cpuset)) {
continue;
}
memset(&target_cpu, 0, sizeof(cpu_set_t));
CPU_SET(cpu, &target_cpu);
if (sched_setaffinity(0, sizeof(cpu_set_t), &target_cpu) < 0) {
perror("error: sched_setaffinity");
exit(-1);
}
fprintf(lf, "%d", cpu);
for (iter = 0; iter < 5; ++iter) {
gflopsps = init_and_do_dgemm(hostname,
matrixA, matrixB, matrixC, N, alpha, beta, repeats);
}
for (iter = 0; iter < 10; ++iter) {
gflopsps = init_and_do_dgemm(hostname,
matrixA, matrixB, matrixC, N, alpha, beta, repeats);
fprintf(lf, ",%g", gflopsps);
}
fprintf(lf, "\n");
fflush(lf);
fflush(stdout);
}
fclose(lf);
free(matrixA);
free(matrixB);
free(matrixC);
#if 0
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
#endif
return 0;
}
#endif
|
GB_unaryop__ainv_uint64_int16.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__ainv_uint64_int16
// op(A') function: GB_tran__ainv_uint64_int16
// C type: uint64_t
// A type: int16_t
// cast: uint64_t cij = (uint64_t) aij
// unaryop: cij = -aij
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
uint64_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, aij) \
uint64_t z = (uint64_t) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_AINV || GxB_NO_UINT64 || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__ainv_uint64_int16
(
uint64_t *Cx, // Cx and Ax may be aliased
int16_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__ainv_uint64_int16
(
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
|
singleModificadoMaster.c | #include <stdio.h>
#include <omp.h>
main() {
int n = 9, i, a, b[n];
for (i=0; i<n; i++) b[i] = -1;
#pragma omp parallel
{
#pragma omp single
{
printf("Introduce valor de inicialización a: ");
scanf("%d", &a );
printf("Single 1 ejecutada por el thread %d\n", omp_get_thread_num());
}
#pragma omp for
for (i=0; i<n; i++)
b[i] = a;
#pragma omp master
{
printf("Single 2 ejecutada por el thread %d\n", omp_get_thread_num());
printf("Depués de la región parallel:\n");
for (i=0; i<n; i++)
printf("b[%d] = %d\t\n",i,b[i]);
}
}
return 0;
}
|
cache.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC AAA CCCC H H EEEEE %
% C A A C H H E %
% C AAAAA C HHHHH EEE %
% C A A C H H E %
% CCCC A A CCCC H H EEEEE %
% %
% %
% MagickCore Pixel Cache Methods %
% %
% Software Design %
% Cristy %
% July 1999 %
% %
% %
% Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/cache-private.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/composite-private.h"
#include "magick/distribute-cache-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/memory-private.h"
#include "magick/nt-base-private.h"
#include "magick/option.h"
#include "magick/pixel.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/policy.h"
#include "magick/quantum.h"
#include "magick/random_.h"
#include "magick/registry.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/splay-tree.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread-private.h"
#include "magick/timer-private.h"
#include "magick/utility.h"
#include "magick/utility-private.h"
#if defined(MAGICKCORE_ZLIB_DELEGATE)
#include "zlib.h"
#endif
/*
Define declarations.
*/
#define CacheTick(offset,extent) QuantumTick((MagickOffsetType) offset,extent)
#define IsFileDescriptorLimitExceeded() (GetMagickResource(FileResource) > \
GetMagickResourceLimit(FileResource) ? MagickTrue : MagickFalse)
/*
Typedef declarations.
*/
typedef struct _MagickModulo
{
ssize_t
quotient,
remainder;
} MagickModulo;
/*
Forward declarations.
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static Cache
GetImagePixelCache(Image *,const MagickBooleanType,ExceptionInfo *)
magick_hot_spot;
static const IndexPacket
*GetVirtualIndexesFromCache(const Image *);
static const PixelPacket
*GetVirtualPixelCache(const Image *,const VirtualPixelMethod,const ssize_t,
const ssize_t,const size_t,const size_t,ExceptionInfo *),
*GetVirtualPixelsCache(const Image *);
static MagickBooleanType
GetOneAuthenticPixelFromCache(Image *,const ssize_t,const ssize_t,
PixelPacket *,ExceptionInfo *),
GetOneVirtualPixelFromCache(const Image *,const VirtualPixelMethod,
const ssize_t,const ssize_t,PixelPacket *,ExceptionInfo *),
OpenPixelCache(Image *,const MapMode,ExceptionInfo *),
OpenPixelCacheOnDisk(CacheInfo *,const MapMode),
ReadPixelCacheIndexes(CacheInfo *magick_restrict,NexusInfo *magick_restrict,
ExceptionInfo *),
ReadPixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict,
ExceptionInfo *),
SyncAuthenticPixelsCache(Image *,ExceptionInfo *),
WritePixelCacheIndexes(CacheInfo *,NexusInfo *magick_restrict,
ExceptionInfo *),
WritePixelCachePixels(CacheInfo *,NexusInfo *magick_restrict,
ExceptionInfo *);
static PixelPacket
*GetAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t,
const size_t,ExceptionInfo *),
*QueueAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t,
const size_t,ExceptionInfo *),
*SetPixelCacheNexusPixels(const CacheInfo *magick_restrict,const MapMode,
const ssize_t,const ssize_t,const size_t,const size_t,
const MagickBooleanType,NexusInfo *magick_restrict,ExceptionInfo *)
magick_hot_spot;
#if defined(MAGICKCORE_OPENCL_SUPPORT)
static void
CopyOpenCLBuffer(CacheInfo *magick_restrict);
#endif
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
/*
Global declarations.
*/
static SemaphoreInfo
*cache_semaphore = (SemaphoreInfo *) NULL;
static ssize_t
cache_anonymous_memory = (-1);
static time_t
cache_epoch = 0;
#if defined(MAGICKCORE_OPENCL_SUPPORT)
static inline OpenCLCacheInfo *RelinquishOpenCLCacheInfo(MagickCLEnv clEnv,
OpenCLCacheInfo *info)
{
ssize_t
i;
for (i=0; i < (ssize_t) info->event_count; i++)
clEnv->library->clReleaseEvent(info->events[i]);
info->events=(cl_event *) RelinquishMagickMemory(info->events);
DestroySemaphoreInfo(&info->events_semaphore);
if (info->buffer != (cl_mem) NULL)
{
clEnv->library->clReleaseMemObject(info->buffer);
info->buffer=(cl_mem) NULL;
}
return((OpenCLCacheInfo *) RelinquishMagickMemory(info));
}
static void CL_API_CALL RelinquishPixelCachePixelsDelayed(
cl_event magick_unused(event),cl_int magick_unused(event_command_exec_status),
void *user_data)
{
MagickCLEnv
clEnv;
OpenCLCacheInfo
*info;
PixelPacket
*pixels;
ssize_t
i;
magick_unreferenced(event);
magick_unreferenced(event_command_exec_status);
info=(OpenCLCacheInfo *) user_data;
clEnv=GetDefaultOpenCLEnv();
for (i=(ssize_t)info->event_count-1; i >= 0; i--)
{
cl_int
event_status;
cl_uint
status;
status=clEnv->library->clGetEventInfo(info->events[i],
CL_EVENT_COMMAND_EXECUTION_STATUS,sizeof(cl_int),&event_status,NULL);
if ((status == CL_SUCCESS) && (event_status > CL_COMPLETE))
{
clEnv->library->clSetEventCallback(info->events[i],CL_COMPLETE,
&RelinquishPixelCachePixelsDelayed,info);
return;
}
}
pixels=info->pixels;
RelinquishMagickResource(MemoryResource,info->length);
(void) RelinquishOpenCLCacheInfo(clEnv,info);
(void) RelinquishAlignedMemory(pixels);
}
static MagickBooleanType RelinquishOpenCLBuffer(
CacheInfo *magick_restrict cache_info)
{
MagickCLEnv
clEnv;
assert(cache_info != (CacheInfo *) NULL);
if (cache_info->opencl == (OpenCLCacheInfo *) NULL)
return(MagickFalse);
RelinquishPixelCachePixelsDelayed((cl_event) NULL,0,cache_info->opencl);
return(MagickTrue);
}
static cl_event *CopyOpenCLEvents(OpenCLCacheInfo *opencl_info,
cl_uint *event_count)
{
cl_event
*events;
register size_t
i;
assert(opencl_info != (OpenCLCacheInfo *) NULL);
events=(cl_event *) NULL;
LockSemaphoreInfo(opencl_info->events_semaphore);
*event_count=opencl_info->event_count;
if (*event_count > 0)
{
events=AcquireQuantumMemory(*event_count,sizeof(*events));
if (events == (cl_event *) NULL)
*event_count=0;
else
{
for (i=0; i < opencl_info->event_count; i++)
events[i]=opencl_info->events[i];
}
}
UnlockSemaphoreInfo(opencl_info->events_semaphore);
return(events);
}
#endif
#if defined(MAGICKCORE_OPENCL_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A d d O p e n C L E v e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AddOpenCLEvent() adds an event to the list of operations the next operation
% should wait for.
%
% The format of the AddOpenCLEvent() method is:
%
% void AddOpenCLEvent(const Image *image,cl_event event)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o event: the event that should be added.
%
*/
extern MagickPrivate void AddOpenCLEvent(const Image *image,cl_event event)
{
CacheInfo
*magick_restrict cache_info;
MagickCLEnv
clEnv;
assert(image != (const Image *) NULL);
assert(event != (cl_event) NULL);
cache_info=(CacheInfo *)image->cache;
assert(cache_info->opencl != (OpenCLCacheInfo *) NULL);
clEnv=GetDefaultOpenCLEnv();
if (clEnv->library->clRetainEvent(event) != CL_SUCCESS)
{
clEnv->library->clWaitForEvents(1,&event);
return;
}
LockSemaphoreInfo(cache_info->opencl->events_semaphore);
if (cache_info->opencl->events == (cl_event *) NULL)
{
cache_info->opencl->events=AcquireMagickMemory(sizeof(
*cache_info->opencl->events));
cache_info->opencl->event_count=1;
}
else
cache_info->opencl->events=ResizeQuantumMemory(cache_info->opencl->events,
++cache_info->opencl->event_count,sizeof(*cache_info->opencl->events));
if (cache_info->opencl->events == (cl_event *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
cache_info->opencl->events[cache_info->opencl->event_count-1]=event;
UnlockSemaphoreInfo(cache_info->opencl->events_semaphore);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquirePixelCache() acquires a pixel cache.
%
% The format of the AcquirePixelCache() method is:
%
% Cache AcquirePixelCache(const size_t number_threads)
%
% A description of each parameter follows:
%
% o number_threads: the number of nexus threads.
%
*/
MagickExport Cache AcquirePixelCache(const size_t number_threads)
{
CacheInfo
*magick_restrict cache_info;
char
*value;
cache_info=(CacheInfo *) AcquireAlignedMemory(1,sizeof(*cache_info));
if (cache_info == (CacheInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) memset(cache_info,0,sizeof(*cache_info));
cache_info->type=UndefinedCache;
cache_info->mode=IOMode;
cache_info->disk_mode=IOMode;
cache_info->colorspace=sRGBColorspace;
cache_info->channels=4;
cache_info->file=(-1);
cache_info->id=GetMagickThreadId();
cache_info->number_threads=number_threads;
if (GetOpenMPMaximumThreads() > cache_info->number_threads)
cache_info->number_threads=GetOpenMPMaximumThreads();
if (GetMagickResourceLimit(ThreadResource) > cache_info->number_threads)
cache_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
if (cache_info->number_threads == 0)
cache_info->number_threads=1;
cache_info->nexus_info=AcquirePixelCacheNexus(cache_info->number_threads);
value=GetEnvironmentValue("MAGICK_SYNCHRONIZE");
if (value != (const char *) NULL)
{
cache_info->synchronize=IsStringTrue(value);
value=DestroyString(value);
}
value=GetPolicyValue("cache:synchronize");
if (value != (const char *) NULL)
{
cache_info->synchronize=IsStringTrue(value);
value=DestroyString(value);
}
cache_info->width_limit=GetMagickResourceLimit(WidthResource);
cache_info->height_limit=GetMagickResourceLimit(HeightResource);
cache_info->semaphore=AllocateSemaphoreInfo();
cache_info->reference_count=1;
cache_info->file_semaphore=AllocateSemaphoreInfo();
cache_info->debug=IsEventLogging();
cache_info->signature=MagickCoreSignature;
return((Cache ) cache_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquirePixelCacheNexus() allocates the NexusInfo structure.
%
% The format of the AcquirePixelCacheNexus method is:
%
% NexusInfo **AcquirePixelCacheNexus(const size_t number_threads)
%
% A description of each parameter follows:
%
% o number_threads: the number of nexus threads.
%
*/
MagickExport NexusInfo **AcquirePixelCacheNexus(const size_t number_threads)
{
NexusInfo
**magick_restrict nexus_info;
register ssize_t
i;
nexus_info=(NexusInfo **) MagickAssumeAligned(AcquireAlignedMemory(2*
number_threads,sizeof(*nexus_info)));
if (nexus_info == (NexusInfo **) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
*nexus_info=(NexusInfo *) AcquireQuantumMemory(2*number_threads,
sizeof(**nexus_info));
if (*nexus_info == (NexusInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) memset(*nexus_info,0,2*number_threads*sizeof(**nexus_info));
for (i=0; i < (ssize_t) (2*number_threads); i++)
{
nexus_info[i]=(*nexus_info+i);
if (i < (ssize_t) number_threads)
nexus_info[i]->virtual_nexus=(*nexus_info+number_threads+i);
nexus_info[i]->signature=MagickCoreSignature;
}
return(nexus_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e P i x e l C a c h e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquirePixelCachePixels() returns the pixels associated with the specified
% image.
%
% The format of the AcquirePixelCachePixels() method is:
%
% const void *AcquirePixelCachePixels(const Image *image,
% MagickSizeType *length,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o length: the pixel cache length.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport const void *AcquirePixelCachePixels(const Image *image,
MagickSizeType *length,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
(void) exception;
*length=0;
if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache))
return((const void *) NULL);
*length=cache_info->length;
return((const void *) cache_info->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C a c h e C o m p o n e n t G e n e s i s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CacheComponentGenesis() instantiates the cache component.
%
% The format of the CacheComponentGenesis method is:
%
% MagickBooleanType CacheComponentGenesis(void)
%
*/
MagickExport MagickBooleanType CacheComponentGenesis(void)
{
if (cache_semaphore == (SemaphoreInfo *) NULL)
cache_semaphore=AllocateSemaphoreInfo();
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C a c h e C o m p o n e n t T e r m i n u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CacheComponentTerminus() destroys the cache component.
%
% The format of the CacheComponentTerminus() method is:
%
% CacheComponentTerminus(void)
%
*/
MagickExport void CacheComponentTerminus(void)
{
if (cache_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&cache_semaphore);
/* no op-- nothing to destroy */
DestroySemaphoreInfo(&cache_semaphore);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l i p P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClipPixelCacheNexus() clips the cache nexus as defined by the image clip
% mask. The method returns MagickTrue if the pixel region is clipped,
% otherwise MagickFalse.
%
% The format of the ClipPixelCacheNexus() method is:
%
% MagickBooleanType ClipPixelCacheNexus(Image *image,NexusInfo *nexus_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o nexus_info: the cache nexus to clip.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType ClipPixelCacheNexus(Image *image,
NexusInfo *nexus_info,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
MagickOffsetType
n;
NexusInfo
**magick_restrict clip_nexus;
register const PixelPacket
*magick_restrict r;
register IndexPacket
*magick_restrict nexus_indexes,
*magick_restrict indexes;
register PixelPacket
*magick_restrict p,
*magick_restrict q;
ssize_t
y;
/*
Apply clip mask.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->clip_mask == (Image *) NULL) ||
(image->storage_class == PseudoClass))
return(MagickTrue);
if ((nexus_info->region.width == 0) || (nexus_info->region.height == 0))
return(MagickTrue);
cache_info=(CacheInfo *) image->cache;
if (cache_info == (Cache) NULL)
return(MagickFalse);
clip_nexus=AcquirePixelCacheNexus(1);
p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y,
nexus_info->region.width,nexus_info->region.height,
nexus_info->virtual_nexus,exception);
indexes=nexus_info->virtual_nexus->indexes;
q=nexus_info->pixels;
nexus_indexes=nexus_info->indexes;
r=GetVirtualPixelCacheNexus(image->clip_mask,MaskVirtualPixelMethod,
nexus_info->region.x,nexus_info->region.y,nexus_info->region.width,
nexus_info->region.height,clip_nexus[0],exception);
if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL) ||
(r == (const PixelPacket *) NULL))
return(MagickFalse);
n=0;
for (y=0; y < (ssize_t) nexus_info->region.height; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) nexus_info->region.width; x++)
{
double
mask_alpha;
mask_alpha=QuantumScale*GetPixelIntensity(image,r);
if (fabs(mask_alpha) >= MagickEpsilon)
{
SetPixelRed(q,mask_alpha*MagickOver_((MagickRealType) p->red,
(MagickRealType) GetPixelOpacity(p),(MagickRealType) q->red,
(MagickRealType) GetPixelOpacity(q)));
SetPixelGreen(q,mask_alpha*MagickOver_((MagickRealType) p->green,
(MagickRealType) GetPixelOpacity(p),(MagickRealType) q->green,
(MagickRealType) GetPixelOpacity(q)));
SetPixelBlue(q,mask_alpha*MagickOver_((MagickRealType) p->blue,
(MagickRealType) GetPixelOpacity(p),(MagickRealType) q->blue,
(MagickRealType) GetPixelOpacity(q)));
SetPixelOpacity(q,GetPixelOpacity(p));
if (cache_info->active_index_channel != MagickFalse)
SetPixelIndex(nexus_indexes+n,GetPixelIndex(indexes+n));
}
p++;
q++;
r++;
n++;
}
}
clip_nexus=DestroyPixelCacheNexus(clip_nexus,1);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l o n e P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClonePixelCache() clones a pixel cache.
%
% The format of the ClonePixelCache() method is:
%
% Cache ClonePixelCache(const Cache cache)
%
% A description of each parameter follows:
%
% o cache: the pixel cache.
%
*/
MagickExport Cache ClonePixelCache(const Cache cache)
{
CacheInfo
*magick_restrict clone_info;
const CacheInfo
*magick_restrict cache_info;
assert(cache != NULL);
cache_info=(const CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
cache_info->filename);
clone_info=(CacheInfo *) AcquirePixelCache(cache_info->number_threads);
clone_info->virtual_pixel_method=cache_info->virtual_pixel_method;
return((Cache ) clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l o n e P i x e l C a c h e M e t h o d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClonePixelCacheMethods() clones the pixel cache methods from one cache to
% another.
%
% The format of the ClonePixelCacheMethods() method is:
%
% void ClonePixelCacheMethods(Cache clone,const Cache cache)
%
% A description of each parameter follows:
%
% o clone: Specifies a pointer to a Cache structure.
%
% o cache: the pixel cache.
%
*/
MagickExport void ClonePixelCacheMethods(Cache clone,const Cache cache)
{
CacheInfo
*magick_restrict cache_info,
*magick_restrict source_info;
assert(clone != (Cache) NULL);
source_info=(CacheInfo *) clone;
assert(source_info->signature == MagickCoreSignature);
if (source_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
source_info->filename);
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
source_info->methods=cache_info->methods;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l o n e P i x e l C a c h e R e p o s i t o r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %
% ClonePixelCacheRepository() clones the source pixel cache to the destination
% cache.
%
% The format of the ClonePixelCacheRepository() method is:
%
% MagickBooleanType ClonePixelCacheRepository(CacheInfo *cache_info,
% CacheInfo *source_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
% o source_info: the source pixel cache.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType ClonePixelCacheOnDisk(
CacheInfo *magick_restrict cache_info,CacheInfo *magick_restrict clone_info)
{
MagickSizeType
extent;
size_t
quantum;
ssize_t
count;
struct stat
file_stats;
unsigned char
*buffer;
/*
Clone pixel cache on disk with identical morphology.
*/
if ((OpenPixelCacheOnDisk(cache_info,ReadMode) == MagickFalse) ||
(OpenPixelCacheOnDisk(clone_info,IOMode) == MagickFalse))
return(MagickFalse);
if ((lseek(cache_info->file,0,SEEK_SET) < 0) ||
(lseek(clone_info->file,0,SEEK_SET) < 0))
return(MagickFalse);
quantum=(size_t) MagickMaxBufferExtent;
if ((fstat(cache_info->file,&file_stats) == 0) && (file_stats.st_size > 0))
{
#if defined(MAGICKCORE_HAVE_LINUX_SENDFILE)
if (cache_info->length < 0x7ffff000)
{
count=sendfile(clone_info->file,cache_info->file,(off_t *) NULL,
(ssize_t) cache_info->length);
if (count == (ssize_t) cache_info->length)
return(MagickTrue);
if ((lseek(cache_info->file,0,SEEK_SET) < 0) ||
(lseek(clone_info->file,0,SEEK_SET) < 0))
return(MagickFalse);
}
#endif
quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent);
}
buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
extent=0;
while ((count=read(cache_info->file,buffer,quantum)) > 0)
{
ssize_t
number_bytes;
number_bytes=write(clone_info->file,buffer,(size_t) count);
if (number_bytes != count)
break;
extent+=number_bytes;
}
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
if (extent != cache_info->length)
return(MagickFalse);
return(MagickTrue);
}
static MagickBooleanType ClonePixelCacheRepository(
CacheInfo *magick_restrict clone_info,CacheInfo *magick_restrict cache_info,
ExceptionInfo *exception)
{
#define MaxCacheThreads ((size_t) GetMagickResourceLimit(ThreadResource))
#define cache_number_threads(source,destination,chunk,multithreaded) \
num_threads((multithreaded) == 0 ? 1 : \
(((source)->type != MemoryCache) && ((source)->type != MapCache)) || \
(((destination)->type != MemoryCache) && ((destination)->type != MapCache)) ? \
MagickMax(MagickMin(GetMagickResourceLimit(ThreadResource),2),1) : \
MagickMax(MagickMin((ssize_t) GetMagickResourceLimit(ThreadResource),(ssize_t) (chunk)/256),1))
MagickBooleanType
status;
NexusInfo
**magick_restrict cache_nexus,
**magick_restrict clone_nexus;
size_t
length;
ssize_t
y;
assert(cache_info != (CacheInfo *) NULL);
assert(clone_info != (CacheInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
if (cache_info->type == PingCache)
return(MagickTrue);
if ((cache_info->storage_class == clone_info->storage_class) &&
(cache_info->colorspace == clone_info->colorspace) &&
(cache_info->channels == clone_info->channels) &&
(cache_info->columns == clone_info->columns) &&
(cache_info->rows == clone_info->rows) &&
(cache_info->active_index_channel == clone_info->active_index_channel))
{
/*
Identical pixel cache morphology.
*/
if (((cache_info->type == MemoryCache) ||
(cache_info->type == MapCache)) &&
((clone_info->type == MemoryCache) ||
(clone_info->type == MapCache)))
{
(void) memcpy(clone_info->pixels,cache_info->pixels,
cache_info->columns*cache_info->rows*sizeof(*cache_info->pixels));
if ((cache_info->active_index_channel != MagickFalse) &&
(clone_info->active_index_channel != MagickFalse))
(void) memcpy(clone_info->indexes,cache_info->indexes,
cache_info->columns*cache_info->rows*
sizeof(*cache_info->indexes));
return(MagickTrue);
}
if ((cache_info->type == DiskCache) && (clone_info->type == DiskCache))
return(ClonePixelCacheOnDisk(cache_info,clone_info));
}
/*
Mismatched pixel cache morphology.
*/
cache_nexus=AcquirePixelCacheNexus(cache_info->number_threads);
clone_nexus=AcquirePixelCacheNexus(clone_info->number_threads);
length=(size_t) MagickMin(cache_info->columns,clone_info->columns)*
sizeof(*cache_info->pixels);
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
cache_number_threads(cache_info,clone_info,cache_info->rows,1)
#endif
for (y=0; y < (ssize_t) cache_info->rows; y++)
{
const int
id = GetOpenMPThreadId();
PixelPacket
*pixels;
if (status == MagickFalse)
continue;
if (y >= (ssize_t) clone_info->rows)
continue;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,0,y,
cache_info->columns,1,MagickFalse,cache_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception);
if (status == MagickFalse)
continue;
pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,0,y,
clone_info->columns,1,MagickFalse,clone_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
(void) memset(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length);
(void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length);
status=WritePixelCachePixels(clone_info,clone_nexus[id],exception);
}
if ((cache_info->active_index_channel != MagickFalse) &&
(clone_info->active_index_channel != MagickFalse))
{
/*
Clone indexes.
*/
length=(size_t) MagickMin(cache_info->columns,clone_info->columns)*
sizeof(*cache_info->indexes);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
cache_number_threads(cache_info,clone_info,cache_info->rows,1)
#endif
for (y=0; y < (ssize_t) cache_info->rows; y++)
{
const int
id = GetOpenMPThreadId();
PixelPacket
*pixels;
if (status == MagickFalse)
continue;
if (y >= (ssize_t) clone_info->rows)
continue;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,0,y,
cache_info->columns,1,MagickFalse,cache_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
status=ReadPixelCacheIndexes(cache_info,cache_nexus[id],exception);
if (status == MagickFalse)
continue;
pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,0,y,
clone_info->columns,1,MagickFalse,clone_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
(void) memcpy(clone_nexus[id]->indexes,cache_nexus[id]->indexes,length);
status=WritePixelCacheIndexes(clone_info,clone_nexus[id],exception);
}
}
clone_nexus=DestroyPixelCacheNexus(clone_nexus,clone_info->number_threads);
cache_nexus=DestroyPixelCacheNexus(cache_nexus,cache_info->number_threads);
if (cache_info->debug != MagickFalse)
{
char
message[MaxTextExtent];
(void) FormatLocaleString(message,MaxTextExtent,"%s => %s",
CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type),
CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type));
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y I m a g e P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImagePixelCache() deallocates memory associated with the pixel cache.
%
% The format of the DestroyImagePixelCache() method is:
%
% void DestroyImagePixelCache(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static void DestroyImagePixelCache(Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->cache != (void *) NULL)
image->cache=DestroyPixelCache(image->cache);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y I m a g e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImagePixels() deallocates memory associated with the pixel cache.
%
% The format of the DestroyImagePixels() method is:
%
% void DestroyImagePixels(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DestroyImagePixels(Image *image)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL)
{
cache_info->methods.destroy_pixel_handler(image);
return;
}
image->cache=DestroyPixelCache(image->cache);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyPixelCache() deallocates memory associated with the pixel cache.
%
% The format of the DestroyPixelCache() method is:
%
% Cache DestroyPixelCache(Cache cache)
%
% A description of each parameter follows:
%
% o cache: the pixel cache.
%
*/
static MagickBooleanType ClosePixelCacheOnDisk(CacheInfo *cache_info)
{
int
status;
status=(-1);
if (cache_info->file != -1)
{
status=close(cache_info->file);
cache_info->file=(-1);
RelinquishMagickResource(FileResource,1);
}
return(status == -1 ? MagickFalse : MagickTrue);
}
static inline void RelinquishPixelCachePixels(CacheInfo *cache_info)
{
switch (cache_info->type)
{
case MemoryCache:
{
#if defined(MAGICKCORE_OPENCL_SUPPORT)
if (RelinquishOpenCLBuffer(cache_info) != MagickFalse)
{
cache_info->pixels=(PixelPacket *) NULL;
break;
}
#endif
if (cache_info->mapped == MagickFalse)
cache_info->pixels=(PixelPacket *) RelinquishAlignedMemory(
cache_info->pixels);
else
(void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length);
RelinquishMagickResource(MemoryResource,cache_info->length);
break;
}
case MapCache:
{
(void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length);
cache_info->pixels=(PixelPacket *) NULL;
if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode))
(void) RelinquishUniqueFileResource(cache_info->cache_filename);
*cache_info->cache_filename='\0';
RelinquishMagickResource(MapResource,cache_info->length);
}
case DiskCache:
{
if (cache_info->file != -1)
(void) ClosePixelCacheOnDisk(cache_info);
if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode))
(void) RelinquishUniqueFileResource(cache_info->cache_filename);
*cache_info->cache_filename='\0';
RelinquishMagickResource(DiskResource,cache_info->length);
break;
}
case DistributedCache:
{
*cache_info->cache_filename='\0';
(void) RelinquishDistributePixelCache((DistributeCacheInfo *)
cache_info->server_info);
break;
}
default:
break;
}
cache_info->type=UndefinedCache;
cache_info->mapped=MagickFalse;
cache_info->indexes=(IndexPacket *) NULL;
}
MagickExport Cache DestroyPixelCache(Cache cache)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
cache_info->filename);
LockSemaphoreInfo(cache_info->semaphore);
cache_info->reference_count--;
if (cache_info->reference_count != 0)
{
UnlockSemaphoreInfo(cache_info->semaphore);
return((Cache) NULL);
}
UnlockSemaphoreInfo(cache_info->semaphore);
if (cache_info->debug != MagickFalse)
{
char
message[MaxTextExtent];
(void) FormatLocaleString(message,MaxTextExtent,"destroy %s",
cache_info->filename);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
RelinquishPixelCachePixels(cache_info);
if (cache_info->server_info != (DistributeCacheInfo *) NULL)
cache_info->server_info=DestroyDistributeCacheInfo((DistributeCacheInfo *)
cache_info->server_info);
if (cache_info->nexus_info != (NexusInfo **) NULL)
cache_info->nexus_info=DestroyPixelCacheNexus(cache_info->nexus_info,
cache_info->number_threads);
if (cache_info->random_info != (RandomInfo *) NULL)
cache_info->random_info=DestroyRandomInfo(cache_info->random_info);
if (cache_info->file_semaphore != (SemaphoreInfo *) NULL)
DestroySemaphoreInfo(&cache_info->file_semaphore);
if (cache_info->semaphore != (SemaphoreInfo *) NULL)
DestroySemaphoreInfo(&cache_info->semaphore);
cache_info->signature=(~MagickCoreSignature);
cache_info=(CacheInfo *) RelinquishAlignedMemory(cache_info);
cache=(Cache) NULL;
return(cache);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyPixelCacheNexus() destroys a pixel cache nexus.
%
% The format of the DestroyPixelCacheNexus() method is:
%
% NexusInfo **DestroyPixelCacheNexus(NexusInfo *nexus_info,
% const size_t number_threads)
%
% A description of each parameter follows:
%
% o nexus_info: the nexus to destroy.
%
% o number_threads: the number of nexus threads.
%
*/
static inline void RelinquishCacheNexusPixels(NexusInfo *nexus_info)
{
if (nexus_info->mapped == MagickFalse)
(void) RelinquishAlignedMemory(nexus_info->cache);
else
(void) UnmapBlob(nexus_info->cache,(size_t) nexus_info->length);
nexus_info->cache=(PixelPacket *) NULL;
nexus_info->pixels=(PixelPacket *) NULL;
nexus_info->indexes=(IndexPacket *) NULL;
nexus_info->length=0;
nexus_info->mapped=MagickFalse;
}
MagickExport NexusInfo **DestroyPixelCacheNexus(NexusInfo **nexus_info,
const size_t number_threads)
{
register ssize_t
i;
assert(nexus_info != (NexusInfo **) NULL);
for (i=0; i < (ssize_t) (2*number_threads); i++)
{
if (nexus_info[i]->cache != (PixelPacket *) NULL)
RelinquishCacheNexusPixels(nexus_info[i]);
nexus_info[i]->signature=(~MagickCoreSignature);
}
*nexus_info=(NexusInfo *) RelinquishMagickMemory(*nexus_info);
nexus_info=(NexusInfo **) RelinquishAlignedMemory(nexus_info);
return(nexus_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t A u t h e n t i c I n d e x e s F r o m C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticIndexesFromCache() returns the indexes associated with the last
% call to QueueAuthenticPixelsCache() or GetAuthenticPixelsCache().
%
% The format of the GetAuthenticIndexesFromCache() method is:
%
% IndexPacket *GetAuthenticIndexesFromCache(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static IndexPacket *GetAuthenticIndexesFromCache(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
return(cache_info->nexus_info[id]->indexes);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t A u t h e n t i c I n d e x Q u e u e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticIndexQueue() returns the authentic black channel or the colormap
% indexes associated with the last call to QueueAuthenticPixels() or
% GetVirtualPixels(). NULL is returned if the black channel or colormap
% indexes are not available.
%
% The format of the GetAuthenticIndexQueue() method is:
%
% IndexPacket *GetAuthenticIndexQueue(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport IndexPacket *GetAuthenticIndexQueue(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.get_authentic_indexes_from_handler !=
(GetAuthenticIndexesFromHandler) NULL)
return(cache_info->methods.get_authentic_indexes_from_handler(image));
assert(id < (int) cache_info->number_threads);
return(cache_info->nexus_info[id]->indexes);
}
#if defined(MAGICKCORE_OPENCL_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t A u t h e n t i c O p e n C L B u f f e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticOpenCLBuffer() returns an OpenCL buffer used to execute OpenCL
% operations.
%
% The format of the GetAuthenticOpenCLBuffer() method is:
%
% cl_mem GetAuthenticOpenCLBuffer(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickPrivate cl_mem GetAuthenticOpenCLBuffer(const Image *image,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
cl_context
context;
cl_int
status;
MagickCLEnv
clEnv;
assert(image != (const Image *) NULL);
cache_info=(CacheInfo *)image->cache;
if ((cache_info->type == UndefinedCache) || (cache_info->reference_count > 1))
{
SyncImagePixelCache((Image *) image,exception);
cache_info=(CacheInfo *)image->cache;
}
if ((cache_info->type != MemoryCache) || (cache_info->mapped != MagickFalse))
return((cl_mem) NULL);
LockSemaphoreInfo(cache_info->semaphore);
clEnv=GetDefaultOpenCLEnv();
if (cache_info->opencl == (OpenCLCacheInfo *) NULL)
{
assert(cache_info->pixels != NULL);
context=GetOpenCLContext(clEnv);
cache_info->opencl=(OpenCLCacheInfo *) AcquireCriticalMemory(
sizeof(*cache_info->opencl));
(void) memset(cache_info->opencl,0,sizeof(*cache_info->opencl));
cache_info->opencl->events_semaphore=AllocateSemaphoreInfo();
cache_info->opencl->length=cache_info->length;
cache_info->opencl->pixels=cache_info->pixels;
cache_info->opencl->buffer=clEnv->library->clCreateBuffer(context,
CL_MEM_USE_HOST_PTR,cache_info->length,cache_info->pixels,&status);
if (status != CL_SUCCESS)
cache_info->opencl=RelinquishOpenCLCacheInfo(clEnv,cache_info->opencl);
}
if (cache_info->opencl != (OpenCLCacheInfo *) NULL)
clEnv->library->clRetainMemObject(cache_info->opencl->buffer);
UnlockSemaphoreInfo(cache_info->semaphore);
if (cache_info->opencl == (OpenCLCacheInfo *) NULL)
return((cl_mem) NULL);
return(cache_info->opencl->buffer);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t A u t h e n t i c P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticPixelCacheNexus() gets authentic pixels from the in-memory or
% disk pixel cache as defined by the geometry parameters. A pointer to the
% pixels is returned if the pixels are transferred, otherwise a NULL is
% returned.
%
% The format of the GetAuthenticPixelCacheNexus() method is:
%
% PixelPacket *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o nexus_info: the cache nexus to return.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport PixelPacket *GetAuthenticPixelCacheNexus(Image *image,
const ssize_t x,const ssize_t y,const size_t columns,const size_t rows,
NexusInfo *nexus_info,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
PixelPacket
*magick_restrict pixels;
/*
Transfer pixels from the cache.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickTrue,
nexus_info,exception);
if (pixels == (PixelPacket *) NULL)
return((PixelPacket *) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(pixels);
if (ReadPixelCachePixels(cache_info,nexus_info,exception) == MagickFalse)
return((PixelPacket *) NULL);
if (cache_info->active_index_channel != MagickFalse)
if (ReadPixelCacheIndexes(cache_info,nexus_info,exception) == MagickFalse)
return((PixelPacket *) NULL);
return(pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t A u t h e n t i c P i x e l s F r o m C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticPixelsFromCache() returns the pixels associated with the last
% call to the QueueAuthenticPixelsCache() or GetAuthenticPixelsCache() methods.
%
% The format of the GetAuthenticPixelsFromCache() method is:
%
% PixelPacket *GetAuthenticPixelsFromCache(const Image image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static PixelPacket *GetAuthenticPixelsFromCache(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
return(cache_info->nexus_info[id]->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t A u t h e n t i c P i x e l Q u e u e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticPixelQueue() returns the authentic pixels associated with the
% last call to QueueAuthenticPixels() or GetAuthenticPixels().
%
% The format of the GetAuthenticPixelQueue() method is:
%
% PixelPacket *GetAuthenticPixelQueue(const Image image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport PixelPacket *GetAuthenticPixelQueue(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.get_authentic_pixels_from_handler !=
(GetAuthenticPixelsFromHandler) NULL)
return(cache_info->methods.get_authentic_pixels_from_handler(image));
assert(id < (int) cache_info->number_threads);
return(cache_info->nexus_info[id]->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t A u t h e n t i c P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticPixels() obtains a pixel region for read/write access. If the
% region is successfully accessed, a pointer to a PixelPacket array
% representing the region is returned, otherwise NULL is returned.
%
% The returned pointer may point to a temporary working copy of the pixels
% or it may point to the original pixels in memory. Performance is maximized
% if the selected region is part of one row, or one or more full rows, since
% then there is opportunity to access the pixels in-place (without a copy)
% if the image is in memory, or in a memory-mapped file. The returned pointer
% must *never* be deallocated by the user.
%
% Pixels accessed via the returned pointer represent a simple array of type
% PixelPacket. If the image type is CMYK or if the storage class is
% PseduoClass, call GetAuthenticIndexQueue() after invoking
% GetAuthenticPixels() to obtain the black color component or colormap indexes
% (of type IndexPacket) corresponding to the region. Once the PixelPacket
% (and/or IndexPacket) array has been updated, the changes must be saved back
% to the underlying image using SyncAuthenticPixels() or they may be lost.
%
% The format of the GetAuthenticPixels() method is:
%
% PixelPacket *GetAuthenticPixels(Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport PixelPacket *GetAuthenticPixels(Image *image,const ssize_t x,
const ssize_t y,const size_t columns,const size_t rows,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.get_authentic_pixels_handler !=
(GetAuthenticPixelsHandler) NULL)
return(cache_info->methods.get_authentic_pixels_handler(image,x,y,columns,
rows,exception));
assert(id < (int) cache_info->number_threads);
return(GetAuthenticPixelCacheNexus(image,x,y,columns,rows,
cache_info->nexus_info[id],exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t A u t h e n t i c P i x e l s C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAuthenticPixelsCache() gets pixels from the in-memory or disk pixel cache
% as defined by the geometry parameters. A pointer to the pixels is returned
% if the pixels are transferred, otherwise a NULL is returned.
%
% The format of the GetAuthenticPixelsCache() method is:
%
% PixelPacket *GetAuthenticPixelsCache(Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static PixelPacket *GetAuthenticPixelsCache(Image *image,const ssize_t x,
const ssize_t y,const size_t columns,const size_t rows,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
if (cache_info == (Cache) NULL)
return((PixelPacket *) NULL);
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
return(GetAuthenticPixelCacheNexus(image,x,y,columns,rows,
cache_info->nexus_info[id],exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageExtent() returns the extent of the pixels associated with the
% last call to QueueAuthenticPixels() or GetAuthenticPixels().
%
% The format of the GetImageExtent() method is:
%
% MagickSizeType GetImageExtent(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickSizeType GetImageExtent(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id]));
}
#if defined(MAGICKCORE_OPENCL_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t O p e n C L E v e n t s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetOpenCLEvents() returns the events that the next operation should wait
% for. The argument event_count is set to the number of events.
%
% The format of the GetOpenCLEvents() method is:
%
% const cl_event *GetOpenCLEvents(const Image *image,
% cl_command_queue queue)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o event_count: will be set to the number of events.
%
*/
extern MagickPrivate cl_event *GetOpenCLEvents(const Image *image,
cl_uint *event_count)
{
CacheInfo
*magick_restrict cache_info;
cl_event
*events;
assert(image != (const Image *) NULL);
assert(event_count != (cl_uint *) NULL);
cache_info=(CacheInfo *) image->cache;
*event_count=0;
events=(cl_event *) NULL;
if (cache_info->opencl != (OpenCLCacheInfo *) NULL)
events=CopyOpenCLEvents(cache_info->opencl,event_count);
return(events);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImagePixelCache() ensures that there is only a single reference to the
% pixel cache to be modified, updating the provided cache pointer to point to
% a clone of the original pixel cache if necessary.
%
% The format of the GetImagePixelCache method is:
%
% Cache GetImagePixelCache(Image *image,const MagickBooleanType clone,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o clone: any value other than MagickFalse clones the cache pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline MagickBooleanType ValidatePixelCacheMorphology(
const Image *magick_restrict image)
{
CacheInfo
*magick_restrict cache_info;
/*
Does the image match the pixel cache morphology?
*/
cache_info=(CacheInfo *) image->cache;
if ((image->storage_class != cache_info->storage_class) ||
(image->colorspace != cache_info->colorspace) ||
(image->channels != cache_info->channels) ||
(image->columns != cache_info->columns) ||
(image->rows != cache_info->rows) ||
(cache_info->nexus_info == (NexusInfo **) NULL))
return(MagickFalse);
return(MagickTrue);
}
static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
MagickBooleanType
destroy,
status;
static MagickSizeType
cache_timelimit = MagickResourceInfinity,
cpu_throttle = MagickResourceInfinity,
cycles = 0;
status=MagickTrue;
if (cpu_throttle == MagickResourceInfinity)
cpu_throttle=GetMagickResourceLimit(ThrottleResource);
if ((cpu_throttle != 0) && ((cycles++ % 32) == 0))
MagickDelay(cpu_throttle);
if (cache_epoch == 0)
{
/*
Set the expire time in seconds.
*/
cache_epoch=GetMagickTime();
cache_timelimit=GetMagickResourceLimit(TimeResource);
}
if ((cache_timelimit != MagickResourceInfinity) &&
((MagickSizeType) (GetMagickTime()-cache_epoch) >= cache_timelimit))
{
#if defined(ECANCELED)
errno=ECANCELED;
#endif
cache_info=(CacheInfo *) image->cache;
if (cache_info->file != -1)
(void) ClosePixelCacheOnDisk(cache_info);
ThrowFatalException(ResourceLimitFatalError,"TimeLimitExceeded");
}
LockSemaphoreInfo(image->semaphore);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
#if defined(MAGICKCORE_OPENCL_SUPPORT)
CopyOpenCLBuffer(cache_info);
#endif
destroy=MagickFalse;
if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode))
{
LockSemaphoreInfo(cache_info->semaphore);
if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode))
{
CacheInfo
*clone_info;
Image
clone_image;
/*
Clone pixel cache.
*/
clone_image=(*image);
clone_image.semaphore=AllocateSemaphoreInfo();
clone_image.reference_count=1;
clone_image.cache=ClonePixelCache(cache_info);
clone_info=(CacheInfo *) clone_image.cache;
status=OpenPixelCache(&clone_image,IOMode,exception);
if (status == MagickFalse)
clone_info=(CacheInfo *) DestroyPixelCache(clone_info);
else
{
if (clone != MagickFalse)
status=ClonePixelCacheRepository(clone_info,cache_info,
exception);
if (status == MagickFalse)
clone_info=(CacheInfo *) DestroyPixelCache(clone_info);
else
{
destroy=MagickTrue;
image->cache=clone_info;
}
}
DestroySemaphoreInfo(&clone_image.semaphore);
}
UnlockSemaphoreInfo(cache_info->semaphore);
}
if (destroy != MagickFalse)
cache_info=(CacheInfo *) DestroyPixelCache(cache_info);
if (status != MagickFalse)
{
/*
Ensure the image matches the pixel cache morphology.
*/
if (image->type != UndefinedType)
image->type=UndefinedType;
if (ValidatePixelCacheMorphology(image) == MagickFalse)
{
status=OpenPixelCache(image,IOMode,exception);
cache_info=(CacheInfo *) image->cache;
if (cache_info->file != -1)
(void) ClosePixelCacheOnDisk(cache_info);
}
}
UnlockSemaphoreInfo(image->semaphore);
if (status == MagickFalse)
return((Cache) NULL);
return(image->cache);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e P i x e l C a c h e T y p e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImagePixelCacheType() returns the pixel cache type: UndefinedCache,
% DiskCache, MapCache, MemoryCache, or PingCache.
%
% The format of the GetImagePixelCacheType() method is:
%
% CacheType GetImagePixelCacheType(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport CacheType GetPixelCacheType(const Image *image)
{
return(GetImagePixelCacheType(image));
}
MagickExport CacheType GetImagePixelCacheType(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
return(cache_info->type);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t O n e A u t h e n t i c P i x e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetOneAuthenticPixel() returns a single pixel at the specified (x,y)
% location. The image background color is returned if an error occurs.
%
% The format of the GetOneAuthenticPixel() method is:
%
% MagickBooleanType GetOneAuthenticPixel(const Image image,const ssize_t x,
% const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y: These values define the location of the pixel to return.
%
% o pixel: return a pixel at the specified (x,y) location.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image,
const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
PixelPacket
*magick_restrict pixels;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
*pixel=image->background_color;
if (cache_info->methods.get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL)
return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y,pixel,exception));
pixels=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception);
if (pixels == (PixelPacket *) NULL)
return(MagickFalse);
*pixel=(*pixels);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t O n e A u t h e n t i c P i x e l F r o m C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetOneAuthenticPixelFromCache() returns a single pixel at the specified (x,y)
% location. The image background color is returned if an error occurs.
%
% The format of the GetOneAuthenticPixelFromCache() method is:
%
% MagickBooleanType GetOneAuthenticPixelFromCache(const Image image,
% const ssize_t x,const ssize_t y,PixelPacket *pixel,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y: These values define the location of the pixel to return.
%
% o pixel: return a pixel at the specified (x,y) location.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image,
const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
PixelPacket
*magick_restrict pixels;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
*pixel=image->background_color;
assert(id < (int) cache_info->number_threads);
pixels=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL,
cache_info->nexus_info[id],exception);
if (pixels == (PixelPacket *) NULL)
return(MagickFalse);
*pixel=(*pixels);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t O n e V i r t u a l M a g i c k P i x e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetOneVirtualMagickPixel() returns a single pixel at the specified (x,y)
% location. The image background color is returned if an error occurs. If
% you plan to modify the pixel, use GetOneAuthenticPixel() instead.
%
% The format of the GetOneVirtualMagickPixel() method is:
%
% MagickBooleanType GetOneVirtualMagickPixel(const Image image,
% const ssize_t x,const ssize_t y,MagickPixelPacket *pixel,
% ExceptionInfo exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y: these values define the location of the pixel to return.
%
% o pixel: return a pixel at the specified (x,y) location.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetOneVirtualMagickPixel(const Image *image,
const ssize_t x,const ssize_t y,MagickPixelPacket *pixel,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict pixels;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
pixels=GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y,
1UL,1UL,cache_info->nexus_info[id],exception);
GetMagickPixelPacket(image,pixel);
if (pixels == (const PixelPacket *) NULL)
return(MagickFalse);
indexes=GetVirtualIndexesFromNexus(cache_info,cache_info->nexus_info[id]);
SetMagickPixelPacket(image,pixels,indexes,pixel);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t O n e V i r t u a l M e t h o d P i x e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetOneVirtualMethodPixel() returns a single pixel at the specified (x,y)
% location as defined by specified pixel method. The image background color
% is returned if an error occurs. If you plan to modify the pixel, use
% GetOneAuthenticPixel() instead.
%
% The format of the GetOneVirtualMethodPixel() method is:
%
% MagickBooleanType GetOneVirtualMethodPixel(const Image image,
% const VirtualPixelMethod virtual_pixel_method,const ssize_t x,
% const ssize_t y,Pixelpacket *pixel,ExceptionInfo exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: the virtual pixel method.
%
% o x,y: These values define the location of the pixel to return.
%
% o pixel: return a pixel at the specified (x,y) location.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetOneVirtualMethodPixel(const Image *image,
const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y,
PixelPacket *pixel,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
const PixelPacket
*magick_restrict pixels;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
*pixel=image->background_color;
if (cache_info->methods.get_one_virtual_pixel_from_handler !=
(GetOneVirtualPixelFromHandler) NULL)
return(cache_info->methods.get_one_virtual_pixel_from_handler(image,
virtual_pixel_method,x,y,pixel,exception));
assert(id < (int) cache_info->number_threads);
pixels=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,1UL,1UL,
cache_info->nexus_info[id],exception);
if (pixels == (const PixelPacket *) NULL)
return(MagickFalse);
*pixel=(*pixels);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t O n e V i r t u a l P i x e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetOneVirtualPixel() returns a single virtual pixel at the specified
% (x,y) location. The image background color is returned if an error occurs.
% If you plan to modify the pixel, use GetOneAuthenticPixel() instead.
%
% The format of the GetOneVirtualPixel() method is:
%
% MagickBooleanType GetOneVirtualPixel(const Image image,const ssize_t x,
% const ssize_t y,PixelPacket *pixel,ExceptionInfo exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y: These values define the location of the pixel to return.
%
% o pixel: return a pixel at the specified (x,y) location.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetOneVirtualPixel(const Image *image,
const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
const PixelPacket
*magick_restrict pixels;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
*pixel=image->background_color;
if (cache_info->methods.get_one_virtual_pixel_from_handler !=
(GetOneVirtualPixelFromHandler) NULL)
return(cache_info->methods.get_one_virtual_pixel_from_handler(image,
GetPixelCacheVirtualMethod(image),x,y,pixel,exception));
assert(id < (int) cache_info->number_threads);
pixels=GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y,
1UL,1UL,cache_info->nexus_info[id],exception);
if (pixels == (const PixelPacket *) NULL)
return(MagickFalse);
*pixel=(*pixels);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t O n e V i r t u a l P i x e l F r o m C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetOneVirtualPixelFromCache() returns a single virtual pixel at the
% specified (x,y) location. The image background color is returned if an
% error occurs.
%
% The format of the GetOneVirtualPixelFromCache() method is:
%
% MagickBooleanType GetOneVirtualPixelFromCache(const Image image,
% const VirtualPixelPacket method,const ssize_t x,const ssize_t y,
% PixelPacket *pixel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: the virtual pixel method.
%
% o x,y: These values define the location of the pixel to return.
%
% o pixel: return a pixel at the specified (x,y) location.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType GetOneVirtualPixelFromCache(const Image *image,
const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y,
PixelPacket *pixel,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
const PixelPacket
*magick_restrict pixels;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
*pixel=image->background_color;
pixels=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,1UL,1UL,
cache_info->nexus_info[id],exception);
if (pixels == (const PixelPacket *) NULL)
return(MagickFalse);
*pixel=(*pixels);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e C h a n n e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheChannels() returns the number of pixel channels associated
% with this instance of the pixel cache.
%
% The format of the GetPixelCacheChannels() method is:
%
% size_t GetPixelCacheChannels(Cache cache)
%
% A description of each parameter follows:
%
% o type: GetPixelCacheChannels returns DirectClass or PseudoClass.
%
% o cache: the pixel cache.
%
*/
MagickExport size_t GetPixelCacheChannels(const Cache cache)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
cache_info->filename);
return(cache_info->channels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e C o l o r s p a c e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheColorspace() returns the colorspace of the pixel cache.
%
% The format of the GetPixelCacheColorspace() method is:
%
% Colorspace GetPixelCacheColorspace(const Cache cache)
%
% A description of each parameter follows:
%
% o cache: the pixel cache.
%
*/
MagickExport ColorspaceType GetPixelCacheColorspace(const Cache cache)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
cache_info->filename);
return(cache_info->colorspace);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e F i l e n a m e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheFilename() returns the filename associated with the pixel
% cache.
%
% The format of the GetPixelCacheFilename() method is:
%
% const char *GetPixelCacheFilename(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport const char *GetPixelCacheFilename(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
return(cache_info->cache_filename);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e M e t h o d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheMethods() initializes the CacheMethods structure.
%
% The format of the GetPixelCacheMethods() method is:
%
% void GetPixelCacheMethods(CacheMethods *cache_methods)
%
% A description of each parameter follows:
%
% o cache_methods: Specifies a pointer to a CacheMethods structure.
%
*/
MagickExport void GetPixelCacheMethods(CacheMethods *cache_methods)
{
assert(cache_methods != (CacheMethods *) NULL);
(void) memset(cache_methods,0,sizeof(*cache_methods));
cache_methods->get_virtual_pixel_handler=GetVirtualPixelCache;
cache_methods->get_virtual_pixels_handler=GetVirtualPixelsCache;
cache_methods->get_virtual_indexes_from_handler=GetVirtualIndexesFromCache;
cache_methods->get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromCache;
cache_methods->get_authentic_pixels_handler=GetAuthenticPixelsCache;
cache_methods->get_authentic_indexes_from_handler=
GetAuthenticIndexesFromCache;
cache_methods->get_authentic_pixels_from_handler=GetAuthenticPixelsFromCache;
cache_methods->get_one_authentic_pixel_from_handler=
GetOneAuthenticPixelFromCache;
cache_methods->queue_authentic_pixels_handler=QueueAuthenticPixelsCache;
cache_methods->sync_authentic_pixels_handler=SyncAuthenticPixelsCache;
cache_methods->destroy_pixel_handler=DestroyImagePixelCache;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e N e x u s E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheNexusExtent() returns the extent of the pixels associated with
% the last call to SetPixelCacheNexusPixels() or GetPixelCacheNexusPixels().
%
% The format of the GetPixelCacheNexusExtent() method is:
%
% MagickSizeType GetPixelCacheNexusExtent(const Cache cache,
% NexusInfo *nexus_info)
%
% A description of each parameter follows:
%
% o nexus_info: the nexus info.
%
*/
MagickExport MagickSizeType GetPixelCacheNexusExtent(const Cache cache,
NexusInfo *nexus_info)
{
CacheInfo
*magick_restrict cache_info;
MagickSizeType
extent;
assert(cache != NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
extent=(MagickSizeType) nexus_info->region.width*nexus_info->region.height;
if (extent == 0)
return((MagickSizeType) cache_info->columns*cache_info->rows);
return(extent);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCachePixels() returns the pixels associated with the specified image.
%
% The format of the GetPixelCachePixels() method is:
%
% void *GetPixelCachePixels(Image *image,MagickSizeType *length,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o length: the pixel cache length.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport void *GetPixelCachePixels(Image *image,MagickSizeType *length,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
assert(length != (MagickSizeType *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
(void) exception;
*length=cache_info->length;
if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache))
return((void *) NULL);
return((void *) cache_info->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e S t o r a g e C l a s s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheStorageClass() returns the class type of the pixel cache.
%
% The format of the GetPixelCacheStorageClass() method is:
%
% ClassType GetPixelCacheStorageClass(Cache cache)
%
% A description of each parameter follows:
%
% o type: GetPixelCacheStorageClass returns DirectClass or PseudoClass.
%
% o cache: the pixel cache.
%
*/
MagickExport ClassType GetPixelCacheStorageClass(const Cache cache)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
cache_info->filename);
return(cache_info->storage_class);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e T i l e S i z e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheTileSize() returns the pixel cache tile size.
%
% The format of the GetPixelCacheTileSize() method is:
%
% void GetPixelCacheTileSize(const Image *image,size_t *width,
% size_t *height)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the optimize cache tile width in pixels.
%
% o height: the optimize cache tile height in pixels.
%
*/
MagickExport void GetPixelCacheTileSize(const Image *image,size_t *width,
size_t *height)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
*width=2048UL/sizeof(PixelPacket);
if (GetImagePixelCacheType(image) == DiskCache)
*width=8192UL/sizeof(PixelPacket);
*height=(*width);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t P i x e l C a c h e V i r t u a l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelCacheVirtualMethod() gets the "virtual pixels" method for the
% pixel cache. A virtual pixel is any pixel access that is outside the
% boundaries of the image cache.
%
% The format of the GetPixelCacheVirtualMethod() method is:
%
% VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
return(cache_info->virtual_pixel_method);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t V i r t u a l I n d e x e s F r o m C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualIndexesFromCache() returns the indexes associated with the last
% call to QueueAuthenticPixelsCache() or GetVirtualPixelCache().
%
% The format of the GetVirtualIndexesFromCache() method is:
%
% IndexPacket *GetVirtualIndexesFromCache(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static const IndexPacket *GetVirtualIndexesFromCache(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
return(GetVirtualIndexesFromNexus(cache_info,cache_info->nexus_info[id]));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t V i r t u a l I n d e x e s F r o m N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualIndexesFromNexus() returns the indexes associated with the
% specified cache nexus.
%
% The format of the GetVirtualIndexesFromNexus() method is:
%
% const IndexPacket *GetVirtualIndexesFromNexus(const Cache cache,
% NexusInfo *nexus_info)
%
% A description of each parameter follows:
%
% o cache: the pixel cache.
%
% o nexus_info: the cache nexus to return the colormap indexes.
%
*/
MagickExport const IndexPacket *GetVirtualIndexesFromNexus(const Cache cache,
NexusInfo *nexus_info)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->storage_class == UndefinedClass)
return((IndexPacket *) NULL);
return(nexus_info->indexes);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t V i r t u a l I n d e x Q u e u e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualIndexQueue() returns the virtual black channel or the
% colormap indexes associated with the last call to QueueAuthenticPixels() or
% GetVirtualPixels(). NULL is returned if the black channel or colormap
% indexes are not available.
%
% The format of the GetVirtualIndexQueue() method is:
%
% const IndexPacket *GetVirtualIndexQueue(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport const IndexPacket *GetVirtualIndexQueue(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.get_virtual_indexes_from_handler !=
(GetVirtualIndexesFromHandler) NULL)
return(cache_info->methods.get_virtual_indexes_from_handler(image));
assert(id < (int) cache_info->number_threads);
return(GetVirtualIndexesFromNexus(cache_info,cache_info->nexus_info[id]));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t V i r t u a l P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualPixelCacheNexus() gets virtual pixels from the in-memory or disk
% pixel cache as defined by the geometry parameters. A pointer to the pixels
% is returned if the pixels are transferred, otherwise a NULL is returned.
%
% The format of the GetVirtualPixelCacheNexus() method is:
%
% PixelPacket *GetVirtualPixelCacheNexus(const Image *image,
% const VirtualPixelMethod method,const ssize_t x,const ssize_t y,
% const size_t columns,const size_t rows,NexusInfo *nexus_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: the virtual pixel method.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o nexus_info: the cache nexus to acquire.
%
% o exception: return any errors or warnings in this structure.
%
*/
static ssize_t
DitherMatrix[64] =
{
0, 48, 12, 60, 3, 51, 15, 63,
32, 16, 44, 28, 35, 19, 47, 31,
8, 56, 4, 52, 11, 59, 7, 55,
40, 24, 36, 20, 43, 27, 39, 23,
2, 50, 14, 62, 1, 49, 13, 61,
34, 18, 46, 30, 33, 17, 45, 29,
10, 58, 6, 54, 9, 57, 5, 53,
42, 26, 38, 22, 41, 25, 37, 21
};
static inline ssize_t DitherX(const ssize_t x,const size_t columns)
{
ssize_t
index;
index=x+DitherMatrix[x & 0x07]-32L;
if (index < 0L)
return(0L);
if (index >= (ssize_t) columns)
return((ssize_t) columns-1L);
return(index);
}
static inline ssize_t DitherY(const ssize_t y,const size_t rows)
{
ssize_t
index;
index=y+DitherMatrix[y & 0x07]-32L;
if (index < 0L)
return(0L);
if (index >= (ssize_t) rows)
return((ssize_t) rows-1L);
return(index);
}
static inline ssize_t EdgeX(const ssize_t x,const size_t columns)
{
if (x < 0L)
return(0L);
if (x >= (ssize_t) columns)
return((ssize_t) (columns-1));
return(x);
}
static inline ssize_t EdgeY(const ssize_t y,const size_t rows)
{
if (y < 0L)
return(0L);
if (y >= (ssize_t) rows)
return((ssize_t) (rows-1));
return(y);
}
static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns)
{
return((ssize_t) (columns*GetPseudoRandomValue(random_info)));
}
static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows)
{
return((ssize_t) (rows*GetPseudoRandomValue(random_info)));
}
static inline MagickModulo VirtualPixelModulo(const ssize_t offset,
const size_t extent)
{
MagickModulo
modulo;
modulo.quotient=offset/((ssize_t) extent);
modulo.remainder=offset % ((ssize_t) extent);
if ((modulo.remainder != 0) && ((offset ^ ((ssize_t) extent)) < 0))
{
modulo.quotient-=1;
modulo.remainder+=((ssize_t) extent);
}
return(modulo);
}
MagickExport const PixelPacket *GetVirtualPixelCacheNexus(const Image *image,
const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y,
const size_t columns,const size_t rows,NexusInfo *nexus_info,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
IndexPacket
virtual_index;
MagickOffsetType
offset;
MagickSizeType
length,
number_pixels;
NexusInfo
*magick_restrict virtual_nexus;
PixelPacket
*magick_restrict pixels,
virtual_pixel;
register const IndexPacket
*magick_restrict virtual_indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
u,
v;
/*
Acquire pixels.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->type == UndefinedCache)
return((const PixelPacket *) NULL);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
CopyOpenCLBuffer(cache_info);
#endif
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,x,y,columns,rows,
(image->clip_mask != (Image *) NULL) || (image->mask != (Image *) NULL) ?
MagickTrue : MagickFalse,nexus_info,exception);
if (pixels == (PixelPacket *) NULL)
return((const PixelPacket *) NULL);
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+
nexus_info->region.x;
length=(MagickSizeType) (nexus_info->region.height-1L)*cache_info->columns+
nexus_info->region.width-1L;
number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows;
if ((offset >= 0) && (((MagickSizeType) offset+length) < number_pixels))
if ((x >= 0) && ((ssize_t) (x+columns) <= (ssize_t) cache_info->columns) &&
(y >= 0) && ((ssize_t) (y+rows) <= (ssize_t) cache_info->rows))
{
MagickBooleanType
status;
/*
Pixel request is inside cache extents.
*/
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(pixels);
status=ReadPixelCachePixels(cache_info,nexus_info,exception);
if (status == MagickFalse)
return((const PixelPacket *) NULL);
if ((cache_info->storage_class == PseudoClass) ||
(cache_info->colorspace == CMYKColorspace))
{
status=ReadPixelCacheIndexes(cache_info,nexus_info,exception);
if (status == MagickFalse)
return((const PixelPacket *) NULL);
}
return(pixels);
}
/*
Pixel request is outside cache extents.
*/
virtual_nexus=nexus_info->virtual_nexus;
q=pixels;
indexes=nexus_info->indexes;
switch (virtual_pixel_method)
{
case BlackVirtualPixelMethod:
{
SetPixelRed(&virtual_pixel,0);
SetPixelGreen(&virtual_pixel,0);
SetPixelBlue(&virtual_pixel,0);
SetPixelOpacity(&virtual_pixel,OpaqueOpacity);
break;
}
case GrayVirtualPixelMethod:
{
SetPixelRed(&virtual_pixel,QuantumRange/2);
SetPixelGreen(&virtual_pixel,QuantumRange/2);
SetPixelBlue(&virtual_pixel,QuantumRange/2);
SetPixelOpacity(&virtual_pixel,OpaqueOpacity);
break;
}
case TransparentVirtualPixelMethod:
{
SetPixelRed(&virtual_pixel,0);
SetPixelGreen(&virtual_pixel,0);
SetPixelBlue(&virtual_pixel,0);
SetPixelOpacity(&virtual_pixel,TransparentOpacity);
break;
}
case MaskVirtualPixelMethod:
case WhiteVirtualPixelMethod:
{
SetPixelRed(&virtual_pixel,QuantumRange);
SetPixelGreen(&virtual_pixel,QuantumRange);
SetPixelBlue(&virtual_pixel,QuantumRange);
SetPixelOpacity(&virtual_pixel,OpaqueOpacity);
break;
}
default:
{
virtual_pixel=image->background_color;
break;
}
}
virtual_index=(IndexPacket) 0;
for (v=0; v < (ssize_t) rows; v++)
{
ssize_t
y_offset;
y_offset=y+v;
if ((virtual_pixel_method == EdgeVirtualPixelMethod) ||
(virtual_pixel_method == UndefinedVirtualPixelMethod))
y_offset=EdgeY(y_offset,cache_info->rows);
for (u=0; u < (ssize_t) columns; u+=length)
{
ssize_t
x_offset;
x_offset=x+u;
length=(MagickSizeType) MagickMin(cache_info->columns-x_offset,columns-u);
if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) ||
((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) ||
(length == 0))
{
MagickModulo
x_modulo,
y_modulo;
/*
Transfer a single pixel.
*/
length=(MagickSizeType) 1;
switch (virtual_pixel_method)
{
case BackgroundVirtualPixelMethod:
case ConstantVirtualPixelMethod:
case BlackVirtualPixelMethod:
case GrayVirtualPixelMethod:
case TransparentVirtualPixelMethod:
case MaskVirtualPixelMethod:
case WhiteVirtualPixelMethod:
{
p=(&virtual_pixel);
virtual_indexes=(&virtual_index);
break;
}
case EdgeVirtualPixelMethod:
default:
{
p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,
EdgeX(x_offset,cache_info->columns),
EdgeY(y_offset,cache_info->rows),1UL,1UL,virtual_nexus,
exception);
virtual_indexes=GetVirtualIndexesFromNexus(cache_info,
virtual_nexus);
break;
}
case RandomVirtualPixelMethod:
{
if (cache_info->random_info == (RandomInfo *) NULL)
cache_info->random_info=AcquireRandomInfo();
p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,
RandomX(cache_info->random_info,cache_info->columns),
RandomY(cache_info->random_info,cache_info->rows),1UL,1UL,
virtual_nexus,exception);
virtual_indexes=GetVirtualIndexesFromNexus(cache_info,
virtual_nexus);
break;
}
case DitherVirtualPixelMethod:
{
p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,
DitherX(x_offset,cache_info->columns),
DitherY(y_offset,cache_info->rows),1UL,1UL,virtual_nexus,
exception);
virtual_indexes=GetVirtualIndexesFromNexus(cache_info,
virtual_nexus);
break;
}
case TileVirtualPixelMethod:
{
x_modulo=VirtualPixelModulo(x_offset,cache_info->columns);
y_modulo=VirtualPixelModulo(y_offset,cache_info->rows);
p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,
x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus,
exception);
virtual_indexes=GetVirtualIndexesFromNexus(cache_info,
virtual_nexus);
break;
}
case MirrorVirtualPixelMethod:
{
x_modulo=VirtualPixelModulo(x_offset,cache_info->columns);
if ((x_modulo.quotient & 0x01) == 1L)
x_modulo.remainder=(ssize_t) cache_info->columns-
x_modulo.remainder-1L;
y_modulo=VirtualPixelModulo(y_offset,cache_info->rows);
if ((y_modulo.quotient & 0x01) == 1L)
y_modulo.remainder=(ssize_t) cache_info->rows-
y_modulo.remainder-1L;
p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,
x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus,
exception);
virtual_indexes=GetVirtualIndexesFromNexus(cache_info,
virtual_nexus);
break;
}
case CheckerTileVirtualPixelMethod:
{
x_modulo=VirtualPixelModulo(x_offset,cache_info->columns);
y_modulo=VirtualPixelModulo(y_offset,cache_info->rows);
if (((x_modulo.quotient ^ y_modulo.quotient) & 0x01) != 0L)
{
p=(&virtual_pixel);
virtual_indexes=(&virtual_index);
break;
}
p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,
x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus,
exception);
virtual_indexes=GetVirtualIndexesFromNexus(cache_info,
virtual_nexus);
break;
}
case HorizontalTileVirtualPixelMethod:
{
if ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows))
{
p=(&virtual_pixel);
virtual_indexes=(&virtual_index);
break;
}
x_modulo=VirtualPixelModulo(x_offset,cache_info->columns);
y_modulo=VirtualPixelModulo(y_offset,cache_info->rows);
p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,
x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus,
exception);
virtual_indexes=GetVirtualIndexesFromNexus(cache_info,
virtual_nexus);
break;
}
case VerticalTileVirtualPixelMethod:
{
if ((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns))
{
p=(&virtual_pixel);
virtual_indexes=(&virtual_index);
break;
}
x_modulo=VirtualPixelModulo(x_offset,cache_info->columns);
y_modulo=VirtualPixelModulo(y_offset,cache_info->rows);
p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,
x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus,
exception);
virtual_indexes=GetVirtualIndexesFromNexus(cache_info,
virtual_nexus);
break;
}
case HorizontalTileEdgeVirtualPixelMethod:
{
x_modulo=VirtualPixelModulo(x_offset,cache_info->columns);
p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,
x_modulo.remainder,EdgeY(y_offset,cache_info->rows),1UL,1UL,
virtual_nexus,exception);
virtual_indexes=GetVirtualIndexesFromNexus(cache_info,
virtual_nexus);
break;
}
case VerticalTileEdgeVirtualPixelMethod:
{
y_modulo=VirtualPixelModulo(y_offset,cache_info->rows);
p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,
EdgeX(x_offset,cache_info->columns),y_modulo.remainder,1UL,1UL,
virtual_nexus,exception);
virtual_indexes=GetVirtualIndexesFromNexus(cache_info,
virtual_nexus);
break;
}
}
if (p == (const PixelPacket *) NULL)
break;
*q++=(*p);
if ((indexes != (IndexPacket *) NULL) &&
(virtual_indexes != (const IndexPacket *) NULL))
*indexes++=(*virtual_indexes);
continue;
}
/*
Transfer a run of pixels.
*/
p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x_offset,y_offset,
(size_t) length,1UL,virtual_nexus,exception);
if (p == (const PixelPacket *) NULL)
break;
virtual_indexes=GetVirtualIndexesFromNexus(cache_info,virtual_nexus);
(void) memcpy(q,p,(size_t) length*sizeof(*p));
q+=length;
if ((indexes != (IndexPacket *) NULL) &&
(virtual_indexes != (const IndexPacket *) NULL))
{
(void) memcpy(indexes,virtual_indexes,(size_t) length*
sizeof(*virtual_indexes));
indexes+=length;
}
}
if (u < (ssize_t) columns)
break;
}
/*
Free resources.
*/
if (v < (ssize_t) rows)
return((const PixelPacket *) NULL);
return(pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t V i r t u a l P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualPixelCache() get virtual pixels from the in-memory or disk pixel
% cache as defined by the geometry parameters. A pointer to the pixels
% is returned if the pixels are transferred, otherwise a NULL is returned.
%
% The format of the GetVirtualPixelCache() method is:
%
% const PixelPacket *GetVirtualPixelCache(const Image *image,
% const VirtualPixelMethod virtual_pixel_method,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: the virtual pixel method.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static const PixelPacket *GetVirtualPixelCache(const Image *image,
const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y,
const size_t columns,const size_t rows,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
return(GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,columns,rows,
cache_info->nexus_info[id],exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t V i r t u a l P i x e l Q u e u e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualPixelQueue() returns the virtual pixels associated with the
% last call to QueueAuthenticPixels() or GetVirtualPixels().
%
% The format of the GetVirtualPixelQueue() method is:
%
% const PixelPacket *GetVirtualPixelQueue(const Image image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport const PixelPacket *GetVirtualPixelQueue(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.get_virtual_pixels_handler !=
(GetVirtualPixelsHandler) NULL)
return(cache_info->methods.get_virtual_pixels_handler(image));
assert(id < (int) cache_info->number_threads);
return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id]));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t V i r t u a l P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualPixels() returns an immutable pixel region. If the
% region is successfully accessed, a pointer to it is returned, otherwise
% NULL is returned. The returned pointer may point to a temporary working
% copy of the pixels or it may point to the original pixels in memory.
% Performance is maximized if the selected region is part of one row, or one
% or more full rows, since there is opportunity to access the pixels in-place
% (without a copy) if the image is in memory, or in a memory-mapped file. The
% returned pointer must *never* be deallocated by the user.
%
% Pixels accessed via the returned pointer represent a simple array of type
% PixelPacket. If the image type is CMYK or the storage class is PseudoClass,
% call GetAuthenticIndexQueue() after invoking GetAuthenticPixels() to access
% the black color component or to obtain the colormap indexes (of type
% IndexPacket) corresponding to the region.
%
% If you plan to modify the pixels, use GetAuthenticPixels() instead.
%
% Note, the GetVirtualPixels() and GetAuthenticPixels() methods are not thread-
% safe. In a threaded environment, use GetCacheViewVirtualPixels() or
% GetCacheViewAuthenticPixels() instead.
%
% The format of the GetVirtualPixels() method is:
%
% const PixelPacket *GetVirtualPixels(const Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport const PixelPacket *GetVirtualPixels(const Image *image,
const ssize_t x,const ssize_t y,const size_t columns,const size_t rows,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.get_virtual_pixel_handler !=
(GetVirtualPixelHandler) NULL)
return(cache_info->methods.get_virtual_pixel_handler(image,
GetPixelCacheVirtualMethod(image),x,y,columns,rows,exception));
assert(id < (int) cache_info->number_threads);
return(GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y,
columns,rows,cache_info->nexus_info[id],exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t V i r t u a l P i x e l s F r o m C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualPixelsCache() returns the pixels associated with the last call
% to QueueAuthenticPixelsCache() or GetVirtualPixelCache().
%
% The format of the GetVirtualPixelsCache() method is:
%
% PixelPacket *GetVirtualPixelsCache(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static const PixelPacket *GetVirtualPixelsCache(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
return(GetVirtualPixelsNexus(image->cache,cache_info->nexus_info[id]));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t V i r t u a l P i x e l s N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetVirtualPixelsNexus() returns the pixels associated with the specified
% cache nexus.
%
% The format of the GetVirtualPixelsNexus() method is:
%
% const IndexPacket *GetVirtualPixelsNexus(const Cache cache,
% NexusInfo *nexus_info)
%
% A description of each parameter follows:
%
% o cache: the pixel cache.
%
% o nexus_info: the cache nexus to return the colormap pixels.
%
*/
MagickExport const PixelPacket *GetVirtualPixelsNexus(const Cache cache,
NexusInfo *nexus_info)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->storage_class == UndefinedClass)
return((PixelPacket *) NULL);
return((const PixelPacket *) nexus_info->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a s k P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MaskPixelCacheNexus() masks the cache nexus as defined by the image mask.
% The method returns MagickTrue if the pixel region is masked, otherwise
% MagickFalse.
%
% The format of the MaskPixelCacheNexus() method is:
%
% MagickBooleanType MaskPixelCacheNexus(Image *image,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o nexus_info: the cache nexus to clip.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void ApplyPixelCompositeMask(const MagickPixelPacket *p,
const MagickRealType alpha,const MagickPixelPacket *q,
const MagickRealType beta,MagickPixelPacket *composite)
{
double
gamma;
if (fabs(alpha-TransparentOpacity) < MagickEpsilon)
{
*composite=(*q);
return;
}
gamma=1.0-QuantumScale*QuantumScale*alpha*beta;
gamma=PerceptibleReciprocal(gamma);
composite->red=gamma*MagickOver_(p->red,alpha,q->red,beta);
composite->green=gamma*MagickOver_(p->green,alpha,q->green,beta);
composite->blue=gamma*MagickOver_(p->blue,alpha,q->blue,beta);
if ((p->colorspace == CMYKColorspace) && (q->colorspace == CMYKColorspace))
composite->index=gamma*MagickOver_(p->index,alpha,q->index,beta);
}
static MagickBooleanType MaskPixelCacheNexus(Image *image,NexusInfo *nexus_info,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
MagickOffsetType
n;
MagickPixelPacket
alpha,
beta;
NexusInfo
**magick_restrict mask_nexus;
register const PixelPacket
*magick_restrict r;
register IndexPacket
*magick_restrict nexus_indexes,
*magick_restrict indexes;
register PixelPacket
*magick_restrict p,
*magick_restrict q;
ssize_t
y;
/*
Apply composite mask.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->mask == (Image *) NULL) || (image->storage_class == PseudoClass))
return(MagickTrue);
if ((nexus_info->region.width == 0) || (nexus_info->region.height == 0))
return(MagickTrue);
cache_info=(CacheInfo *) image->cache;
if (cache_info == (Cache) NULL)
return(MagickFalse);
mask_nexus=AcquirePixelCacheNexus(1);
p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height,
nexus_info->virtual_nexus,exception);
indexes=nexus_info->virtual_nexus->indexes;
q=nexus_info->pixels;
nexus_indexes=nexus_info->indexes;
r=GetVirtualPixelCacheNexus(image->mask,MaskVirtualPixelMethod,
nexus_info->region.x,nexus_info->region.y,nexus_info->region.width,
nexus_info->region.height,mask_nexus[0],&image->exception);
if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL) ||
(r == (const PixelPacket *) NULL))
return(MagickFalse);
n=0;
GetMagickPixelPacket(image,&alpha);
GetMagickPixelPacket(image,&beta);
for (y=0; y < (ssize_t) nexus_info->region.height; y++)
{
register ssize_t
x;
for (x=0; x < (ssize_t) nexus_info->region.width; x++)
{
SetMagickPixelPacket(image,p,indexes+n,&alpha);
SetMagickPixelPacket(image,q,nexus_indexes+n,&beta);
ApplyPixelCompositeMask(&beta,GetPixelIntensity(image,r),&alpha,
alpha.opacity,&beta);
SetPixelRed(q,ClampToQuantum(beta.red));
SetPixelGreen(q,ClampToQuantum(beta.green));
SetPixelBlue(q,ClampToQuantum(beta.blue));
SetPixelOpacity(q,ClampToQuantum(beta.opacity));
if (cache_info->active_index_channel != MagickFalse)
SetPixelIndex(nexus_indexes+n,GetPixelIndex(indexes+n));
p++;
q++;
r++;
n++;
}
}
mask_nexus=DestroyPixelCacheNexus(mask_nexus,1);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ O p e n P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OpenPixelCache() allocates the pixel cache. This includes defining the cache
% dimensions, allocating space for the image pixels and optionally the
% colormap indexes, and memory mapping the cache if it is disk based. The
% cache nexus array is initialized as well.
%
% The format of the OpenPixelCache() method is:
%
% MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o mode: ReadMode, WriteMode, or IOMode.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType OpenPixelCacheOnDisk(CacheInfo *cache_info,
const MapMode mode)
{
int
file;
/*
Open pixel cache on disk.
*/
if ((cache_info->file != -1) && (cache_info->disk_mode == mode))
return(MagickTrue); /* cache already open and in the proper mode */
if (*cache_info->cache_filename == '\0')
file=AcquireUniqueFileResource(cache_info->cache_filename);
else
switch (mode)
{
case ReadMode:
{
file=open_utf8(cache_info->cache_filename,O_RDONLY | O_BINARY,0);
break;
}
case WriteMode:
{
file=open_utf8(cache_info->cache_filename,O_WRONLY | O_CREAT |
O_BINARY | O_EXCL,S_MODE);
if (file == -1)
file=open_utf8(cache_info->cache_filename,O_WRONLY | O_BINARY,S_MODE);
break;
}
case IOMode:
default:
{
file=open_utf8(cache_info->cache_filename,O_RDWR | O_CREAT | O_BINARY |
O_EXCL,S_MODE);
if (file == -1)
file=open_utf8(cache_info->cache_filename,O_RDWR | O_BINARY,S_MODE);
break;
}
}
if (file == -1)
return(MagickFalse);
(void) AcquireMagickResource(FileResource,1);
if (cache_info->file != -1)
(void) ClosePixelCacheOnDisk(cache_info);
cache_info->file=file;
cache_info->disk_mode=mode;
return(MagickTrue);
}
static inline MagickOffsetType WritePixelCacheRegion(
const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset,
const MagickSizeType length,const unsigned char *magick_restrict buffer)
{
register MagickOffsetType
i;
ssize_t
count;
#if !defined(MAGICKCORE_HAVE_PWRITE)
if (lseek(cache_info->file,offset,SEEK_SET) < 0)
return((MagickOffsetType) -1);
#endif
count=0;
for (i=0; i < (MagickOffsetType) length; i+=count)
{
#if !defined(MAGICKCORE_HAVE_PWRITE)
count=write(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t)
SSIZE_MAX));
#else
count=pwrite(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t)
SSIZE_MAX),offset+i);
#endif
if (count <= 0)
{
count=0;
if (errno != EINTR)
break;
}
}
return(i);
}
static MagickBooleanType SetPixelCacheExtent(Image *image,MagickSizeType length)
{
CacheInfo
*magick_restrict cache_info;
MagickOffsetType
count,
extent,
offset;
cache_info=(CacheInfo *) image->cache;
if (image->debug != MagickFalse)
{
char
format[MaxTextExtent],
message[MaxTextExtent];
(void) FormatMagickSize(length,MagickFalse,format);
(void) FormatLocaleString(message,MaxTextExtent,
"extend %s (%s[%d], disk, %s)",cache_info->filename,
cache_info->cache_filename,cache_info->file,format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_END);
if (offset < 0)
return(MagickFalse);
if ((MagickSizeType) offset >= length)
count=(MagickOffsetType) 1;
else
{
extent=(MagickOffsetType) length-1;
count=WritePixelCacheRegion(cache_info,extent,1,(const unsigned char *)
"");
if (count != 1)
return(MagickFalse);
#if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE)
if (cache_info->synchronize != MagickFalse)
if (posix_fallocate(cache_info->file,offset+1,extent-offset) != 0)
return(MagickFalse);
#endif
}
offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_SET);
if (offset < 0)
return(MagickFalse);
return(MagickTrue);
}
static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info,
source_info;
char
format[MaxTextExtent],
message[MaxTextExtent];
const char
*hosts,
*type;
MagickSizeType
length,
number_pixels;
MagickStatusType
status;
size_t
columns,
packet_size;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (cache_anonymous_memory < 0)
{
char
*value;
/*
Does the security policy require anonymous mapping for pixel cache?
*/
cache_anonymous_memory=0;
value=GetPolicyValue("pixel-cache-memory");
if (value == (char *) NULL)
value=GetPolicyValue("cache:memory-map");
if (LocaleCompare(value,"anonymous") == 0)
{
#if defined(MAGICKCORE_HAVE_MMAP) && defined(MAP_ANONYMOUS)
cache_anonymous_memory=1;
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateError,"DelegateLibrarySupportNotBuiltIn",
"'%s' (policy requires anonymous memory mapping)",image->filename);
#endif
}
value=DestroyString(value);
}
if ((image->columns == 0) || (image->rows == 0))
ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (((MagickSizeType) image->columns > cache_info->width_limit) ||
((MagickSizeType) image->rows > cache_info->height_limit))
ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit",
image->filename);
if (GetMagickResourceLimit(ListLengthResource) != MagickResourceInfinity)
{
length=GetImageListLength(image);
if (AcquireMagickResource(ListLengthResource,length) == MagickFalse)
ThrowBinaryException(ResourceLimitError,"ListLengthExceedsLimit",
image->filename);
}
source_info=(*cache_info);
source_info.file=(-1);
(void) FormatLocaleString(cache_info->filename,MaxTextExtent,"%s[%.20g]",
image->filename,(double) image->scene);
cache_info->storage_class=image->storage_class;
cache_info->colorspace=image->colorspace;
cache_info->rows=image->rows;
cache_info->columns=image->columns;
cache_info->channels=image->channels;
cache_info->active_index_channel=((image->storage_class == PseudoClass) ||
(image->colorspace == CMYKColorspace)) ? MagickTrue : MagickFalse;
cache_info->mode=mode;
number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows;
packet_size=sizeof(PixelPacket);
if (cache_info->active_index_channel != MagickFalse)
packet_size+=sizeof(IndexPacket);
length=number_pixels*packet_size;
columns=(size_t) (length/cache_info->rows/packet_size);
if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) ||
((ssize_t) cache_info->rows < 0))
ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed",
image->filename);
cache_info->length=length;
if (image->ping != MagickFalse)
{
cache_info->type=PingCache;
return(MagickTrue);
}
status=AcquireMagickResource(AreaResource,(MagickSizeType)
cache_info->columns*cache_info->rows);
if (cache_info->mode == PersistMode)
status=MagickFalse;
length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket));
if ((status != MagickFalse) &&
(length == (MagickSizeType) ((size_t) length)) &&
((cache_info->type == UndefinedCache) ||
(cache_info->type == MemoryCache)))
{
status=AcquireMagickResource(MemoryResource,cache_info->length);
if (status != MagickFalse)
{
status=MagickTrue;
if (cache_anonymous_memory <= 0)
{
cache_info->mapped=MagickFalse;
cache_info->pixels=(PixelPacket *) MagickAssumeAligned(
AcquireAlignedMemory(1,(size_t) cache_info->length));
}
else
{
cache_info->mapped=MagickTrue;
cache_info->pixels=(PixelPacket *) MapBlob(-1,IOMode,0,(size_t)
cache_info->length);
}
if (cache_info->pixels == (PixelPacket *) NULL)
{
cache_info->mapped=source_info.mapped;
cache_info->pixels=source_info.pixels;
}
else
{
/*
Create memory pixel cache.
*/
cache_info->colorspace=image->colorspace;
cache_info->type=MemoryCache;
cache_info->indexes=(IndexPacket *) NULL;
if (cache_info->active_index_channel != MagickFalse)
cache_info->indexes=(IndexPacket *) (cache_info->pixels+
number_pixels);
if ((source_info.storage_class != UndefinedClass) &&
(mode != ReadMode))
{
status&=ClonePixelCacheRepository(cache_info,&source_info,
exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickTrue,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MaxTextExtent,
"open %s (%s %s, %.20gx%.20g %s)",cache_info->filename,
cache_info->mapped != MagickFalse ? "Anonymous" : "Heap",
type,(double) cache_info->columns,(double) cache_info->rows,
format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",
message);
}
cache_info->storage_class=image->storage_class;
if (status == 0)
{
cache_info->type=UndefinedCache;
return(MagickFalse);
}
return(MagickTrue);
}
}
}
status=AcquireMagickResource(DiskResource,cache_info->length);
hosts=(const char *) GetImageRegistry(StringRegistryType,"cache:hosts",
exception);
if ((status == MagickFalse) && (hosts != (const char *) NULL))
{
DistributeCacheInfo
*server_info;
/*
Distribute the pixel cache to a remote server.
*/
server_info=AcquireDistributeCacheInfo(exception);
if (server_info != (DistributeCacheInfo *) NULL)
{
status=OpenDistributePixelCache(server_info,image);
if (status == MagickFalse)
{
ThrowFileException(exception,CacheError,"UnableToOpenPixelCache",
GetDistributeCacheHostname(server_info));
server_info=DestroyDistributeCacheInfo(server_info);
}
else
{
/*
Create a distributed pixel cache.
*/
status=MagickTrue;
cache_info->type=DistributedCache;
cache_info->storage_class=image->storage_class;
cache_info->colorspace=image->colorspace;
cache_info->server_info=server_info;
(void) FormatLocaleString(cache_info->cache_filename,
MaxTextExtent,"%s:%d",GetDistributeCacheHostname(
(DistributeCacheInfo *) cache_info->server_info),
GetDistributeCachePort((DistributeCacheInfo *)
cache_info->server_info));
if ((source_info.storage_class != UndefinedClass) &&
(mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,
exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickFalse,
format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MaxTextExtent,
"open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename,
cache_info->cache_filename,GetDistributeCacheFile(
(DistributeCacheInfo *) cache_info->server_info),type,
(double) cache_info->columns,(double) cache_info->rows,
format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",
message);
}
if (status == 0)
{
cache_info->type=UndefinedCache;
return(MagickFalse);
}
return(MagickTrue);
}
}
cache_info->type=UndefinedCache;
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"CacheResourcesExhausted","`%s'",image->filename);
return(MagickFalse);
}
/*
Create pixel cache on disk.
*/
if (status == MagickFalse)
{
cache_info->type=UndefinedCache;
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"CacheResourcesExhausted","`%s'",image->filename);
return(MagickFalse);
}
if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode) &&
(cache_info->mode != PersistMode))
{
(void) ClosePixelCacheOnDisk(cache_info);
*cache_info->cache_filename='\0';
}
if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse)
{
cache_info->type=UndefinedCache;
ThrowFileException(exception,CacheError,"UnableToOpenPixelCache",
image->filename);
return(MagickFalse);
}
status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+
cache_info->length);
if (status == MagickFalse)
{
cache_info->type=UndefinedCache;
ThrowFileException(exception,CacheError,"UnableToExtendCache",
image->filename);
return(MagickFalse);
}
cache_info->storage_class=image->storage_class;
cache_info->colorspace=image->colorspace;
cache_info->type=DiskCache;
length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket));
if (length == (MagickSizeType) ((size_t) length))
{
status=AcquireMagickResource(MapResource,cache_info->length);
if (status != MagickFalse)
{
cache_info->pixels=(PixelPacket *) MapBlob(cache_info->file,mode,
cache_info->offset,(size_t) cache_info->length);
if (cache_info->pixels == (PixelPacket *) NULL)
{
cache_info->mapped=source_info.mapped;
cache_info->pixels=source_info.pixels;
RelinquishMagickResource(MapResource,cache_info->length);
}
else
{
/*
Create file-backed memory-mapped pixel cache.
*/
(void) ClosePixelCacheOnDisk(cache_info);
cache_info->type=MapCache;
cache_info->mapped=MagickTrue;
cache_info->indexes=(IndexPacket *) NULL;
if (cache_info->active_index_channel != MagickFalse)
cache_info->indexes=(IndexPacket *) (cache_info->pixels+
number_pixels);
if ((source_info.storage_class != UndefinedClass) &&
(mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,
exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickTrue,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MaxTextExtent,
"open %s (%s[%d], %s, %.20gx%.20g %s)",
cache_info->filename,cache_info->cache_filename,
cache_info->file,type,(double) cache_info->columns,
(double) cache_info->rows,format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",
message);
}
if (status == 0)
{
cache_info->type=UndefinedCache;
return(MagickFalse);
}
return(MagickTrue);
}
}
}
status=MagickTrue;
if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode))
{
status=ClonePixelCacheRepository(cache_info,&source_info,exception);
RelinquishPixelCachePixels(&source_info);
}
if (image->debug != MagickFalse)
{
(void) FormatMagickSize(cache_info->length,MagickFalse,format);
type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t)
cache_info->type);
(void) FormatLocaleString(message,MaxTextExtent,
"open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename,
cache_info->cache_filename,cache_info->file,type,(double)
cache_info->columns,(double) cache_info->rows,format);
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
if (status == 0)
{
cache_info->type=UndefinedCache;
return(MagickFalse);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P e r s i s t P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PersistPixelCache() attaches to or initializes a persistent pixel cache. A
% persistent pixel cache is one that resides on disk and is not destroyed
% when the program exits.
%
% The format of the PersistPixelCache() method is:
%
% MagickBooleanType PersistPixelCache(Image *image,const char *filename,
% const MagickBooleanType attach,MagickOffsetType *offset,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o filename: the persistent pixel cache filename.
%
% o attach: A value other than zero initializes the persistent pixel cache.
%
% o initialize: A value other than zero initializes the persistent pixel
% cache.
%
% o offset: the offset in the persistent cache to store pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType PersistPixelCache(Image *image,
const char *filename,const MagickBooleanType attach,MagickOffsetType *offset,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info,
*magick_restrict clone_info;
MagickBooleanType
status;
ssize_t
page_size;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(image->cache != (void *) NULL);
assert(filename != (const char *) NULL);
assert(offset != (MagickOffsetType *) NULL);
page_size=GetMagickPageSize();
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
CopyOpenCLBuffer(cache_info);
#endif
if (attach != MagickFalse)
{
/*
Attach existing persistent pixel cache.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CacheEvent,GetMagickModule(),
"attach persistent cache");
(void) CopyMagickString(cache_info->cache_filename,filename,
MaxTextExtent);
cache_info->type=MapCache;
cache_info->offset=(*offset);
if (OpenPixelCache(image,ReadMode,exception) == MagickFalse)
return(MagickFalse);
*offset+=cache_info->length+page_size-(cache_info->length % page_size);
return(MagickTrue);
}
/*
Clone persistent pixel cache.
*/
status=AcquireMagickResource(DiskResource,cache_info->length);
if (status == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"CacheResourcesExhausted","`%s'",image->filename);
return(MagickFalse);
}
clone_info=(CacheInfo *) ClonePixelCache(cache_info);
clone_info->type=DiskCache;
(void) CopyMagickString(clone_info->cache_filename,filename,MaxTextExtent);
clone_info->file=(-1);
clone_info->storage_class=cache_info->storage_class;
clone_info->colorspace=cache_info->colorspace;
clone_info->columns=cache_info->columns;
clone_info->rows=cache_info->rows;
clone_info->active_index_channel=cache_info->active_index_channel;
clone_info->mode=PersistMode;
clone_info->length=cache_info->length;
clone_info->channels=cache_info->channels;
clone_info->offset=(*offset);
status=ClonePixelCacheRepository(clone_info,cache_info,exception);
*offset+=cache_info->length+page_size-(cache_info->length % page_size);
clone_info=(CacheInfo *) DestroyPixelCache(clone_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ Q u e u e A u t h e n t i c P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QueueAuthenticPixelCacheNexus() allocates an region to store image pixels as
% defined by the region rectangle and returns a pointer to the region. This
% region is subsequently transferred from the pixel cache with
% SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the
% pixels are transferred, otherwise a NULL is returned.
%
% The format of the QueueAuthenticPixelCacheNexus() method is:
%
% PixelPacket *QueueAuthenticPixelCacheNexus(Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% const MagickBooleanType clone,NexusInfo *nexus_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o nexus_info: the cache nexus to set.
%
% o clone: clone the pixel cache.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport PixelPacket *QueueAuthenticPixel(Image *image,const ssize_t x,
const ssize_t y,const size_t columns,const size_t rows,
const MagickBooleanType clone,NexusInfo *nexus_info,
ExceptionInfo *exception)
{
return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,clone,nexus_info,
exception));
}
MagickExport PixelPacket *QueueAuthenticPixelCacheNexus(Image *image,
const ssize_t x,const ssize_t y,const size_t columns,const size_t rows,
const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
MagickOffsetType
offset;
MagickSizeType
number_pixels;
PixelPacket
*magick_restrict pixels;
/*
Validate pixel cache geometry.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception);
if (cache_info == (Cache) NULL)
return((PixelPacket *) NULL);
assert(cache_info->signature == MagickCoreSignature);
if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) ||
(y < 0) || (x >= (ssize_t) cache_info->columns) ||
(y >= (ssize_t) cache_info->rows))
{
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"PixelsAreNotAuthentic","`%s'",image->filename);
return((PixelPacket *) NULL);
}
offset=(MagickOffsetType) y*cache_info->columns+x;
if (offset < 0)
return((PixelPacket *) NULL);
number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows;
offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1;
if ((MagickSizeType) offset >= number_pixels)
return((PixelPacket *) NULL);
/*
Return pixel cache.
*/
pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,x,y,columns,rows,
(image->clip_mask != (Image *) NULL) || (image->mask != (Image *) NULL) ?
MagickTrue : MagickFalse,nexus_info,exception);
return(pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ Q u e u e A u t h e n t i c P i x e l s C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QueueAuthenticPixelsCache() allocates an region to store image pixels as
% defined by the region rectangle and returns a pointer to the region. This
% region is subsequently transferred from the pixel cache with
% SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the
% pixels are transferred, otherwise a NULL is returned.
%
% The format of the QueueAuthenticPixelsCache() method is:
%
% PixelPacket *QueueAuthenticPixelsCache(Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static PixelPacket *QueueAuthenticPixelsCache(Image *image,const ssize_t x,
const ssize_t y,const size_t columns,const size_t rows,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse,
cache_info->nexus_info[id],exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% Q u e u e A u t h e n t i c P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QueueAuthenticPixels() queues a mutable pixel region. If the region is
% successfully initialized a pointer to a PixelPacket array representing the
% region is returned, otherwise NULL is returned. The returned pointer may
% point to a temporary working buffer for the pixels or it may point to the
% final location of the pixels in memory.
%
% Write-only access means that any existing pixel values corresponding to
% the region are ignored. This is useful if the initial image is being
% created from scratch, or if the existing pixel values are to be
% completely replaced without need to refer to their pre-existing values.
% The application is free to read and write the pixel buffer returned by
% QueueAuthenticPixels() any way it pleases. QueueAuthenticPixels() does not
% initialize the pixel array values. Initializing pixel array values is the
% application's responsibility.
%
% Performance is maximized if the selected region is part of one row, or
% one or more full rows, since then there is opportunity to access the
% pixels in-place (without a copy) if the image is in memory, or in a
% memory-mapped file. The returned pointer must *never* be deallocated
% by the user.
%
% Pixels accessed via the returned pointer represent a simple array of type
% PixelPacket. If the image type is CMYK or the storage class is PseudoClass,
% call GetAuthenticIndexQueue() after invoking GetAuthenticPixels() to obtain
% the black color component or the colormap indexes (of type IndexPacket)
% corresponding to the region. Once the PixelPacket (and/or IndexPacket)
% array has been updated, the changes must be saved back to the underlying
% image using SyncAuthenticPixels() or they may be lost.
%
% The format of the QueueAuthenticPixels() method is:
%
% PixelPacket *QueueAuthenticPixels(Image *image,const ssize_t x,
% const ssize_t y,const size_t columns,const size_t rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,columns,rows: These values define the perimeter of a region of
% pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport PixelPacket *QueueAuthenticPixels(Image *image,const ssize_t x,
const ssize_t y,const size_t columns,const size_t rows,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.queue_authentic_pixels_handler !=
(QueueAuthenticPixelsHandler) NULL)
return(cache_info->methods.queue_authentic_pixels_handler(image,x,y,columns,
rows,exception));
assert(id < (int) cache_info->number_threads);
return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse,
cache_info->nexus_info[id],exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e a d P i x e l C a c h e I n d e x e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPixelCacheIndexes() reads colormap indexes from the specified region of
% the pixel cache.
%
% The format of the ReadPixelCacheIndexes() method is:
%
% MagickBooleanType ReadPixelCacheIndexes(CacheInfo *cache_info,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
% o nexus_info: the cache nexus to read the colormap indexes.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline MagickOffsetType ReadPixelCacheRegion(
const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset,
const MagickSizeType length,unsigned char *magick_restrict buffer)
{
register MagickOffsetType
i;
ssize_t
count;
#if !defined(MAGICKCORE_HAVE_PREAD)
if (lseek(cache_info->file,offset,SEEK_SET) < 0)
return((MagickOffsetType) -1);
#endif
count=0;
for (i=0; i < (MagickOffsetType) length; i+=count)
{
#if !defined(MAGICKCORE_HAVE_PREAD)
count=read(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t)
SSIZE_MAX));
#else
count=pread(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t)
SSIZE_MAX),offset+i);
#endif
if (count <= 0)
{
count=0;
if (errno != EINTR)
break;
}
}
return(i);
}
static MagickBooleanType ReadPixelCacheIndexes(
CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info,
ExceptionInfo *exception)
{
MagickOffsetType
count,
offset;
MagickSizeType
extent,
length;
register IndexPacket
*magick_restrict q;
register ssize_t
y;
size_t
rows;
if (cache_info->active_index_channel == MagickFalse)
return(MagickFalse);
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(MagickTrue);
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+
nexus_info->region.x;
length=(MagickSizeType) nexus_info->region.width*sizeof(IndexPacket);
rows=nexus_info->region.height;
extent=length*rows;
q=nexus_info->indexes;
y=0;
switch (cache_info->type)
{
case MemoryCache:
case MapCache:
{
register IndexPacket
*magick_restrict p;
/*
Read indexes from memory.
*/
if ((cache_info->columns == nexus_info->region.width) &&
(extent == (MagickSizeType) ((size_t) extent)))
{
length=extent;
rows=1UL;
}
p=cache_info->indexes+offset;
for (y=0; y < (ssize_t) rows; y++)
{
(void) memcpy(q,p,(size_t) length);
p+=cache_info->columns;
q+=nexus_info->region.width;
}
break;
}
case DiskCache:
{
/*
Read indexes from disk.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
cache_info->cache_filename);
UnlockSemaphoreInfo(cache_info->file_semaphore);
return(MagickFalse);
}
if ((cache_info->columns == nexus_info->region.width) &&
(extent <= MagickMaxBufferExtent))
{
length=extent;
rows=1UL;
}
extent=(MagickSizeType) cache_info->columns*cache_info->rows;
for (y=0; y < (ssize_t) rows; y++)
{
count=ReadPixelCacheRegion(cache_info,cache_info->offset+extent*
sizeof(PixelPacket)+offset*sizeof(*q),length,(unsigned char *) q);
if (count < (MagickOffsetType) length)
break;
offset+=cache_info->columns;
q+=nexus_info->region.width;
}
if (IsFileDescriptorLimitExceeded() != MagickFalse)
(void) ClosePixelCacheOnDisk(cache_info);
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
case DistributedCache:
{
RectangleInfo
region;
/*
Read indexes from distributed cache.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
region=nexus_info->region;
if ((cache_info->columns != nexus_info->region.width) ||
(extent > MagickMaxBufferExtent))
region.height=1UL;
else
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=ReadDistributePixelCacheIndexes((DistributeCacheInfo *)
cache_info->server_info,®ion,length,(unsigned char *) q);
if (count != (MagickOffsetType) length)
break;
q+=nexus_info->region.width;
region.y++;
}
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
default:
break;
}
if (y < (ssize_t) rows)
{
ThrowFileException(exception,CacheError,"UnableToReadPixelCache",
cache_info->cache_filename);
return(MagickFalse);
}
if ((cache_info->debug != MagickFalse) &&
(CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse))
(void) LogMagickEvent(CacheEvent,GetMagickModule(),
"%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double)
nexus_info->region.width,(double) nexus_info->region.height,(double)
nexus_info->region.x,(double) nexus_info->region.y);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e a d P i x e l C a c h e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPixelCachePixels() reads pixels from the specified region of the pixel
% cache.
%
% The format of the ReadPixelCachePixels() method is:
%
% MagickBooleanType ReadPixelCachePixels(CacheInfo *cache_info,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
% o nexus_info: the cache nexus to read the pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType ReadPixelCachePixels(
CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info,
ExceptionInfo *exception)
{
MagickOffsetType
count,
offset;
MagickSizeType
extent,
length;
register PixelPacket
*magick_restrict q;
register ssize_t
y;
size_t
rows;
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(MagickTrue);
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns;
if ((ssize_t) (offset/cache_info->columns) != nexus_info->region.y)
return(MagickFalse);
offset+=nexus_info->region.x;
length=(MagickSizeType) nexus_info->region.width*sizeof(PixelPacket);
if ((length/sizeof(PixelPacket)) != nexus_info->region.width)
return(MagickFalse);
rows=nexus_info->region.height;
extent=length*rows;
if ((extent == 0) || ((extent/length) != rows))
return(MagickFalse);
q=nexus_info->pixels;
y=0;
switch (cache_info->type)
{
case MemoryCache:
case MapCache:
{
register PixelPacket
*magick_restrict p;
/*
Read pixels from memory.
*/
if ((cache_info->columns == nexus_info->region.width) &&
(extent == (MagickSizeType) ((size_t) extent)))
{
length=extent;
rows=1UL;
}
p=cache_info->pixels+offset;
for (y=0; y < (ssize_t) rows; y++)
{
(void) memcpy(q,p,(size_t) length);
p+=cache_info->columns;
q+=nexus_info->region.width;
}
break;
}
case DiskCache:
{
/*
Read pixels from disk.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
cache_info->cache_filename);
UnlockSemaphoreInfo(cache_info->file_semaphore);
return(MagickFalse);
}
if ((cache_info->columns == nexus_info->region.width) &&
(extent <= MagickMaxBufferExtent))
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=ReadPixelCacheRegion(cache_info,cache_info->offset+offset*
sizeof(*q),length,(unsigned char *) q);
if (count < (MagickOffsetType) length)
break;
offset+=cache_info->columns;
q+=nexus_info->region.width;
}
if (IsFileDescriptorLimitExceeded() != MagickFalse)
(void) ClosePixelCacheOnDisk(cache_info);
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
case DistributedCache:
{
RectangleInfo
region;
/*
Read pixels from distributed cache.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
region=nexus_info->region;
if ((cache_info->columns != nexus_info->region.width) ||
(extent > MagickMaxBufferExtent))
region.height=1UL;
else
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=ReadDistributePixelCachePixels((DistributeCacheInfo *)
cache_info->server_info,®ion,length,(unsigned char *) q);
if (count != (MagickOffsetType) length)
break;
q+=nexus_info->region.width;
region.y++;
}
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
default:
break;
}
if (y < (ssize_t) rows)
{
ThrowFileException(exception,CacheError,"UnableToReadPixelCache",
cache_info->cache_filename);
return(MagickFalse);
}
if ((cache_info->debug != MagickFalse) &&
(CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse))
(void) LogMagickEvent(CacheEvent,GetMagickModule(),
"%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double)
nexus_info->region.width,(double) nexus_info->region.height,(double)
nexus_info->region.x,(double) nexus_info->region.y);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e f e r e n c e P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReferencePixelCache() increments the reference count associated with the
% pixel cache returning a pointer to the cache.
%
% The format of the ReferencePixelCache method is:
%
% Cache ReferencePixelCache(Cache cache_info)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
*/
MagickExport Cache ReferencePixelCache(Cache cache)
{
CacheInfo
*magick_restrict cache_info;
assert(cache != (Cache *) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
LockSemaphoreInfo(cache_info->semaphore);
cache_info->reference_count++;
UnlockSemaphoreInfo(cache_info->semaphore);
return(cache_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e s e t P i x e l C a c h e E p o c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetPixelCacheEpoch() resets the pixel cache epoch.
%
% The format of the ResetPixelCacheEpoch method is:
%
% void ResetPixelCacheEpoch(void)
%
*/
MagickPrivate void ResetPixelCacheEpoch(void)
{
cache_epoch=0;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S e t P i x e l C a c h e M e t h o d s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetPixelCacheMethods() sets the image pixel methods to the specified ones.
%
% The format of the SetPixelCacheMethods() method is:
%
% SetPixelCacheMethods(Cache *,CacheMethods *cache_methods)
%
% A description of each parameter follows:
%
% o cache: the pixel cache.
%
% o cache_methods: Specifies a pointer to a CacheMethods structure.
%
*/
MagickExport void SetPixelCacheMethods(Cache cache,CacheMethods *cache_methods)
{
CacheInfo
*magick_restrict cache_info;
GetOneAuthenticPixelFromHandler
get_one_authentic_pixel_from_handler;
GetOneVirtualPixelFromHandler
get_one_virtual_pixel_from_handler;
/*
Set cache pixel methods.
*/
assert(cache != (Cache) NULL);
assert(cache_methods != (CacheMethods *) NULL);
cache_info=(CacheInfo *) cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
cache_info->filename);
if (cache_methods->get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL)
cache_info->methods.get_virtual_pixel_handler=
cache_methods->get_virtual_pixel_handler;
if (cache_methods->destroy_pixel_handler != (DestroyPixelHandler) NULL)
cache_info->methods.destroy_pixel_handler=
cache_methods->destroy_pixel_handler;
if (cache_methods->get_virtual_indexes_from_handler !=
(GetVirtualIndexesFromHandler) NULL)
cache_info->methods.get_virtual_indexes_from_handler=
cache_methods->get_virtual_indexes_from_handler;
if (cache_methods->get_authentic_pixels_handler !=
(GetAuthenticPixelsHandler) NULL)
cache_info->methods.get_authentic_pixels_handler=
cache_methods->get_authentic_pixels_handler;
if (cache_methods->queue_authentic_pixels_handler !=
(QueueAuthenticPixelsHandler) NULL)
cache_info->methods.queue_authentic_pixels_handler=
cache_methods->queue_authentic_pixels_handler;
if (cache_methods->sync_authentic_pixels_handler !=
(SyncAuthenticPixelsHandler) NULL)
cache_info->methods.sync_authentic_pixels_handler=
cache_methods->sync_authentic_pixels_handler;
if (cache_methods->get_authentic_pixels_from_handler !=
(GetAuthenticPixelsFromHandler) NULL)
cache_info->methods.get_authentic_pixels_from_handler=
cache_methods->get_authentic_pixels_from_handler;
if (cache_methods->get_authentic_indexes_from_handler !=
(GetAuthenticIndexesFromHandler) NULL)
cache_info->methods.get_authentic_indexes_from_handler=
cache_methods->get_authentic_indexes_from_handler;
get_one_virtual_pixel_from_handler=
cache_info->methods.get_one_virtual_pixel_from_handler;
if (get_one_virtual_pixel_from_handler !=
(GetOneVirtualPixelFromHandler) NULL)
cache_info->methods.get_one_virtual_pixel_from_handler=
cache_methods->get_one_virtual_pixel_from_handler;
get_one_authentic_pixel_from_handler=
cache_methods->get_one_authentic_pixel_from_handler;
if (get_one_authentic_pixel_from_handler !=
(GetOneAuthenticPixelFromHandler) NULL)
cache_info->methods.get_one_authentic_pixel_from_handler=
cache_methods->get_one_authentic_pixel_from_handler;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S e t P i x e l C a c h e N e x u s P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetPixelCacheNexusPixels() defines the region of the cache for the
% specified cache nexus.
%
% The format of the SetPixelCacheNexusPixels() method is:
%
% PixelPacket SetPixelCacheNexusPixels(
% const CacheInfo *magick_restrcit cache_info,const MapMode mode,
% const ssize_t y,const size_t width,const size_t height,
% const MagickBooleanType buffered,NexusInfo *magick_restrict nexus_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
% o mode: ReadMode, WriteMode, or IOMode.
%
% o x,y,width,height: define the region of this particular cache nexus.
%
% o buffered: pixels are buffered.
%
% o nexus_info: the cache nexus to set.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline MagickBooleanType AcquireCacheNexusPixels(
const CacheInfo *magick_restrict cache_info,const MagickSizeType length,
NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception)
{
if (length != (MagickSizeType) ((size_t) length))
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"PixelCacheAllocationFailed","`%s'",
cache_info->filename);
return(MagickFalse);
}
nexus_info->length=0;
nexus_info->mapped=MagickFalse;
if (cache_anonymous_memory <= 0)
{
nexus_info->cache=(PixelPacket *) MagickAssumeAligned(
AcquireAlignedMemory(1,(size_t) length));
if (nexus_info->cache != (PixelPacket *) NULL)
(void) memset(nexus_info->cache,0,(size_t) length);
}
else
{
nexus_info->cache=(PixelPacket *) MapBlob(-1,IOMode,0,(size_t) length);
if (nexus_info->cache != (PixelPacket *) NULL)
nexus_info->mapped=MagickTrue;
}
if (nexus_info->cache == (PixelPacket *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"PixelCacheAllocationFailed","`%s'",
cache_info->filename);
return(MagickFalse);
}
nexus_info->length=length;
return(MagickTrue);
}
static inline void PrefetchPixelCacheNexusPixels(const NexusInfo *nexus_info,
const MapMode mode)
{
if (nexus_info->length < CACHE_LINE_SIZE)
return;
if (mode == ReadMode)
{
MagickCachePrefetch((unsigned char *) nexus_info->pixels+CACHE_LINE_SIZE,
0,1);
return;
}
MagickCachePrefetch((unsigned char *) nexus_info->pixels+CACHE_LINE_SIZE,1,1);
}
static PixelPacket *SetPixelCacheNexusPixels(
const CacheInfo *magick_restrict cache_info,const MapMode mode,
const ssize_t x,const ssize_t y,const size_t width,const size_t height,
const MagickBooleanType buffered,NexusInfo *magick_restrict nexus_info,
ExceptionInfo *exception)
{
MagickBooleanType
status;
MagickSizeType
length,
number_pixels;
assert(cache_info != (const CacheInfo *) NULL);
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->type == UndefinedCache)
return((PixelPacket *) NULL);
assert(nexus_info->signature == MagickCoreSignature);
(void) memset(&nexus_info->region,0,sizeof(nexus_info->region));
if ((width == 0) || (height == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CacheError,
"NoPixelsDefinedInCache","`%s'",cache_info->filename);
return((PixelPacket *) NULL);
}
if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) &&
(buffered == MagickFalse))
{
if (((x >= 0) && (y >= 0) &&
(((ssize_t) height+y-1) < (ssize_t) cache_info->rows)) &&
(((x == 0) && (width == cache_info->columns)) || ((height == 1) &&
(((ssize_t) width+x-1) < (ssize_t) cache_info->columns))))
{
MagickOffsetType
offset;
/*
Pixels are accessed directly from memory.
*/
offset=(MagickOffsetType) y*cache_info->columns+x;
nexus_info->pixels=cache_info->pixels+offset;
nexus_info->indexes=(IndexPacket *) NULL;
if (cache_info->active_index_channel != MagickFalse)
nexus_info->indexes=cache_info->indexes+offset;
nexus_info->region.width=width;
nexus_info->region.height=height;
nexus_info->region.x=x;
nexus_info->region.y=y;
nexus_info->authentic_pixel_cache=MagickTrue;
PrefetchPixelCacheNexusPixels(nexus_info,mode);
return(nexus_info->pixels);
}
}
/*
Pixels are stored in a staging region until they are synced to the cache.
*/
if (((MagickSizeType) width > cache_info->width_limit) ||
((MagickSizeType) height > cache_info->height_limit))
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"WidthOrHeightExceedsLimit","`%s'",cache_info->filename);
return((PixelPacket *) NULL);
}
number_pixels=(MagickSizeType) width*height;
length=MagickMax(number_pixels,MagickMax(cache_info->columns,
cache_info->rows))*sizeof(PixelPacket);
if (cache_info->active_index_channel != MagickFalse)
length+=number_pixels*sizeof(IndexPacket);
status=MagickTrue;
if (nexus_info->cache == (PixelPacket *) NULL)
status=AcquireCacheNexusPixels(cache_info,length,nexus_info,exception);
else
if (nexus_info->length < length)
{
RelinquishCacheNexusPixels(nexus_info);
status=AcquireCacheNexusPixels(cache_info,length,nexus_info,exception);
}
if (status == MagickFalse)
{
(void) memset(&nexus_info->region,0,sizeof(nexus_info->region));
return((PixelPacket *) NULL);
}
nexus_info->pixels=nexus_info->cache;
nexus_info->indexes=(IndexPacket *) NULL;
if (cache_info->active_index_channel != MagickFalse)
nexus_info->indexes=(IndexPacket *) (nexus_info->pixels+number_pixels);
nexus_info->region.width=width;
nexus_info->region.height=height;
nexus_info->region.x=x;
nexus_info->region.y=y;
nexus_info->authentic_pixel_cache=cache_info->type == PingCache ?
MagickTrue : MagickFalse;
PrefetchPixelCacheNexusPixels(nexus_info,mode);
return(nexus_info->pixels);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t P i x e l C a c h e V i r t u a l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetPixelCacheVirtualMethod() sets the "virtual pixels" method for the
% pixel cache 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 SetPixelCacheVirtualMethod() method is:
%
% VirtualPixelMethod SetPixelCacheVirtualMethod(const Image *image,
% const VirtualPixelMethod virtual_pixel_method)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: choose the type of virtual pixel.
%
*/
static MagickBooleanType SetCacheAlphaChannel(Image *image,
const Quantum opacity)
{
CacheInfo
*magick_restrict cache_info;
CacheView
*magick_restrict 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);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
image->matte=MagickTrue;
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,&image->exception); /* must be virtual */
#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 PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
&image->exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
q->opacity=opacity;
q++;
}
status=SyncCacheViewAuthenticPixels(image_view,&image->exception);
}
image_view=DestroyCacheView(image_view);
return(status);
}
MagickExport VirtualPixelMethod SetPixelCacheVirtualMethod(const Image *image,
const VirtualPixelMethod virtual_pixel_method)
{
CacheInfo
*magick_restrict cache_info;
VirtualPixelMethod
method;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
method=cache_info->virtual_pixel_method;
cache_info->virtual_pixel_method=virtual_pixel_method;
if ((image->columns != 0) && (image->rows != 0))
switch (virtual_pixel_method)
{
case BackgroundVirtualPixelMethod:
{
if ((image->background_color.opacity != OpaqueOpacity) &&
(image->matte == MagickFalse))
(void) SetCacheAlphaChannel((Image *) image,OpaqueOpacity);
if ((IsPixelGray(&image->background_color) == MagickFalse) &&
(IsGrayColorspace(image->colorspace) != MagickFalse))
(void) SetImageColorspace((Image *) image,sRGBColorspace);
break;
}
case TransparentVirtualPixelMethod:
{
if (image->matte == MagickFalse)
(void) SetCacheAlphaChannel((Image *) image,OpaqueOpacity);
break;
}
default:
break;
}
return(method);
}
#if defined(MAGICKCORE_OPENCL_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S y n c A u t h e n t i c O p e n C L B u f f e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncAuthenticOpenCLBuffer() ensures all the OpenCL operations have been
% completed and updates the host memory.
%
% The format of the SyncAuthenticOpenCLBuffer() method is:
%
% void SyncAuthenticOpenCLBuffer(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static void CopyOpenCLBuffer(CacheInfo *magick_restrict cache_info)
{
MagickCLEnv
clEnv;
assert(cache_info != (CacheInfo *)NULL);
if ((cache_info->type != MemoryCache) ||
(cache_info->opencl == (OpenCLCacheInfo *)NULL))
return;
/*
Ensure single threaded access to OpenCL environment.
*/
LockSemaphoreInfo(cache_info->semaphore);
if (cache_info->opencl != (OpenCLCacheInfo *)NULL)
{
cl_event
*events;
cl_uint
event_count;
clEnv=GetDefaultOpenCLEnv();
events=CopyOpenCLEvents(cache_info->opencl,&event_count);
if (events != (cl_event *) NULL)
{
cl_command_queue
queue;
cl_context
context;
cl_int
status;
PixelPacket
*pixels;
context=GetOpenCLContext(clEnv);
queue=AcquireOpenCLCommandQueue(clEnv);
pixels=(PixelPacket *) clEnv->library->clEnqueueMapBuffer(queue,
cache_info->opencl->buffer,CL_TRUE, CL_MAP_READ | CL_MAP_WRITE,0,
cache_info->length,event_count,events,NULL,&status);
assert(pixels == cache_info->pixels);
events=(cl_event *) RelinquishMagickMemory(events);
RelinquishOpenCLCommandQueue(clEnv,queue);
}
cache_info->opencl=RelinquishOpenCLCacheInfo(clEnv,cache_info->opencl);
}
UnlockSemaphoreInfo(cache_info->semaphore);
}
MagickPrivate void SyncAuthenticOpenCLBuffer(const Image *image)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (Image *)NULL);
cache_info = (CacheInfo *)image->cache;
CopyOpenCLBuffer(cache_info);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S y n c A u t h e n t i c P i x e l C a c h e N e x u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncAuthenticPixelCacheNexus() saves the authentic image pixels to the
% in-memory or disk cache. The method returns MagickTrue if the pixel region
% is synced, otherwise MagickFalse.
%
% The format of the SyncAuthenticPixelCacheNexus() method is:
%
% MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o nexus_info: the cache nexus to sync.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image,
NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
MagickBooleanType
status;
/*
Transfer pixels to the cache.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->cache == (Cache) NULL)
ThrowBinaryException(CacheError,"PixelCacheIsNotOpen",image->filename);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->type == UndefinedCache)
return(MagickFalse);
if ((image->storage_class == DirectClass) &&
(image->clip_mask != (Image *) NULL) &&
(ClipPixelCacheNexus(image,nexus_info,exception) == MagickFalse))
return(MagickFalse);
if ((image->storage_class == DirectClass) &&
(image->mask != (Image *) NULL) &&
(MaskPixelCacheNexus(image,nexus_info,exception) == MagickFalse))
return(MagickFalse);
if (nexus_info->authentic_pixel_cache != MagickFalse)
{
if (image->taint == MagickFalse)
image->taint=MagickTrue;
return(MagickTrue);
}
assert(cache_info->signature == MagickCoreSignature);
status=WritePixelCachePixels(cache_info,nexus_info,exception);
if ((cache_info->active_index_channel != MagickFalse) &&
(WritePixelCacheIndexes(cache_info,nexus_info,exception) == MagickFalse))
return(MagickFalse);
if ((status != MagickFalse) && (image->taint == MagickFalse))
image->taint=MagickTrue;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S y n c A u t h e n t i c P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncAuthenticPixelsCache() saves the authentic image pixels to the in-memory
% or disk cache. The method returns MagickTrue if the pixel region is synced,
% otherwise MagickFalse.
%
% The format of the SyncAuthenticPixelsCache() method is:
%
% MagickBooleanType SyncAuthenticPixelsCache(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 MagickBooleanType SyncAuthenticPixelsCache(Image *image,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
assert(id < (int) cache_info->number_threads);
status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id],
exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S y n c A u t h e n t i c P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncAuthenticPixels() saves the image pixels to the in-memory or disk cache.
% The method returns MagickTrue if the pixel region is flushed, otherwise
% MagickFalse.
%
% The format of the SyncAuthenticPixels() method is:
%
% MagickBooleanType SyncAuthenticPixels(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 SyncAuthenticPixels(Image *image,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
const int
id = GetOpenMPThreadId();
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image->cache != (Cache) NULL);
cache_info=(CacheInfo *) image->cache;
assert(cache_info->signature == MagickCoreSignature);
if (cache_info->methods.sync_authentic_pixels_handler !=
(SyncAuthenticPixelsHandler) NULL)
return(cache_info->methods.sync_authentic_pixels_handler(image,exception));
assert(id < (int) cache_info->number_threads);
status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id],
exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S y n c I m a g e P i x e l C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImagePixelCache() saves the image pixels to the in-memory or disk cache.
% The method returns MagickTrue if the pixel region is flushed, otherwise
% MagickFalse.
%
% The format of the SyncImagePixelCache() method is:
%
% MagickBooleanType SyncImagePixelCache(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickPrivate MagickBooleanType SyncImagePixelCache(Image *image,
ExceptionInfo *exception)
{
CacheInfo
*magick_restrict cache_info;
assert(image != (Image *) NULL);
assert(exception != (ExceptionInfo *) NULL);
cache_info=(CacheInfo *) GetImagePixelCache(image,MagickTrue,exception);
return(cache_info == (CacheInfo *) NULL ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ W r i t e P i x e l C a c h e I n d e x e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePixelCacheIndexes() writes the colormap indexes to the specified
% region of the pixel cache.
%
% The format of the WritePixelCacheIndexes() method is:
%
% MagickBooleanType WritePixelCacheIndexes(CacheInfo *cache_info,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
% o nexus_info: the cache nexus to write the colormap indexes.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WritePixelCacheIndexes(CacheInfo *cache_info,
NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception)
{
MagickOffsetType
count,
offset;
MagickSizeType
extent,
length;
register const IndexPacket
*magick_restrict p;
register ssize_t
y;
size_t
rows;
if (cache_info->active_index_channel == MagickFalse)
return(MagickFalse);
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(MagickTrue);
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+
nexus_info->region.x;
length=(MagickSizeType) nexus_info->region.width*sizeof(IndexPacket);
rows=nexus_info->region.height;
extent=(MagickSizeType) length*rows;
p=nexus_info->indexes;
y=0;
switch (cache_info->type)
{
case MemoryCache:
case MapCache:
{
register IndexPacket
*magick_restrict q;
/*
Write indexes to memory.
*/
if ((cache_info->columns == nexus_info->region.width) &&
(extent == (MagickSizeType) ((size_t) extent)))
{
length=extent;
rows=1UL;
}
q=cache_info->indexes+offset;
for (y=0; y < (ssize_t) rows; y++)
{
(void) memcpy(q,p,(size_t) length);
p+=nexus_info->region.width;
q+=cache_info->columns;
}
break;
}
case DiskCache:
{
/*
Write indexes to disk.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
cache_info->cache_filename);
UnlockSemaphoreInfo(cache_info->file_semaphore);
return(MagickFalse);
}
if ((cache_info->columns == nexus_info->region.width) &&
(extent <= MagickMaxBufferExtent))
{
length=extent;
rows=1UL;
}
extent=(MagickSizeType) cache_info->columns*cache_info->rows;
for (y=0; y < (ssize_t) rows; y++)
{
count=WritePixelCacheRegion(cache_info,cache_info->offset+extent*
sizeof(PixelPacket)+offset*sizeof(*p),length,(const unsigned char *)
p);
if (count < (MagickOffsetType) length)
break;
p+=nexus_info->region.width;
offset+=cache_info->columns;
}
if (IsFileDescriptorLimitExceeded() != MagickFalse)
(void) ClosePixelCacheOnDisk(cache_info);
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
case DistributedCache:
{
RectangleInfo
region;
/*
Write indexes to distributed cache.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
region=nexus_info->region;
if ((cache_info->columns != nexus_info->region.width) ||
(extent > MagickMaxBufferExtent))
region.height=1UL;
else
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=WriteDistributePixelCacheIndexes((DistributeCacheInfo *)
cache_info->server_info,®ion,length,(const unsigned char *) p);
if (count != (MagickOffsetType) length)
break;
p+=nexus_info->region.width;
region.y++;
}
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
default:
break;
}
if (y < (ssize_t) rows)
{
ThrowFileException(exception,CacheError,"UnableToWritePixelCache",
cache_info->cache_filename);
return(MagickFalse);
}
if ((cache_info->debug != MagickFalse) &&
(CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse))
(void) LogMagickEvent(CacheEvent,GetMagickModule(),
"%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double)
nexus_info->region.width,(double) nexus_info->region.height,(double)
nexus_info->region.x,(double) nexus_info->region.y);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ W r i t e P i x e l C a c h e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePixelCachePixels() writes image pixels to the specified region of the
% pixel cache.
%
% The format of the WritePixelCachePixels() method is:
%
% MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info,
% NexusInfo *nexus_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o cache_info: the pixel cache.
%
% o nexus_info: the cache nexus to write the pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info,
NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception)
{
MagickOffsetType
count,
offset;
MagickSizeType
extent,
length;
register const PixelPacket
*magick_restrict p;
register ssize_t
y;
size_t
rows;
if (nexus_info->authentic_pixel_cache != MagickFalse)
return(MagickTrue);
offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+
nexus_info->region.x;
length=(MagickSizeType) nexus_info->region.width*sizeof(PixelPacket);
rows=nexus_info->region.height;
extent=length*rows;
p=nexus_info->pixels;
y=0;
switch (cache_info->type)
{
case MemoryCache:
case MapCache:
{
register PixelPacket
*magick_restrict q;
/*
Write pixels to memory.
*/
if ((cache_info->columns == nexus_info->region.width) &&
(extent == (MagickSizeType) ((size_t) extent)))
{
length=extent;
rows=1UL;
}
q=cache_info->pixels+offset;
for (y=0; y < (ssize_t) rows; y++)
{
(void) memcpy(q,p,(size_t) length);
p+=nexus_info->region.width;
q+=cache_info->columns;
}
break;
}
case DiskCache:
{
/*
Write pixels to disk.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
cache_info->cache_filename);
UnlockSemaphoreInfo(cache_info->file_semaphore);
return(MagickFalse);
}
if ((cache_info->columns == nexus_info->region.width) &&
(extent <= MagickMaxBufferExtent))
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=WritePixelCacheRegion(cache_info,cache_info->offset+offset*
sizeof(*p),length,(const unsigned char *) p);
if (count < (MagickOffsetType) length)
break;
p+=nexus_info->region.width;
offset+=cache_info->columns;
}
if (IsFileDescriptorLimitExceeded() != MagickFalse)
(void) ClosePixelCacheOnDisk(cache_info);
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
case DistributedCache:
{
RectangleInfo
region;
/*
Write pixels to distributed cache.
*/
LockSemaphoreInfo(cache_info->file_semaphore);
region=nexus_info->region;
if ((cache_info->columns != nexus_info->region.width) ||
(extent > MagickMaxBufferExtent))
region.height=1UL;
else
{
length=extent;
rows=1UL;
}
for (y=0; y < (ssize_t) rows; y++)
{
count=WriteDistributePixelCachePixels((DistributeCacheInfo *)
cache_info->server_info,®ion,length,(const unsigned char *) p);
if (count != (MagickOffsetType) length)
break;
p+=nexus_info->region.width;
region.y++;
}
UnlockSemaphoreInfo(cache_info->file_semaphore);
break;
}
default:
break;
}
if (y < (ssize_t) rows)
{
ThrowFileException(exception,CacheError,"UnableToWritePixelCache",
cache_info->cache_filename);
return(MagickFalse);
}
if ((cache_info->debug != MagickFalse) &&
(CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse))
(void) LogMagickEvent(CacheEvent,GetMagickModule(),
"%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double)
nexus_info->region.width,(double) nexus_info->region.height,(double)
nexus_info->region.x,(double) nexus_info->region.y);
return(MagickTrue);
}
|
HYPRE_parcsr_pcg.c | /******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
#include "_hypre_parcsr_ls.h"
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGCreate
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGCreate( MPI_Comm comm, HYPRE_Solver *solver )
{
hypre_PCGFunctions * pcg_functions;
if (!solver)
{
hypre_error_in_arg(2);
return hypre_error_flag;
}
pcg_functions =
hypre_PCGFunctionsCreate(
hypre_CAlloc, hypre_ParKrylovFree, hypre_ParKrylovCommInfo,
hypre_ParKrylovCreateVector,
hypre_ParKrylovDestroyVector, hypre_ParKrylovMatvecCreate,
hypre_ParKrylovMatvec, hypre_ParKrylovMatvecDestroy,
hypre_ParKrylovInnerProd, hypre_ParKrylovCopyVector,
hypre_ParKrylovClearVector,
hypre_ParKrylovScaleVector, hypre_ParKrylovAxpy,
hypre_ParKrylovIdentitySetup, hypre_ParKrylovIdentity );
*solver = ( (HYPRE_Solver) hypre_PCGCreate( pcg_functions ) );
return hypre_error_flag;
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGDestroy
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGDestroy( HYPRE_Solver solver )
{
return( hypre_PCGDestroy( (void *) solver ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGSetup
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGSetup( HYPRE_Solver solver,
HYPRE_ParCSRMatrix A,
HYPRE_ParVector b,
HYPRE_ParVector x )
{
return( HYPRE_PCGSetup( solver,
(HYPRE_Matrix) A,
(HYPRE_Vector) b,
(HYPRE_Vector) x ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGSolve
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGSolve( HYPRE_Solver solver,
HYPRE_ParCSRMatrix A,
HYPRE_ParVector b,
HYPRE_ParVector x )
{
return( HYPRE_PCGSolve( solver,
(HYPRE_Matrix) A,
(HYPRE_Vector) b,
(HYPRE_Vector) x ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGSetTol
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGSetTol( HYPRE_Solver solver,
HYPRE_Real tol )
{
return( HYPRE_PCGSetTol( solver, tol ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGSetAbsoluteTol
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGSetAbsoluteTol( HYPRE_Solver solver,
HYPRE_Real a_tol )
{
return( HYPRE_PCGSetAbsoluteTol( solver, a_tol ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGSetMaxIter
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGSetMaxIter( HYPRE_Solver solver,
HYPRE_Int max_iter )
{
return( HYPRE_PCGSetMaxIter( solver, max_iter ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGSetStopCrit
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGSetStopCrit( HYPRE_Solver solver,
HYPRE_Int stop_crit )
{
return( HYPRE_PCGSetStopCrit( solver, stop_crit ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGSetTwoNorm
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGSetTwoNorm( HYPRE_Solver solver,
HYPRE_Int two_norm )
{
return( HYPRE_PCGSetTwoNorm( solver, two_norm ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGSetRelChange
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGSetRelChange( HYPRE_Solver solver,
HYPRE_Int rel_change )
{
return( HYPRE_PCGSetRelChange( solver, rel_change ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGSetPrecond
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGSetPrecond( HYPRE_Solver solver,
HYPRE_PtrToParSolverFcn precond,
HYPRE_PtrToParSolverFcn precond_setup,
HYPRE_Solver precond_solver )
{
return( HYPRE_PCGSetPrecond( solver,
(HYPRE_PtrToSolverFcn) precond,
(HYPRE_PtrToSolverFcn) precond_setup,
precond_solver ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGGetPrecond
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGGetPrecond( HYPRE_Solver solver,
HYPRE_Solver *precond_data_ptr )
{
return( HYPRE_PCGGetPrecond( solver, precond_data_ptr ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGSetPrintLevel
* an obsolete function; use HYPRE_PCG* functions instead
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGSetPrintLevel( HYPRE_Solver solver,
HYPRE_Int level )
{
return( HYPRE_PCGSetPrintLevel( solver, level ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGSetLogging
* an obsolete function; use HYPRE_PCG* functions instead
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGSetLogging( HYPRE_Solver solver,
HYPRE_Int level )
{
return( HYPRE_PCGSetLogging( solver, level ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGGetNumIterations
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGGetNumIterations( HYPRE_Solver solver,
HYPRE_Int *num_iterations )
{
return( HYPRE_PCGGetNumIterations( solver, num_iterations ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGGetFinalRelativeResidualNorm
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGGetFinalRelativeResidualNorm( HYPRE_Solver solver,
HYPRE_Real *norm )
{
return( HYPRE_PCGGetFinalRelativeResidualNorm( solver, norm ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRPCGGetResidual
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRPCGGetResidual( HYPRE_Solver solver,
HYPRE_ParVector *residual )
{
return( HYPRE_PCGGetResidual( solver, (void *) residual ) );
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRDiagScaleSetup
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRDiagScaleSetup( HYPRE_Solver solver,
HYPRE_ParCSRMatrix A,
HYPRE_ParVector y,
HYPRE_ParVector x )
{
return 0;
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRDiagScale
*--------------------------------------------------------------------------*/
HYPRE_Int
HYPRE_ParCSRDiagScale( HYPRE_Solver solver,
HYPRE_ParCSRMatrix HA,
HYPRE_ParVector Hy,
HYPRE_ParVector Hx )
{
hypre_ParCSRMatrix *A = (hypre_ParCSRMatrix *) HA;
hypre_ParVector *y = (hypre_ParVector *) Hy;
hypre_ParVector *x = (hypre_ParVector *) Hx;
HYPRE_Real *x_data = hypre_VectorData(hypre_ParVectorLocalVector(x));
HYPRE_Real *y_data = hypre_VectorData(hypre_ParVectorLocalVector(y));
HYPRE_Real *A_data = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(A));
HYPRE_Int *A_i = hypre_CSRMatrixI(hypre_ParCSRMatrixDiag(A));
HYPRE_Int local_size = hypre_VectorSize(hypre_ParVectorLocalVector(x));
HYPRE_Int ierr = 0;
#if defined(HYPRE_USING_CUDA)
hypreDevice_DiagScaleVector(local_size, A_i, A_data, y_data, x_data);
//hypre_SyncCudaComputeStream(hypre_handle);
#else /* #if defined(HYPRE_USING_CUDA) */
HYPRE_Int i;
#if defined(HYPRE_USING_DEVICE_OPENMP)
#pragma omp target teams distribute parallel for private(i) is_device_ptr(x_data,y_data,A_data,A_i)
#elif defined(HYPRE_USING_OPENMP)
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i=0; i < local_size; i++)
{
x_data[i] = y_data[i]/A_data[A_i[i]];
}
#endif /* #if defined(HYPRE_USING_CUDA) */
return ierr;
}
/*--------------------------------------------------------------------------
* HYPRE_ParCSRSymPrecondSetup
*--------------------------------------------------------------------------*/
/*
HYPRE_Int
HYPRE_ParCSRSymPrecondSetup( HYPRE_Solver solver,
HYPRE_ParCSRMatrix A,
HYPRE_ParVector b,
HYPRE_ParVector x )
{
hypre_ParCSRMatrix *A = (hypre_ParCSRMatrix *) A;
hypre_ParVector *y = (hypre_ParVector *) b;
hypre_ParVector *x = (hypre_ParVector *) x;
HYPRE_Real *x_data = hypre_VectorData(hypre_ParVectorLocalVector(x));
HYPRE_Real *y_data = hypre_VectorData(hypre_ParVectorLocalVector(y));
HYPRE_Real *A_diag = hypre_CSRMatrixData(hypre_ParCSRMatrixDiag(A));
HYPRE_Real *A_offd = hypre_CSRMatrixData(hypre_ParCSRMatrixOffD(A));
HYPRE_Int i, ierr = 0;
hypre_ParCSRMatrix *Asym;
MPI_Comm comm;
HYPRE_Int global_num_rows;
HYPRE_Int global_num_cols;
HYPRE_Int *row_starts;
HYPRE_Int *col_starts;
HYPRE_Int num_cols_offd;
HYPRE_Int num_nonzeros_diag;
HYPRE_Int num_nonzeros_offd;
Asym = hypre_ParCSRMatrixCreate(comm, global_num_rows, global_num_cols,
row_starts, col_starts, num_cols_offd,
num_nonzeros_diag, num_nonzeros_offd);
for (i=0; i < hypre_VectorSize(hypre_ParVectorLocalVector(x)); i++)
{
x_data[i] = y_data[i]/A_data[A_i[i]];
}
return ierr;
} */
|
GB_unop__ceil_fc64_fc64.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__ceil_fc64_fc64)
// op(A') function: GB (_unop_tran__ceil_fc64_fc64)
// C type: GxB_FC64_t
// A type: GxB_FC64_t
// cast: GxB_FC64_t cij = aij
// unaryop: cij = GB_cceil (aij)
#define GB_ATYPE \
GxB_FC64_t
#define GB_CTYPE \
GxB_FC64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_cceil (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC64_t z = aij ; \
Cx [pC] = GB_cceil (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_CEIL || GxB_NO_FC64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__ceil_fc64_fc64)
(
GxB_FC64_t *Cx, // Cx and Ax may be aliased
const GxB_FC64_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = aij ;
Cx [p] = GB_cceil (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC64_t aij = Ax [p] ;
GxB_FC64_t z = aij ;
Cx [p] = GB_cceil (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__ceil_fc64_fc64)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GraphTango.h | #pragma once
#include <cstdint>
#include <stack>
#include <vector>
#include <variant>
#include <cstring>
#include <algorithm>
#include <omp.h>
#include <string>
#include <iostream>
#include <atomic>
#include <unordered_map>
#include <queue>
#include <cassert>
#include <immintrin.h>
#include <fstream>
#include <map>
#include <bitset>
#include "omp.h"
#include "abstract_data_struc.h"
#include "types.h"
#include "LockFreePoolWithList.h"
#include "CustomAllocator.h"
#include "VertexArray.h"
#include "GEmpty.h"
#include "common.h"
#include "global.h"
using namespace std;
template<typename Neigh>
class GraphTango : public dataStruc {
public:
void print(void) override {
#ifdef CALC_MEM_PER_EDGE
cout << "Total memory req: " << globalAllocator.totMem << endl;
#endif
// std::cout << "Inserts--------------------" << std::endl;
// std::cout << " Total: " << insTot << std::endl;
// std::cout << " Succ : " << insSucc << std::endl;
// std::cout << " Fail : " << insTot - insSucc << std::endl;
// std::cout << std::endl;
//
// std::cout << "Deletes--------------------" << std::endl;
// std::cout << " Total: " << delTot << std::endl;
// std::cout << " Succ : " << delSucc << std::endl;
// std::cout << " Fail : " << delTot - delSucc << std::endl;
// std::cout << std::endl;
//
// std::cout << "Final number of edges: " << insSucc - delSucc << std::endl;
// ofstream out("probing_dist.csv");
// for(auto it : probingDist){
// out << it.first << "," << it.second << endl;
// }
}
#ifdef USE_HYBRID_HASHMAP
VertexArray<Neigh> vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray.resize(numNodes);
#pragma omp parallel for
for(u64 i = 0; i < numNodes; i++){
vArray.outDegree[i] = 0;
vArray.outCapacity[i] = 0;
vArray.outNeighArr[i] = nullptr;
vArray.outMapArr[i] = nullptr;
vArray.inDegree[i] = 0;
vArray.inCapacity[i] = 0;
vArray.inNeighArr[i] = nullptr;
vArray.inMapArr[i] = nullptr;
}
cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl;
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
}
int64_t in_degree(NodeID n) override {
return vArray.inDegree[n];
}
int64_t out_degree(NodeID n) override {
return vArray.outDegree[n];
}
void insertEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, graphite_hashmap* __restrict &locMap, const Idx dstId, const Weight weight, u64& edgeCnt){
//insTot++;
if(deg == cap){
const u64 newCap = getNextPow2MinRet(cap * 2);
Neigh* __restrict oldPtr = neighs;
Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
cap = newCap;
neighs = newPtr;
if(deg > 0){
memcpy(newPtr, oldPtr, deg * sizeof(Neigh));
globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh));
}
if(__builtin_expect(newCap == HYBRID_HASH_PARTITION, 0)){
//switch from linear to hashed mode
locMap = (graphite_hashmap*)globalAllocator.allocate(sizeof(graphite_hashmap));
new (locMap) graphite_hashmap();
//add existing nodes to hash
const Neigh* __restrict neighs = newPtr;
for(u64 i = 0; i < deg; i++){
(*locMap)[neighs[i].node] = i;
}
}
}
//search for existing edge
if(!locMap){
//using linear mode
Neigh* __restrict nn = nullptr;
for(u64 i = 0; i < deg; i++){
if(neighs[i].node == dstId){
nn = neighs + i;
break;
}
}
if(!nn){
//edge not found, insert
neighs[deg].node = dstId;
neighs[deg].setWeight(weight);
deg++;
edgeCnt++;
//insSucc++;
}
else{
//edge found, update
nn->setWeight(weight);
}
}
else {
//using hashed mode
const auto& it = locMap->find(dstId);
if(it == locMap->end()){
//edge not found, insert
Neigh& nn = neighs[deg];
nn.node = dstId;
nn.setWeight(weight);
(*locMap)[dstId] = deg;
deg++;
edgeCnt++;
//insSucc++;
}
else{
//edge found, update weight
neighs[it->second].setWeight(weight);
}
}
}
void deleteEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, graphite_hashmap* __restrict &locMap, const Idx dstId, u64& edgeCnt){
//delTot++;
//search for existing edge
if(!locMap){
//using linear mode
Neigh* __restrict nn = nullptr;
for(u64 i = 0; i < deg; i++){
if(neighs[i].node == dstId){
nn = neighs + i;
break;
}
}
if(!nn){
//edge not found, nothing to do
return;
}
else{
//edge found, delete
deg--;
edgeCnt--;
//delSucc++;
//move last elem
*nn = neighs[deg];
}
}
else {
//using hashed mode
const auto& it = locMap->find(dstId);
if(it == locMap->end()){
//edge not found, nothing to do
return;
}
else{
//edge found, delete
deg--;
edgeCnt--;
//delSucc++;
const u64 loc = it->second;
locMap->erase(it);
if(__builtin_expect(loc != deg, false)){
//not the last element... move
neighs[loc] = neighs[deg];
(*locMap)[neighs[loc].node] = loc;
}
}
}
if((cap > 4) && ((deg * 4) <= cap)){
const u64 newCap = cap / 2;
Neigh* __restrict oldPtr = neighs;
Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
cap = newCap;
neighs = newPtr;
memcpy(newPtr, oldPtr, deg * sizeof(Neigh));
globalAllocator.freePow2(oldPtr, newCap * 2 * sizeof(Neigh));
if(__builtin_expect(newCap < HYBRID_HASH_PARTITION, 0)){
//switch from hashed to linear mode
globalAllocator.freePow2(locMap, sizeof(graphite_hashmap));
locMap = nullptr;
}
}
}
void update(const EdgeList& el) override {
const u64 batchSize = el.size();
#ifdef _OPENMP
int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
i64 targetTh = (src / 64) & thMask;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!el[i].isDelete){
//insert out edge
insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
else{
//delete out edge
deleteEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, thInfo[actualTh].edgeCnt);
}
}
targetTh = (dst / 64) & thMask;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert in edge
insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, el[i].weight, garbage);
}
else{
//delete in edge
deleteEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, garbage);
}
}
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
//we do not need atomic operation on affected as long as "some" thread updates it
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert out edge
insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, el[i].weight, garbage);
}
else{
//delete out edge
deleteEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, thInfo[0].edgeCnt);
//delete in edge
deleteEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, garbage);
}
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_HYBRID_HASHMAP_WITH_CFH
#define FLAG_EMPTY_SLOT 0xFFFFFFFFU
#define FLAG_TOMB_STONE 0xFFFFFFFEU
VertexArray<Neigh> vArray;
const int num_threads;
//map<u64, u64> probingDist;
//u64 probe;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray.resize(numNodes);
#pragma omp parallel for
for(u64 i = 0; i < numNodes; i++){
vArray.outDegree[i] = 0;
vArray.outCapacity[i] = 0;
vArray.outNeighArr[i] = nullptr;
vArray.outMapArr[i] = nullptr;
vArray.inDegree[i] = 0;
vArray.inCapacity[i] = 0;
vArray.inNeighArr[i] = nullptr;
vArray.inMapArr[i] = nullptr;
}
//vArray.usingHash.resize(numNodes, false);
//vArray.dstLocMap.resize(numNodes);
cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl;
#ifdef _OPENMP
cout << "Max threads: " << omp_get_max_threads() << endl;
cout << "Num threads: " << omp_get_num_threads() << endl;
#endif
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
}
int64_t in_degree(NodeID n) override {
return vArray.inDegree[n];
}
int64_t out_degree(NodeID n) override {
return vArray.outDegree[n];
}
//for now, use linear probing
inline DstLocPair* findInsertionPoint(DstLocPair* __restrict &locMap, u32 dst, u32 tableSize){
u32 idx = dst & (tableSize - 1);
while(true){
if((locMap[idx].dst == dst) || (locMap[idx].dst == FLAG_EMPTY_SLOT)){
//found key or an empty slot
return locMap + idx;
}
//move on
idx++;
if(idx == tableSize){
idx = 0;
}
}
return nullptr;
}
void insertEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, DstLocPair* __restrict &locMap, const Idx dstId, const Weight weight, u64& edgeCnt){
//insTot++;
if(deg == cap){
const u64 newCap = getNextPow2MinRet(cap * 2);
Neigh* __restrict oldPtr = neighs;
Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
cap = newCap;
neighs = newPtr;
if(deg > 0){
memcpy(newPtr, oldPtr, deg * sizeof(Neigh));
globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh));
}
if(newCap >= HYBRID_HASH_PARTITION){
if(locMap){
//free old loc map
globalAllocator.freePow2(locMap, cap * sizeof(DstLocPair));
}
locMap = (DstLocPair*)globalAllocator.allocate(sizeof(DstLocPair) * cap * 2);
memset(locMap, -1, sizeof(DstLocPair) * cap * 2);
const u32 mask = cap * 2 - 1;
//add existing nodes to hash
const Neigh* __restrict nn = neighs;
for(u64 i = 0; i < deg; i++){
const u32 dst = nn[i].node;
u32 idx = dst & mask;
while(true){
if(locMap[idx].dst == FLAG_EMPTY_SLOT){
//found insertion point
locMap[idx].dst = dst;
locMap[idx].loc = i;
break;
}
//move on
idx++;
if(idx == (cap * 2)){
idx = 0;
}
}
}
}
}
//search for existing edge
if(!locMap){
//using linear mode
Neigh* __restrict nn = nullptr;
for(u64 i = 0; i < deg; i++){
if(neighs[i].node == dstId){
nn = neighs + i;
break;
}
}
if(!nn){
//edge not found, insert
neighs[deg].node = dstId;
neighs[deg].setWeight(weight);
deg++;
edgeCnt++;
//insSucc++;
}
else{
//edge found, update
nn->setWeight(weight);
}
}
else {
//using hashed mode
u32 idx = dstId & (cap * 2 - 1);
//probe = 0;
while(true){
//probe++;
if(locMap[idx].dst == FLAG_EMPTY_SLOT){
//edge not found, insert
Neigh& nn = neighs[deg];
nn.node = dstId;
nn.setWeight(weight);
locMap[idx].dst = dstId;
locMap[idx].loc = deg;
deg++;
edgeCnt++;
//insSucc++;
//probingDist[probe]++;
return;
}
else if(locMap[idx].dst == dstId){
//edge found, update weight
neighs[locMap[idx].loc].setWeight(weight);
//probingDist[probe]++;
return;
}
//move on
idx++;
if(idx == (cap * 2)){
idx = 0;
}
}
}
}
void deleteEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, DstLocPair* __restrict &locMap, const Idx dstId, u64& edgeCnt){
//delTot++;
//search for existing edge
if(!locMap){
//using linear mode
Neigh* __restrict nn = nullptr;
for(u64 i = 0; i < deg; i++){
if(neighs[i].node == dstId){
nn = neighs + i;
break;
}
}
if(!nn){
//edge not found, return
return;
}
else{
//edge found, delete
deg--;
edgeCnt--;
//delSucc++;
nn->node = neighs[deg].node;
nn->setWeight(neighs[deg].getWeight());
}
}
else {
//using hashed mode
u32 idx = dstId & (cap * 2 - 1);
while(true){
if(locMap[idx].dst == FLAG_EMPTY_SLOT){
//edge not found, return
return;
}
else if(locMap[idx].dst == dstId){
//edge found, delete
deg--;
edgeCnt--;
//delSucc++;
locMap[idx].dst = FLAG_TOMB_STONE; //invalidate previous hash-table entry
const u32 loc = locMap[idx].loc;
if(__builtin_expect(loc != deg, true)){ //nothing to do if last entry is removed
const u32 node = neighs[deg].node;
//copy last entry
neighs[loc] = neighs[deg];
//point to correct location of the swapped entry
u32 idxMoved = node & (cap * 2 - 1);
while(locMap[idxMoved].dst != node){
idxMoved++;
if(idxMoved == (cap * 2)){
idxMoved = 0;
}
}
locMap[idxMoved].loc = loc;
}
break;
}
//move on
idx++;
if(idx == (cap * 2)){
idx = 0;
}
}
}
if((cap > 4) && (deg * 4) <= cap){
//time to reduce capacity
const u64 newCap = cap / 2;
Neigh* __restrict oldPtr = neighs;
Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
//copy old adjList and free
memcpy(newPtr, oldPtr, deg * sizeof(Neigh));
globalAllocator.freePow2(oldPtr, cap * sizeof(Neigh));
cap = newCap;
neighs = newPtr;
if(locMap){
//free old loc map (if any)
globalAllocator.freePow2(locMap, cap * sizeof(DstLocPair));
locMap = nullptr;
}
if(cap >= HYBRID_HASH_PARTITION){
locMap = (DstLocPair*)globalAllocator.allocate(sizeof(DstLocPair) * cap * 2);
memset(locMap, -1, sizeof(DstLocPair) * cap * 2); //This is bad. Is there any way to circumvent this?
const u32 mask = cap * 2 - 1;
//add existing nodes to hash
const Neigh* __restrict nn = neighs;
for(u64 i = 0; i < deg; i++){
const u32 dst = nn[i].node;
u32 idx = dst & mask;
while(true){
if(locMap[idx].dst == FLAG_EMPTY_SLOT){
//found insertion point
locMap[idx].dst = dst;
locMap[idx].loc = i;
break;
}
//move on
idx++;
if(idx == (cap * 2)){
idx = 0;
}
}
}
}
}
}
void update(const EdgeList& el) override {
//probe = 0;
const u64 batchSize = el.size();
#ifdef _OPENMP
//int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
//i64 targetTh = (src / 64) & thMask;
i64 targetTh = (src / 64) % num_threads;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!el[i].isDelete){
//insert out edge
insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
else{
//delete out edge
deleteEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, thInfo[0].edgeCnt);
}
}
//targetTh = (dst / 64) & thMask;
targetTh = (dst / 64) % num_threads;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert in edge
insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, el[i].weight, garbage);
}
else{
//delete in edge
deleteEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, garbage);
}
}
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
//we do not need atomic operation on affected as long as "some" thread updates it
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insertion
//insert out edge
insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, el[i].weight, garbage);
}
else{
//delete out edge
deleteEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, thInfo[0].edgeCnt);
//delete in edge
deleteEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, garbage);
}
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#if defined(USE_GT_BALANCED)
Vertex<Neigh>* vArray;
//VertexArray<Neigh> vArray;
const int num_threads;
#ifdef CALC_TYPE_SWITCH
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u64 switchCnt = 0;
u8 pad[40];
} ThreadInfo;
#else
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
#endif
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)globalAllocator.allocate(sizeof(Vertex<Neigh>) * numNodes);
#pragma omp parallel for
for(u64 i = 0; i < numNodes; i++){
vArray[i].inEdges.degree = 0;
vArray[i].inEdges.capacity = EdgeArray<Neigh>::TH0;
vArray[i].outEdges.degree = 0;
vArray[i].outEdges.capacity = EdgeArray<Neigh>::TH0;
}
cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl;
cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl;
cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl;
cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl;
cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl;
#ifdef _OPENMP
cout << "Max threads: " << omp_get_max_threads() << endl;
#endif
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
#ifdef CALC_TYPE_SWITCH
u32 switchCnt = 0;
for(u64 i = 0; i < num_threads; i++){
switchCnt += thInfo[i].switchCnt;
}
cout << "Switch Count: " << switchCnt << endl;
#endif
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
void update(const EdgeList& el) override {
//probe = 0;
const u64 batchSize = el.size();
#ifdef _OPENMP
//int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
{
const i64 actualTh = omp_get_thread_num();
LIKWID_MARKER_START("upd");
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
//i64 targetTh = (src / 64) & thMask;
i64 targetTh = (src / 64) % num_threads;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
#ifdef CALC_TYPE_SWITCH
VType initType = VType::VTYPE_3;
if(vArray[src].outEdges.capacity <= vArray[src].outEdges.TH0){
initType = VType::VTYPE_1;
}
else if(vArray[src].outEdges.capacity <= vArray[src].outEdges.TH1){
initType = VType::VTYPE_2;
}
#endif
if(!el[i].isDelete){
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[actualTh].edgeCnt);
}
#ifdef CALC_TYPE_SWITCH
VType finType = VType::VTYPE_3;
if(vArray[src].outEdges.capacity <= vArray[src].outEdges.TH0){
finType = VType::VTYPE_1;
}
else if(vArray[src].outEdges.capacity <= vArray[src].outEdges.TH1){
finType = VType::VTYPE_2;
}
if(initType != finType){
thInfo[actualTh].switchCnt++;
}
#endif
}
//targetTh = (dst / 64) & thMask;
targetTh = (dst / 64) % num_threads;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
#ifdef CALC_TYPE_SWITCH
VType initType = VType::VTYPE_3;
if(vArray[dst].inEdges.capacity <= vArray[dst].inEdges.TH0){
initType = VType::VTYPE_1;
}
else if(vArray[dst].inEdges.capacity <= vArray[dst].inEdges.TH1){
initType = VType::VTYPE_2;
}
#endif
u64 garbage;
if(!el[i].isDelete){
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
#ifdef CALC_TYPE_SWITCH
VType finType = VType::VTYPE_3;
if(vArray[dst].inEdges.capacity <= vArray[dst].inEdges.TH0){
finType = VType::VTYPE_1;
}
else if(vArray[dst].inEdges.capacity <= vArray[dst].inEdges.TH1){
finType = VType::VTYPE_2;
}
if(initType != finType){
thInfo[actualTh].switchCnt++;
}
#endif
}
}
LIKWID_MARKER_STOP("upd");
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
//we do not need atomic operation on affected as long as "some" thread updates it
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insertion
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt);
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
#ifdef CALC_TYPE_SWITCH
switchCnt += thInfo[i].switchCnt;
thInfo[i].switchCnt = 0;
#endif
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_GT_BALANCED_TYPE3_ONLY
Vertex<Neigh>* vArray;
//VertexArray<Neigh> vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)globalAllocator.allocate(sizeof(Vertex<Neigh>) * numNodes);
#pragma omp parallel for
for(u64 i = 0; i < numNodes; i++){
vArray[i].inEdges.degree = 0;
vArray[i].inEdges.capacity = 0;
vArray[i].outEdges.degree = 0;
vArray[i].outEdges.capacity = 0;
}
//cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl;
//cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl;
cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl;
cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl;
cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl;
#ifdef _OPENMP
cout << "Max threads: " << omp_get_max_threads() << endl;
#endif
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
void update(const EdgeList& el) override {
//probe = 0;
const u64 batchSize = el.size();
#ifdef _OPENMP
//int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
{
const i64 actualTh = omp_get_thread_num();
LIKWID_MARKER_START("upd");
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
//i64 targetTh = (src / 64) & thMask;
i64 targetTh = (src / 64) % num_threads;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!el[i].isDelete){
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[actualTh].edgeCnt);
}
}
//targetTh = (dst / 64) & thMask;
targetTh = (dst / 64) % num_threads;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
}
}
LIKWID_MARKER_STOP("upd");
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
//we do not need atomic operation on affected as long as "some" thread updates it
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insertion
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt);
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_GT_BALANCED_DYN_PARTITION
Vertex<Neigh>* vArray;
//VertexArray<Neigh> vArray;
const int num_threads;
typedef struct{
u32 nodeCnt = 0;
u32 inCurrEdge = 0;
u32 inNewEdge = 0;
u32 inStart = 0;
u32 inEnd = 0;
u32 outCurrEdge = 0;
u32 outNewEdge = 0;
u32 outStart = 0;
u32 outEnd = 0;
u8 pad[28];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)globalAllocator.allocate(sizeof(Vertex<Neigh>) * numNodes);
#pragma omp parallel for
for(u64 i = 0; i < numNodes; i++){
vArray[i].inEdges.degree = 0;
vArray[i].inEdges.capacity = EdgeArray<Neigh>::TH0;
vArray[i].outEdges.degree = 0;
vArray[i].outEdges.capacity = EdgeArray<Neigh>::TH0;
}
cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl;
cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl;
cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl;
cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl;
cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl;
#ifdef _OPENMP
cout << "Max threads: " << omp_get_max_threads() << endl;
#endif
memset(thInfo, 0, sizeof(ThreadInfo) * 32);
const u32 avgNodePerTh = numNodes / numThreads;
thInfo[0].inStart = 0;
thInfo[0].outStart = 0;
for(u32 i = 0; i < numThreads-1; i++){
thInfo[i].inEnd = thInfo[i].inStart + avgNodePerTh;
thInfo[i+1].inStart = thInfo[i].inEnd + 1;
thInfo[i].outEnd = thInfo[i].outStart + avgNodePerTh;
thInfo[i+1].outStart = thInfo[i].outEnd + 1;
}
thInfo[numThreads - 1].inEnd = numNodes;
thInfo[numThreads - 1].outEnd = numNodes;
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
void update(const EdgeList& el) override {
//probe = 0;
const u64 batchSize = el.size();
#ifdef _OPENMP
//int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
{
ThreadInfo& th = thInfo[omp_get_thread_num()];
const u32 inStart = th.inStart;
const u32 inEnd = th.inEnd;
const u32 outStart = th.outStart;
const u32 outEnd = th.outEnd;
LIKWID_MARKER_START("upd");
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
//i64 targetTh = (src / 64) & thMask;
//i64 targetTh = (src / 64) % num_threads;
if(src >= outStart && src <= outEnd){
if(!el[i].sourceExists){
th.nodeCnt++;
}
if(!el[i].destExists){
th.nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!el[i].isDelete){
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, th.outNewEdge);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, th.outNewEdge);
}
}
//targetTh = (dst / 64) & thMask;
//targetTh = (dst / 64) % num_threads;
if(dst >= inStart && dst <= inEnd){
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, th.inNewEdge);
}
else{
//delete in edge
vArray[dst].inEdges.deleteEdge(src, th.inNewEdge);
}
}
}
LIKWID_MARKER_STOP("upd");
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
//we do not need atomic operation on affected as long as "some" thread updates it
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insertion
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt);
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].inNewEdge + thInfo[i].outNewEdge;
thInfo[i].inCurrEdge += thInfo[i].inNewEdge;
thInfo[i].outCurrEdge += thInfo[i].outNewEdge;
thInfo[i].inNewEdge = 0;
thInfo[i].outNewEdge = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
float avgEdge = (num_edges / 2.0) / num_nodes;
i64 inBalance = 0;
i64 outBalance = 0;
for(u64 i = 0; i < (num_threads - 1); i++){
ThreadInfo& th = thInfo[i];
//balance in edges
if(th.inCurrEdge > avgEdge){
//decrease workload
while(th.inCurrEdge > avgEdge){
const u32 remEdge = vArray[th.inEnd].inEdges.degree;
inBalance += remEdge;
th.inEnd--;
th.inCurrEdge -= remEdge;
}
}
else{
//increase workload
while(th.inCurrEdge < avgEdge){
th.inEnd++;
const u32 remEdge = vArray[th.inEnd].inEdges.degree;
inBalance -= remEdge;
th.inCurrEdge += remEdge;
}
}
thInfo[i+1].inStart = th.inEnd + 1;
thInfo[i+1].inCurrEdge += inBalance;
//balance out edges
if(th.outCurrEdge > avgEdge){
//decrease workload
while(th.outCurrEdge > avgEdge){
const u32 remEdge = vArray[th.outEnd].outEdges.degree;
outBalance += remEdge;
th.outEnd--;
th.outCurrEdge -= remEdge;
}
}
else{
//increase workload
while(th.outCurrEdge < avgEdge){
th.outEnd++;
const u32 remEdge = vArray[th.outEnd].outEdges.degree;
outBalance -= remEdge;
th.outCurrEdge += remEdge;
}
}
thInfo[i+1].outStart = th.outEnd + 1;
thInfo[i+1].outCurrEdge += outBalance;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_GT_BALANCED_STDMAP
Vertex<Neigh>* vArray;
//VertexArray<Neigh> vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)globalAllocator.allocate(sizeof(Vertex<Neigh>) * numNodes);
#pragma omp parallel for
for(u64 i = 0; i < numNodes; i++){
vArray[i].inEdges.degree = 0;
vArray[i].inEdges.capacity = EdgeArray<Neigh>::TH0;
vArray[i].outEdges.degree = 0;
vArray[i].outEdges.capacity = EdgeArray<Neigh>::TH0;
}
cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl;
cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl;
cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl;
cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl;
cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl;
#ifdef _OPENMP
cout << "Max threads: " << omp_get_max_threads() << endl;
#endif
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
void update(const EdgeList& el) override {
//probe = 0;
const u64 batchSize = el.size();
#ifdef _OPENMP
//int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
{
LIKWID_MARKER_START("upd");
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
//i64 targetTh = (src / 64) & thMask;
i64 targetTh = (src / 64) % num_threads;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!el[i].isDelete){
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[actualTh].edgeCnt);
}
}
//targetTh = (dst / 64) & thMask;
targetTh = (dst / 64) % num_threads;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
}
}
LIKWID_MARKER_STOP("upd");
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
//we do not need atomic operation on affected as long as "some" thread updates it
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insertion
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt);
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#if defined(USE_GT_BALANCED_MALLOC_STDMAP) || defined(USE_GT_BALANCED_ABSEIL) || defined(USE_GT_BALANCED_RHH) || defined(USE_GT_BALANCED_TSL_RHH)
Vertex<Neigh>* vArray;
//VertexArray<Neigh> vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)aligned_alloc(64, sizeof(Vertex<Neigh>) * numNodes);
#pragma omp parallel for
for(u64 i = 0; i < numNodes; i++){
vArray[i].inEdges.degree = 0;
vArray[i].inEdges.capacity = EdgeArray<Neigh>::TH0;
vArray[i].outEdges.degree = 0;
vArray[i].outEdges.capacity = EdgeArray<Neigh>::TH0;
}
cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl;
cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl;
cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl;
cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl;
cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl;
#ifdef _OPENMP
cout << "Max threads: " << omp_get_max_threads() << endl;
#endif
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
void update(const EdgeList& el) override {
//probe = 0;
const u64 batchSize = el.size();
#ifdef _OPENMP
//int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
{
LIKWID_MARKER_START("upd");
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
//i64 targetTh = (src / 64) & thMask;
i64 targetTh = (src / 64) % num_threads;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!el[i].isDelete){
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[actualTh].edgeCnt);
}
}
//targetTh = (dst / 64) & thMask;
targetTh = (dst / 64) % num_threads;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
}
}
LIKWID_MARKER_STOP("upd");
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
//we do not need atomic operation on affected as long as "some" thread updates it
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insertion
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt);
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_GT_BALANCED_MALLOC
Vertex<Neigh>* vArray;
//VertexArray<Neigh> vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)aligned_alloc(64, sizeof(Vertex<Neigh>) * numNodes);
#pragma omp parallel for
for(u64 i = 0; i < numNodes; i++){
vArray[i].inEdges.degree = 0;
vArray[i].inEdges.capacity = EdgeArray<Neigh>::TH0;
vArray[i].outEdges.degree = 0;
vArray[i].outEdges.capacity = EdgeArray<Neigh>::TH0;
}
cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl;
cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl;
cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl;
cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl;
cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl;
#ifdef _OPENMP
cout << "Max threads: " << omp_get_max_threads() << endl;
#endif
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
void update(const EdgeList& el) override {
//probe = 0;
const u64 batchSize = el.size();
#ifdef _OPENMP
//int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
{
LIKWID_MARKER_START("upd");
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
//i64 targetTh = (src / 64) & thMask;
i64 targetTh = (src / 64) % num_threads;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!el[i].isDelete){
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[actualTh].edgeCnt);
}
}
//targetTh = (dst / 64) & thMask;
targetTh = (dst / 64) % num_threads;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
}
}
LIKWID_MARKER_STOP("upd");
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
//we do not need atomic operation on affected as long as "some" thread updates it
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insertion
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt);
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_GT_UPDATE
Vertex<Neigh>* vArray;
//VertexArray<Neigh> vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)globalAllocator.allocate(sizeof(Vertex<Neigh>) * numNodes);
#pragma omp parallel for
for(u64 i = 0; i < numNodes; i++){
vArray[i].inEdges.degree = 0;
vArray[i].inEdges.capacity = EdgeArray<Neigh>::TH0;
vArray[i].outEdges.degree = 0;
vArray[i].outEdges.capacity = EdgeArray<Neigh>::TH0;
}
cout << "TH0: " << EdgeArray<Neigh>::TH0 << endl;
cout << "TH1: " << EdgeArray<Neigh>::TH1 << endl;
cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl;
cout << "Sizeof EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl;
cout << "Sizeof Vertex: " << sizeof(Vertex<Neigh>) << endl;
#ifdef _OPENMP
cout << "Max threads: " << omp_get_max_threads() << endl;
#endif
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
// void deleteEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, DstLocPair* __restrict &locMap, const Idx dstId, u64& edgeCnt){
// //delTot++;
// //search for existing edge
// if(!locMap){
// //using linear mode
// Neigh* __restrict nn = nullptr;
// for(u64 i = 0; i < deg; i++){
// if(neighs[i].node == dstId){
// nn = neighs + i;
// break;
// }
// }
// if(!nn){
// //edge not found, return
// return;
// }
// else{
// //edge found, delete
// deg--;
// edgeCnt--;
// //delSucc++;
// nn->node = neighs[deg].node;
// nn->setWeight(neighs[deg].getWeight());
// }
// }
// else {
// //using hashed mode
// u32 idx = dstId & (cap * 2 - 1);
// while(true){
// if(locMap[idx].dst == FLAG_EMPTY_SLOT){
// //edge not found, return
// return;
// }
// else if(locMap[idx].dst == dstId){
// //edge found, delete
// deg--;
// edgeCnt--;
// //delSucc++;
// locMap[idx].dst = FLAG_TOMB_STONE; //invalidate previous hash-table entry
//
// const u32 loc = locMap[idx].loc;
// if(__builtin_expect(loc != deg, true)){ //nothing to do if last entry is removed
// const u32 node = neighs[deg].node;
// //copy last entry
// neighs[loc] = neighs[deg];
//
// //point to correct location of the swapped entry
// u32 idxMoved = node & (cap * 2 - 1);
// while(locMap[idxMoved].dst != node){
// idxMoved++;
// if(idxMoved == (cap * 2)){
// idxMoved = 0;
// }
// }
// locMap[idxMoved].loc = loc;
// }
// break;
// }
// //move on
// idx++;
// if(idx == (cap * 2)){
// idx = 0;
// }
// }
// }
//
// if((cap > 4) && (deg * 4) <= cap){
// //time to reduce capacity
//
// const u64 newCap = cap / 2;
// Neigh* __restrict oldPtr = neighs;
// Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
//
// //copy old adjList and free
// memcpy(newPtr, oldPtr, deg * sizeof(Neigh));
// globalAllocator.freePow2(oldPtr, cap * sizeof(Neigh));
//
// cap = newCap;
// neighs = newPtr;
//
// if(locMap){
// //free old loc map (if any)
// globalAllocator.freePow2(locMap, cap * sizeof(DstLocPair));
// locMap = nullptr;
// }
//
// if(cap >= HYBRID_HASH_PARTITION){
// locMap = (DstLocPair*)globalAllocator.allocate(sizeof(DstLocPair) * cap * 2);
// memset(locMap, -1, sizeof(DstLocPair) * cap * 2); //This is bad. Is there any way to circumvent this?
//
// const u32 mask = cap * 2 - 1;
//
// //add existing nodes to hash
// const Neigh* __restrict nn = neighs;
// for(u64 i = 0; i < deg; i++){
// const u32 dst = nn[i].node;
// u32 idx = dst & mask;
// while(true){
// if(locMap[idx].dst == FLAG_EMPTY_SLOT){
// //found insertion point
// locMap[idx].dst = dst;
// locMap[idx].loc = i;
// break;
// }
// //move on
// idx++;
// if(idx == (cap * 2)){
// idx = 0;
// }
// }
// }
// }
// }
// }
void update(const EdgeList& el) override {
//probe = 0;
const u64 batchSize = el.size();
#ifdef _OPENMP
//int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
//i64 targetTh = (src / 64) & thMask;
i64 targetTh = (src / 64) % num_threads;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!el[i].isDelete){
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[actualTh].edgeCnt);
}
}
//targetTh = (dst / 64) & thMask;
targetTh = (dst / 64) % num_threads;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
}
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
//we do not need atomic operation on affected as long as "some" thread updates it
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insertion
//insert out edge
vArray[src].outEdges.insertEdge(dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
vArray[dst].inEdges.insertEdge(src, el[i].weight, garbage);
}
else{
//delete out edge
vArray[src].outEdges.deleteEdge(dst, thInfo[0].edgeCnt);
//delete in edge
vArray[dst].inEdges.deleteEdge(src, garbage);
}
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_HYBRID_HASHMAP_WITH_GROUPING
Vertex<Neigh>* vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)aligned_alloc(64, numNodes * sizeof(Vertex<Neigh>));
memset(vArray, 0, numNodes * sizeof(Vertex<Neigh>));
cout << "Size of Vertex: " << sizeof(Vertex<Neigh>) << endl;
cout << "Size of ThreadInfo: " << sizeof(ThreadInfo) << endl;
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
free(vArray);
}
void print() override {
cout << "Done" << endl;
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
void insertEdge(EdgeArray<Neigh>* __restrict edgePtr, const Idx dstId, const Weight weight, u64& edgeCnt){
if(edgePtr->degree == edgePtr->capacity){
const u64 newCap = getNextPow2MinRet(edgePtr->capacity * 2);
Neigh* __restrict oldPtr = edgePtr->neighArr;
Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
edgePtr->capacity = newCap;
edgePtr->neighArr = newPtr;
if(edgePtr->degree > 0){
memcpy(newPtr, oldPtr, edgePtr->degree * sizeof(Neigh));
globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh));
}
if(__builtin_expect(newCap == HYBRID_HASH_PARTITION, 0)){
//switch from linear to hashed mode
edgePtr->mapArr = (graphite_hashmap*)globalAllocator.allocate(sizeof(graphite_hashmap));
new (edgePtr->mapArr) graphite_hashmap();
//add existing nodes to hash
const Neigh* __restrict neighs = newPtr;
for(u64 i = 0; i < edgePtr->degree; i++){
(*edgePtr->mapArr)[neighs[i].node] = i;
}
}
}
//search for existing edge
if(!edgePtr->mapArr){
//using linear mode
Neigh* __restrict nn = nullptr;
for(u64 i = 0; i < edgePtr->degree; i++){
if(edgePtr->neighArr[i].node == dstId){
nn = edgePtr->neighArr + i;
break;
}
}
if(!nn){
//edge not found, insert
edgePtr->neighArr[edgePtr->degree].node = dstId;
edgePtr->neighArr[edgePtr->degree].setWeight(weight);
edgePtr->degree++;
edgeCnt++;
}
else{
//edge found, update
nn->setWeight(weight);
}
}
else {
//using hashed mode
const auto& it = edgePtr->mapArr->find(dstId);
if(it == edgePtr->mapArr->end()){
//edge not found, insert
Neigh& nn = edgePtr->neighArr[edgePtr->degree];
nn.node = dstId;
nn.setWeight(weight);
(*edgePtr->mapArr)[dstId] = edgePtr->degree;
edgePtr->degree++;
edgeCnt++;
}
else{
//edge found, update weight
edgePtr->neighArr[it->second].setWeight(weight);
}
}
}
void update(const EdgeList& el) override {
const u64 batchSize = el.size();
#ifdef _OPENMP
int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
i64 targetTh = (src / 64) & thMask;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
//insert out edge
insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
targetTh = (dst / 64) & thMask;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
//insert in edge
insertEdge(&vArray[dst].inEdges, src, el[i].weight, thInfo[actualTh].edgeCnt);
}
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
//insert out edge
insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
u64 garbage;
insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbage);
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_SORTED_EDGES
Vertex<Neigh>* vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)aligned_alloc(64, numNodes * sizeof(Vertex<Neigh>));
memset(vArray, 0, numNodes * sizeof(Vertex<Neigh>));
cout << "Size of Vertex: " << sizeof(Vertex<Neigh>) << endl;
cout << "Size of ThreadInfo: " << sizeof(ThreadInfo) << endl;
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
free(vArray);
}
void print() override {
cout << "Done" << endl;
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
void insertEdge(EdgeArray<Neigh>* __restrict edgePtr, const Idx dstId, const Weight weight, u64& edgeCnt){
Neigh* __restrict insLoc = nullptr;
//first, do linear search
for(u64 i = 0; i < edgePtr->degree; i++){
if(edgePtr->neighArr[i].node == dstId){
//found
insLoc = edgePtr->neighArr + i;
break;
}
}
if(!insLoc && edgePtr->degree > LINEAR_BUFF_SIZE){
//do binary search
u64 low = LINEAR_BUFF_SIZE;
u64 high = edgePtr->degree;
}
if(!insLoc){
//not found, insert
if(edgePtr->degree == edgePtr->capacity){
const u64 newCap = getNextPow2MinRet(edgePtr->capacity * 2);
Neigh* __restrict oldPtr = edgePtr->neighArr;
Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
edgePtr->capacity = newCap;
edgePtr->neighArr = newPtr;
if(edgePtr->degree > 0){
memcpy(newPtr, oldPtr, edgePtr->degree * sizeof(Neigh));
globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh));
}
}
insLoc->node = dstId;
edgePtr->degree++;
edgeCnt++;
}
insLoc->setWeight(weight);
}
void update(const EdgeList& el) override {
const u64 batchSize = el.size();
#ifdef _OPENMP
int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
i64 targetTh = (src / 64) & thMask;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
//insert out edge
insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
targetTh = (dst / 64) & thMask;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
//insert in edge
u64 garbase;
insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbase);
}
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
//insert out edge
insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
u64 garbage;
insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbage);
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_HYBRID_HASHMAP_WITH_GROUPING_TIGHTER
Vertex<Neigh>* vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)aligned_alloc(64, numNodes * sizeof(Vertex<Neigh>));
for(u64 i = 0; i < numNodes; i++){
Vertex<Neigh>& v = vArray[i];
v.inEdges.degree = 0;
v.inEdges.capacity = INITIAL_EDGES;
v.inEdges.neighArr = v.inEdges.neigh;
v.inEdges.mapArr = nullptr;
v.outEdges.degree = 0;
v.outEdges.capacity = INITIAL_EDGES;
v.outEdges.neighArr = v.outEdges.neigh;
v.outEdges.mapArr = nullptr;
}
cout << "Size of EdgeArray: " << sizeof(EdgeArray<Neigh>) << endl;
cout << "Size of Vertex: " << sizeof(Vertex<Neigh>) << endl;
cout << "Size of ThreadInfo: " << sizeof(ThreadInfo) << endl;
cout << "Size of Neigh: " << sizeof(Neigh) << endl;
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
free(vArray);
}
void print() override {
cout << "Done" << endl;
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
void insertEdge(EdgeArray<Neigh>* __restrict edgePtr, const Idx dstId, const Weight weight, u64& edgeCnt){
if(edgePtr->degree == edgePtr->capacity){
const u64 newCap = getNextPow2MinRet(edgePtr->capacity * 2);
Neigh* __restrict oldPtr = edgePtr->neighArr;
Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
edgePtr->capacity = newCap;
edgePtr->neighArr = newPtr;
if(edgePtr->degree > 0){
memcpy(newPtr, oldPtr, edgePtr->degree * sizeof(Neigh));
if(oldPtr != edgePtr->neigh){
globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh));
}
}
if(__builtin_expect(newCap == HYBRID_HASH_PARTITION, 0)){
//switch from linear to hashed mode
edgePtr->mapArr = (graphite_hashmap*)globalAllocator.allocate(sizeof(graphite_hashmap));
new (edgePtr->mapArr) graphite_hashmap();
//add existing nodes to hash
const Neigh* __restrict neighs = newPtr;
for(u64 i = 0; i < edgePtr->degree; i++){
(*edgePtr->mapArr)[neighs[i].node] = i;
}
}
}
//search for existing edge
if(!edgePtr->mapArr){
//using linear mode
Neigh* __restrict nn = nullptr;
for(u64 i = 0; i < edgePtr->degree; i++){
if(edgePtr->neighArr[i].node == dstId){
nn = edgePtr->neighArr + i;
break;
}
}
if(!nn){
//edge not found, insert
edgePtr->neighArr[edgePtr->degree].node = dstId;
edgePtr->neighArr[edgePtr->degree].setWeight(weight);
edgePtr->degree++;
edgeCnt++;
}
else{
//edge found, update
nn->setWeight(weight);
}
}
else {
//using hashed mode
const auto& it = edgePtr->mapArr->find(dstId);
if(it == edgePtr->mapArr->end()){
//edge not found, insert
Neigh& nn = edgePtr->neighArr[edgePtr->degree];
nn.node = dstId;
nn.setWeight(weight);
(*edgePtr->mapArr)[dstId] = edgePtr->degree;
edgePtr->degree++;
edgeCnt++;
}
else{
//edge found, update weight
edgePtr->neighArr[it->second].setWeight(weight);
}
}
}
void update(const EdgeList& el) override {
const u64 batchSize = el.size();
#ifdef _OPENMP
int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
i64 targetTh = (src / 64) & thMask;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
//insert out edge
insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
targetTh = (dst / 64) & thMask;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
//insert in edge
u64 garbase;
insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbase);
}
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
//insert out edge
insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
u64 garbage;
insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbage);
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_HYBRID_HASHMAP_WITH_GROUPING_AND_EDGE_ARR_LOCKING
Vertex<Neigh>* vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)aligned_alloc(64, numNodes * sizeof(Vertex<Neigh>));
//memset(vArray, 0, numNodes * sizeof(Vertex<Neigh>));
for(u64 i = 0; i < numNodes; i++){
vArray[i].inEdges.degree = 0;
vArray[i].inEdges.capacity = 0;
vArray[i].inEdges.neighArr = nullptr;
vArray[i].inEdges.mapArr = nullptr;
vArray[i].outEdges.degree = 0;
vArray[i].outEdges.capacity = 0;
vArray[i].outEdges.neighArr = nullptr;
vArray[i].outEdges.mapArr = nullptr;
#ifdef _OPENMP
omp_init_lock(&vArray[i].inEdges.lock);
omp_init_lock(&vArray[i].outEdges.lock);
#endif
}
cout << "Size of Vertex: " << sizeof(Vertex<Neigh>) << endl;
cout << "Size of ThreadInfo: " << sizeof(ThreadInfo) << endl;
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
free(vArray);
}
void print() override {
cout << "Done" << endl;
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
void insertEdge(EdgeArray<Neigh>* __restrict edgePtr, const Idx dstId, const Weight weight, u64& edgeCnt){
if(edgePtr->degree == edgePtr->capacity){
const u64 newCap = getNextPow2MinRet(edgePtr->capacity * 2);
Neigh* __restrict oldPtr = edgePtr->neighArr;
Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
edgePtr->capacity = newCap;
edgePtr->neighArr = newPtr;
if(edgePtr->degree > 0){
memcpy(newPtr, oldPtr, edgePtr->degree * sizeof(Neigh));
globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh));
}
if(__builtin_expect(newCap == HYBRID_HASH_PARTITION, 0)){
//switch from linear to hashed mode
edgePtr->mapArr = (graphite_hashmap*)globalAllocator.allocate(sizeof(graphite_hashmap));
new (edgePtr->mapArr) graphite_hashmap();
//add existing nodes to hash
const Neigh* __restrict neighs = newPtr;
for(u64 i = 0; i < edgePtr->degree; i++){
(*edgePtr->mapArr)[neighs[i].node] = i;
}
}
}
//search for existing edge
if(!edgePtr->mapArr){
//using linear mode
Neigh* __restrict nn = nullptr;
for(u64 i = 0; i < edgePtr->degree; i++){
if(edgePtr->neighArr[i].node == dstId){
nn = edgePtr->neighArr + i;
break;
}
}
if(!nn){
//edge not found, insert
edgePtr->neighArr[edgePtr->degree].node = dstId;
edgePtr->neighArr[edgePtr->degree].setWeight(weight);
edgePtr->degree++;
edgeCnt++;
}
else{
//edge found, update
nn->setWeight(weight);
}
}
else {
//using hashed mode
const auto& it = edgePtr->mapArr->find(dstId);
if(it == edgePtr->mapArr->end()){
//edge not found, insert
Neigh& nn = edgePtr->neighArr[edgePtr->degree];
nn.node = dstId;
nn.setWeight(weight);
(*edgePtr->mapArr)[dstId] = edgePtr->degree;
edgePtr->degree++;
edgeCnt++;
}
else{
//edge found, update weight
edgePtr->neighArr[it->second].setWeight(weight);
}
}
}
void update(const EdgeList& el) override {
const u64 batchSize = el.size();
#pragma omp parallel for
for(u64 i = 0; i < batchSize; i++){
const Edge e = el[i];
const int th = omp_get_thread_num();
if(!e.sourceExists){
thInfo[th].nodeCnt++;
}
if(!e.destExists){
thInfo[th].nodeCnt++;
}
if(!affected[e.source]){
affected[e.source] = true;
}
if(!affected[e.destination]){
affected[e.destination] = true;
}
//take a lock on the out edge of src
omp_set_lock(&vArray[e.source].outEdges.lock);
//insert outgoing edge
insertEdge(&vArray[e.source].outEdges, e.destination, e.weight, thInfo[th].edgeCnt);
//release lock
omp_unset_lock(&vArray[e.source].outEdges.lock);
//take a lock on the incoming edge of dest
omp_set_lock(&vArray[e.destination].inEdges.lock);
//insert incoming edge
u64 garbage;
insertEdge(&vArray[e.destination].inEdges, e.source, e.weight, garbage);
//release lock
omp_unset_lock(&vArray[e.destination].inEdges.lock);
}
//#ifdef _OPENMP
// int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
//
// #pragma omp parallel
// for(u64 i = 0; i < batchSize; i++){
// const i64 src = el[i].source;
// const i64 dst = el[i].destination;
// const i64 actualTh = omp_get_thread_num();
//
// i64 targetTh = (src / 64) & thMask;
// if(targetTh == actualTh){
// if(!el[i].sourceExists){
// thInfo[actualTh].nodeCnt++;
// }
// if(!el[i].destExists){
// thInfo[actualTh].nodeCnt++;
// }
//
// if(!affected[src]){
// affected[src] = true;
// }
//
// //insert out edge
// insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[actualTh].edgeCnt);
// }
//
// targetTh = (dst / 64) & thMask;
// if(targetTh == actualTh){
// if(!affected[dst]){
// affected[dst] = true;
// }
// //insert in edge
// u64 garbase;
// insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbase);
// }
//
// }
//#else
// for(u64 i = 0; i < batchSize; i++){
// const u64 src = el[i].source;
// const u64 dst = el[i].destination;
//
// if(!el[i].sourceExists){
// thInfo[0].nodeCnt++;
// }
// if(!el[i].destExists){
// thInfo[0].nodeCnt++;
// }
// if(!affected[src]){
// affected[src] = true;
// }
// if(!affected[dst]){
// affected[dst] = true;
// }
//
// //insert out edge
// insertEdge(&vArray[src].outEdges, dst, el[i].weight, thInfo[0].edgeCnt);
//
// //insert in edge
// u64 garbage;
// insertEdge(&vArray[dst].inEdges, src, el[i].weight, garbage);
// }
//#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_ONLY_HASHMAP
VertexArray<Neigh> vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray.resize(numNodes);
#pragma omp parallel for
for(u64 i = 0; i < numNodes; i++){
vArray.outDegree[i] = 0;
vArray.outCapacity[i] = 0;
vArray.outNeighArr[i] = nullptr;
vArray.inDegree[i] = 0;
vArray.inCapacity[i] = 0;
vArray.inNeighArr[i] = nullptr;
}
//vArray.usingHash.resize(numNodes, false);
//vArray.dstLocMap.resize(numNodes);
cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl;
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
}
void print() override {
cout << "Done" << endl;
}
int64_t in_degree(NodeID n) override {
return vArray.inDegree[n];
}
int64_t out_degree(NodeID n) override {
return vArray.outDegree[n];
}
void insertEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, graphite_hashmap __restrict &locMap, const Idx dstId, const Weight weight, u64& edgeCnt){
if(deg == cap){
const u64 newCap = getNextPow2MinRet(cap * 2);
Neigh* __restrict oldPtr = neighs;
Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
cap = newCap;
neighs = newPtr;
if(deg > 0){
memcpy(newPtr, oldPtr, deg * sizeof(Neigh));
globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh));
}
}
//using hashed mode
const auto& it = locMap.find(dstId);
if(it == locMap.end()){
//edge not found, insert
Neigh& nn = neighs[deg];
nn.node = dstId;
nn.setWeight(weight);
locMap[dstId] = deg;
deg++;
edgeCnt++;
}
else{
//edge found, update weight
neighs[it->second].setWeight(weight);
}
}
void update(const EdgeList& el) override {
const u64 batchSize = el.size();
#ifdef _OPENMP
int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
i64 targetTh = (src / 64) & thMask;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
//insert out edge
insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
targetTh = (dst / 64) & thMask;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
//insert in edge
u64 garbase;
insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, el[i].weight, garbase);
}
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
//we do not need atomic operation on affected as long as "some" thread updates it
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
//insert out edge
insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], vArray.outMapArr[src], dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
u64 garbage;
insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], vArray.inMapArr[dst], src, el[i].weight, garbage);
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
// void insertEdge(Idx srcId, Idx dstId, Weight weight, int thId){
// const u64 deg = vArray.outDegree[srcId];
//
// if(__builtin_expect(deg == vArray.outCapacity[srcId], 0)){
// const u64 newCap = getNextPow2(vArray.outCapacity[srcId] * 2);
//
//
// Neigh* __restrict oldPtr = vArray.outNeighArr[srcId];
// Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
//
// vArray.outCapacity[srcId] = newCap;
// vArray.outNeighArr[srcId] = newPtr;
//
// if(deg > 0){
// memcpy(newPtr, oldPtr, deg * sizeof(Neigh));
// globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh));
// }
//
// if(__builtin_expect(newCap == HYBRID_HASH_PARTITION, 0)){
// //switch from linear to hashed mode
// graphite_hashmap* __restrict hashPtr = (graphite_hashmap*)globalAllocator.allocate(sizeof(graphite_hashmap));
// new (hashPtr) graphite_hashmap();
//
// vArray.outMapArr[srcId] = hashPtr;
//
// //add existing nodes to hash
// const Neigh* __restrict neighs = newPtr;
// for(u64 i = 0; i < deg; i++){
// (*hashPtr)[neighs[i].node] = i;
// }
// }
// }
//
// //search for existing edge
// graphite_hashmap* __restrict locMap = vArray.outMapArr[srcId];
// Neigh* __restrict neigh = vArray.outNeighArr[srcId];
//
// if(!locMap){
// //using linear mode
// Neigh* __restrict nn = nullptr;
// for(u64 i = 0; i < deg; i++){
// if(neigh[i].node == dstId){
// nn = neigh + i;
// break;
// }
// }
// if(!nn){
// //edge not found, insert
// neigh[deg].node = dstId;
// neigh[deg].setWeight(weight);
// vArray.outDegree[srcId]++;
//
// thInfo[thId].edgeCnt++;
// }
// else{
// //edge found, update
// nn->setWeight(weight);
// }
// }
// else {
// //using hashed mode
// const auto& it = locMap->find(dstId);
// if(it == locMap->end()){
// //edge not found, insert
// Neigh& nn = neigh[deg];
// nn.node = dstId;
// nn.setWeight(weight);
// (*locMap)[dstId] = deg;
// vArray.outDegree[srcId]++;
//
// thInfo[thId].edgeCnt++;
// }
// else{
// //edge found, update weight
// neigh[it->second].setWeight(weight);
// }
// }
//
// //we do not need atomic operation on affected as long as "some" thread updates it
// if(!affected[srcId]){
// affected[srcId] = true;
// }
// if(!affected[dstId]){
// affected[dstId] = true;
// }
// }
#endif
#ifdef USE_ONLY_LINEAR
VertexArray<Neigh> vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray.resize(numNodes);
#pragma omp parallel for
for(u64 i = 0; i < numNodes; i++){
vArray.outDegree[i] = 0;
vArray.outCapacity[i] = 0;
vArray.outNeighArr[i] = nullptr;
vArray.inDegree[i] = 0;
vArray.inCapacity[i] = 0;
vArray.inNeighArr[i] = nullptr;
}
cout << "Sizeof ThreadInfo: " << sizeof(ThreadInfo) << endl;
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
}
int64_t in_degree(NodeID n) override {
return vArray.inDegree[n];
}
int64_t out_degree(NodeID n) override {
return vArray.outDegree[n];
}
void insertEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, const Idx dstId, const Weight weight, u64& edgeCnt){
insTot++;
if(deg == cap){
const u64 newCap = getNextPow2MinRet(cap * 2);
Neigh* __restrict oldPtr = neighs;
Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
cap = newCap;
neighs = newPtr;
if(deg > 0){
memcpy(newPtr, oldPtr, deg * sizeof(Neigh));
globalAllocator.freePow2(oldPtr, newCap / 2 * sizeof(Neigh));
}
}
//search for existing edge
Neigh* __restrict nn = nullptr;
for(u64 i = 0; i < deg; i++){
if(neighs[i].node == dstId){
nn = neighs + i;
break;
}
}
if(!nn){
//edge not found, insert
neighs[deg].node = dstId;
neighs[deg].setWeight(weight);
deg++;
edgeCnt++;
insSucc++;
}
else{
//edge found, update
nn->setWeight(weight);
}
}
void deleteEdge(u64& deg, u64& cap, Neigh* __restrict &neighs, const Idx dstId, u64& edgeCnt){
delTot++;
//search for existing edge
Neigh* __restrict nn = nullptr;
for(u64 i = 0; i < deg; i++){
if(neighs[i].node == dstId){
nn = neighs + i;
break;
}
}
if(!nn){
//edge not found, return
return;
}
else{
//edge found, delete
deg--;
edgeCnt--;
delSucc++;
*nn = neighs[deg];
}
if((cap > 4) && (deg * 4) <= cap){
//reduce size
const u64 newCap = cap / 2;
Neigh* __restrict oldPtr = neighs;
Neigh* __restrict newPtr = (Neigh*)globalAllocator.allocPow2(newCap * sizeof(Neigh));
cap = newCap;
neighs = newPtr;
memcpy(newPtr, oldPtr, deg * sizeof(Neigh));
globalAllocator.freePow2(oldPtr, newCap * 2 * sizeof(Neigh));
}
}
void update(const EdgeList& el) override {
const u64 batchSize = el.size();
#ifdef _OPENMP
int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
i64 targetTh = (src / 64) & thMask;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!el[i].isDelete){
//insert out edge
insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], dst, el[i].weight, thInfo[actualTh].edgeCnt);
}
else{
//delete out edge
deleteEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], dst, thInfo[actualTh].edgeCnt);
}
}
targetTh = (dst / 64) & thMask;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert in edge
insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], src, el[i].weight, garbage);
}
else{
//delete in edge
deleteEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], src, garbage);
}
}
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
//we do not need atomic operation on affected as long as "some" thread updates it
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert out edge
insertEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], dst, el[i].weight, thInfo[0].edgeCnt);
//insert in edge
insertEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], src, el[i].weight, garbage);
}
else{
//delete out edge
deleteEdge(vArray.outDegree[src], vArray.outCapacity[src], vArray.outNeighArr[src], dst, thInfo[0].edgeCnt);
//delete in edge
deleteEdge(vArray.inDegree[dst], vArray.inCapacity[dst], vArray.inNeighArr[dst], src, garbage);
}
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_CAHCE_FRIENDLY_HASH
#include "GraphTangoHash.h"
Vertex<Neigh>* vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)aligned_alloc(64, numNodes * sizeof(Vertex<Neigh>));
for(u64 i = 0; i < numNodes; i++){
Vertex<Neigh>& v = vArray[i];
v.inEdges.degree = 0;
v.inEdges.capacity = NUM_INITIAL_ELEMS;
v.inEdges.neighArr = v.inEdges.neigh;
v.outEdges.degree = 0;
v.outEdges.capacity = NUM_INITIAL_ELEMS;
v.outEdges.neighArr = v.outEdges.neigh;
}
cout << "Size of GraphTangoHash: " << sizeof(GraphTangoHash<Neigh>) << endl;
cout << "Size of Vertex: " << sizeof(Vertex<Neigh>) << endl;
cout << "Size of ThreadInfo: " << sizeof(ThreadInfo) << endl;
cout << "Size of Neigh: " << sizeof(Neigh) << endl;
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
free(vArray);
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
void update(const EdgeList& el) override {
const u64 batchSize = el.size();
#ifdef _OPENMP
int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
i64 targetTh = (src / 64) & thMask;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
//insert out edge
vArray[src].outEdges.insert(dst, thInfo[actualTh].edgeCnt);
}
targetTh = (dst / 64) & thMask;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
//insert in edge
u64 garbage;
vArray[dst].inEdges.insert(src, garbage);
}
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
//insert out edge
vArray[src].outEdges.insert(dst, thInfo[0].edgeCnt);
//insert in edge
u64 garbage;
vArray[dst].inEdges.insert(src, garbage);
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
#ifdef USE_CAHCE_FRIENDLY_HASH_ONLY
#include "GraphTangoHash.h"
Vertex<Neigh>* vArray;
const int num_threads;
typedef struct{
u64 edgeCnt = 0;
u64 nodeCnt = 0;
u8 pad[48];
} ThreadInfo;
alignas(64) ThreadInfo thInfo[32];
GraphTango(bool weighted, bool directed, i64 numNodes, i64 numThreads) : dataStruc(weighted, directed), num_threads(numThreads){
#ifdef _OPENMP
if(numThreads > 0){
omp_set_num_threads(numThreads);
}
#endif
vArray = (Vertex<Neigh>*)aligned_alloc(64, numNodes * sizeof(Vertex<Neigh>));
for(u64 i = 0; i < numNodes; i++){
Vertex<Neigh>& v = vArray[i];
v.inEdges.degree = 0;
v.inEdges.adjList = v.inEdges.neigh;
//v.inEdges.capacity = NUM_INITIAL_ELEMS * 2;
//v.inEdges.neighArr = v.inEdges.neigh;
v.outEdges.degree = 0;
v.outEdges.adjList = v.outEdges.neigh;
//v.outEdges.capacity = NUM_INITIAL_ELEMS * 2;
//v.outEdges.neighArr = v.outEdges.neigh;
}
cout << "Size of GraphTangoHash: " << sizeof(GraphTangoHash<Neigh>) << endl;
cout << "Size of Vertex: " << sizeof(Vertex<Neigh>) << endl;
cout << "Size of ThreadInfo: " << sizeof(ThreadInfo) << endl;
cout << "Size of Neigh: " << sizeof(Neigh) << endl;
property.resize(numNodes, -1);
affected.resize(numNodes);
affected.fill(false);
}
~GraphTango(){
free(vArray);
}
int64_t in_degree(NodeID n) override {
return vArray[n].inEdges.degree;
}
int64_t out_degree(NodeID n) override {
return vArray[n].outEdges.degree;
}
void update(const EdgeList& el) override {
const u64 batchSize = el.size();
#ifdef _OPENMP
int thMask = (1 << getNextPow2Log2(num_threads)) - 1;
#pragma omp parallel
for(u64 i = 0; i < batchSize; i++){
const i64 src = el[i].source;
const i64 dst = el[i].destination;
const i64 actualTh = omp_get_thread_num();
i64 targetTh = (src / 64) & thMask;
if(targetTh == actualTh){
if(!el[i].sourceExists){
thInfo[actualTh].nodeCnt++;
}
if(!el[i].destExists){
thInfo[actualTh].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!el[i].isDelete){
//insert out edge
vArray[src].outEdges.insert(dst, thInfo[actualTh].edgeCnt);
}
else{
//delete out edge
vArray[src].outEdges.erase(dst, thInfo[actualTh].edgeCnt);
}
}
targetTh = (dst / 64) & thMask;
if(targetTh == actualTh){
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert in edge
vArray[dst].inEdges.insert(src, garbage);
}
else{
//delete in edge
vArray[dst].inEdges.erase(src, garbage);
}
}
}
#else
for(u64 i = 0; i < batchSize; i++){
const u64 src = el[i].source;
const u64 dst = el[i].destination;
if(!el[i].sourceExists){
thInfo[0].nodeCnt++;
}
if(!el[i].destExists){
thInfo[0].nodeCnt++;
}
if(!affected[src]){
affected[src] = true;
}
if(!affected[dst]){
affected[dst] = true;
}
u64 garbage;
if(!el[i].isDelete){
//insert out edge
vArray[src].outEdges.insert(dst, thInfo[0].edgeCnt);
//insert in edge
vArray[dst].inEdges.insert(src, garbage);
}
else{
//delete out edge
vArray[src].outEdges.erase(dst, thInfo[0].edgeCnt);
//delete in edge
vArray[dst].inEdges.erase(src, garbage);
}
}
#endif
for(u64 i = 0; i < num_threads; i++){
num_edges += thInfo[i].edgeCnt;
thInfo[i].edgeCnt = 0;
num_nodes += thInfo[i].nodeCnt;
thInfo[i].nodeCnt = 0;
}
//num_nodes = el[batchSize - 1].lastAssignedId + 1;
}
#endif
// void insertEdge(Idx srcId, Idx dstId, const EProp& eProp){
// const u64 deg = vArray.getOutDegree(srcId);
//
// if(__builtin_expect(deg == vArray.getCapacity(srcId), 0)){
// const u64 newCap = vArray.getCapacity(srcId) * 2;
//
//
// Idx* __restrict dstOld = vArray.getDstIdArray(srcId);
//
//#ifdef HAS_EDGE_PROP
// EProp* __restrict propOld = vSoA.ePropArr[offset];
// Idx* __restrict dstNew = (Idx*)globalAllocator.allocPow2(newCap * (sizeof(Idx) + sizeof(EProp)));
// EProp* __restrict propNew = (EProp*)(dstNew + newCap);
// //EProp* __restrict propNew = (EProp*)globalAllocator.allocPow2(newCap * sizeof(EProp));
//#else
// Idx* __restrict dstNew = (Idx*)globalAllocator.allocPow2(newCap * sizeof(Idx));
//#endif
//
// for(U64 i = 0; i < deg; i++){
// dstNew[i] = dstOld[i];
//#ifdef HAS_EDGE_PROP
// propNew[i] = propOld[i];
//#endif
// }
//
//#ifdef HAS_EDGE_PROP
// globalAllocator.freePow2(dstOld, newCap / 2 * (sizeof(Idx) + sizeof(EProp)));
//#else
// globalAllocator.freePow2(dstOld, newCap / 2 * (sizeof(Idx)));
//#endif
// //globalAllocator.freePow2(dstOld, newCap / 2 * sizeof(Idx));
// //globalAllocator.freePow2(propOld, newCap / 2 * sizeof(EProp));
//
//#if defined(USE_FULL_HASHMAP) || defined(USE_HYBRID_HASH_V2)
// vArray.dstLocMap[srcId][0].reserve(newCap);
//#endif
// vArray.setCapacity(srcId, newCap);
// vArray.setDstIdArray(srcId, dstNew);
//#ifdef HAS_EDGE_PROP
// vSoA.ePropArr[offset] = propNew;
//#endif
// }
//
//#if defined(USE_FULL_HASHMAP)
// vSoA.dstLocMap[offset][dstId] = deg;
//#elif defined(USE_HYBRID_HASHMAP)
// if(deg >= HYBRID_HASH_PARTITION) {
// vSoA.dstLocMap[offset][dstId] = deg;
// }
//#elif defined(USE_HYBRID_HASH_V2)
// if(vArray.dstLocMap[srcId] != nullptr) {
// vArray.dstLocMap[srcId][0][dstId] = deg;
// }
// else if(deg >= HYBRID_HASH_THRESHOLD){
// vArray.dstLocMap[srcId] = new graphite_hashmap;
// vArray.dstLocMap[srcId][0][dstId] = deg;
// }
//
//#endif
//
// vArray.getDstIdArray(srcId)[deg] = dstId;
//#ifdef HAS_EDGE_PROP
// vSoA.ePropArr[offset][deg] = eProp;
//#endif
// vArray.getOutDegree(srcId)++;
// }
// void deleteEdge(Idx srcId, Idx dstId){
// Idx* __restrict dstIdArr = vArray.getDstIdArray(srcId);
//
//#ifdef HAS_EDGE_PROP
// EProp* __restrict ePropArr = vSoA.ePropArr[offset];
//#endif
//
// if(vArray.getOutDegree(srcId)){
//#if defined(USE_FULL_HASHMAP)
// const auto& dstIt = vSoA.dstLocMap[offset].find(dstId);
// if(dstIt != vSoA.dstLocMap[offset].end()){
// const Idx dstLoc = dstIt->second;
// vSoA.dstLocMap[offset].erase(dstIt);
// const Idx outDeg = --vSoA.outDegree[offset];
// if(__builtin_expect(outDeg != dstLoc, 1)){ //not the last element
// dstIdArr[dstLoc] = dstIdArr[outDeg];
//#ifdef HAS_EDGE_PROP
// ePropArr[dstLoc] = ePropArr[outDeg];
//#endif
// vSoA.dstLocMap[offset][dstIdArr[outDeg]] = dstLoc;
// }
// }
//#elif defined(USE_SORTED_EDGES)
// // First thing first, find the location of the dst node
// const Idx outDeg = vSoA.outDegree[offset] - 1;
// const Idx lastDstId = dstIdArr[outDeg];
// if(__builtin_expect(lastDstId != dstId, 1)){ //not the last element
// const u64 sortedLen = vSoA.sortedLen[offset];
// u64 dstLoc = lower_bound(dstIdArr, dstIdArr + sortedLen, dstId) - dstIdArr;
// if((dstLoc == sortedLen) || (dstIdArr[dstLoc] != dstId)){ //not found in the sorted region, linear search rest
// dstLoc = sortedLen - 1;
// while(dstIdArr[++dstLoc] != dstId && dstLoc < outDeg);
// }
//
// if(__builtin_expect(dstLoc != outDeg, 1)){
// //found
// dstIdArr[dstLoc] = dstIdArr[outDeg];
//#ifdef HAS_EDGE_PROP
// ePropArr[dstLoc] = ePropArr[outDeg];
//#endif
// vSoA.outDegree[offset]--;
// }
// }
// else{ //last element
// vSoA.outDegree[offset]--;
// }
//
// // sorted len goes over the out degree. Adjust.
// if(vSoA.sortedLen[offset] > vSoA.outDegree[offset]){
// vSoA.sortedLen[offset]--;
// }
//
//#elif defined(USE_HYBRID_HASHMAP)
// const u64 outDeg = vSoA.outDegree[offset] - 1;
//
// if(dstIdArr[outDeg] == dstId){ //last element
// vSoA.outDegree[offset]--;
// if(outDeg >= HYBRID_HASH_PARTITION){
// vSoA.dstLocMap[offset].erase(dstId);
// }
// return;
// }
//
//
// u64 dstLoc = -1;
//
// if(outDeg >= HYBRID_HASH_PARTITION){
// const auto& dstIt = vSoA.dstLocMap[offset].find(dstId);
// if(dstIt != vSoA.dstLocMap[offset].end()){
// //found
// dstLoc = dstIt->second;
// vSoA.dstLocMap[offset].erase(dstIt);
// }
// }
//
// if(dstLoc == -1){ //not yet found, do linear search
// while(dstIdArr[++dstLoc] != dstId && dstLoc < outDeg);
// if(__builtin_expect(dstLoc == outDeg, 0)){
// //not found
// return;
// }
// }
//
//
//
// //valid dstLoc
// dstIdArr[dstLoc] = dstIdArr[outDeg];
//#ifdef HAS_EDGE_PROP
// ePropArr[dstLoc] = ePropArr[outDeg];
//#endif
// vSoA.dstLocMap[offset][dstIdArr[outDeg]] = dstLoc;
//
//#elif defined(USE_HYBRID_HASH_V2)
// if(vArray.dstLocMap[srcId] == nullptr){
// //Not using hashmap
// const Idx outDeg = vArray.getOutDegree(srcId) - 1;
// Idx lastDstId = dstIdArr[outDeg];
// if(__builtin_expect(lastDstId != dstId, 1)){ //not the last element
// u64 dstLoc = -1;
// while(dstIdArr[++dstLoc] != dstId && dstLoc < outDeg);
// if(__builtin_expect(dstLoc != outDeg, 1)){
// dstIdArr[dstLoc] = dstIdArr[outDeg];
//#ifdef HAS_EDGE_PROP
// ePropArr[dstLoc] = ePropArr[outDeg];
//#endif
// vArray.getOutDegree(srcId)--;
// }
// }
// else{
// vArray.getOutDegree(srcId)--; //last element
// }
// }
// else{
// //Using hashmap
// const auto& dstIt = vArray.dstLocMap[srcId]->find(dstId);
// if(dstIt != vArray.dstLocMap[srcId]->end()){
// const Idx dstLoc = dstIt->second;
// vArray.dstLocMap[srcId]->erase(dstIt);
// const Idx outDeg = --vArray.outDegree[srcId];
// if(__builtin_expect(outDeg != dstLoc, 1)){ //not the last element
// dstIdArr[dstLoc] = dstIdArr[outDeg];
//#ifdef HAS_EDGE_PROP
// ePropArr[dstLoc] = ePropArr[outDeg];
//#endif
// vArray.dstLocMap[srcId][0][dstIdArr[outDeg]] = dstLoc;
// }
// }
// }
//
//#else
// const Idx outDeg = vArray.getOutDegree(srcId) - 1;
// Idx lastDstId = dstIdArr[outDeg];
// if(__builtin_expect(lastDstId != dstId, 1)){ //not the last element
// u64 dstLoc = -1;
// while(dstIdArr[++dstLoc] != dstId && dstLoc < outDeg);
// if(__builtin_expect(dstLoc != outDeg, 1)){
// dstIdArr[dstLoc] = dstIdArr[outDeg];
//#ifdef HAS_EDGE_PROP
// ePropArr[dstLoc] = ePropArr[outDeg];
//#endif
// vArray.getOutDegree(srcId)--;
// }
// }
// else{
// vArray.getOutDegree(srcId)--; //last element
// }
//#endif
// }
// }
//
// void insertEdges(Idx srcId, U64 count, const Idx* __restrict dstIds, const EProp* __restrict eProps){
// Vertex& vv = vertices[srcId];
// VExtra& ve = vExtras[srcId];
//
// if(ve.eCap < (vv.outDeg + count)){
// ve.eCap = getNextPow2(vv.outDeg + count);
// Idx* __restrict dstOld = vv.dstArr;
// EProp* __restrict propOld = vv.ePropArr;
// vv.dstArr = (Idx*)aligned_alloc(64, ve.eCap * sizeof(Idx));
// vv.ePropArr = (EProp*)aligned_alloc(64, ve.eCap * sizeof(EProp));
// #pragma omp parallel for simd
// for(U64 i = 0; i < vv.outDeg; i++){
// vv.dstArr[i] = dstOld[i];
// vv.ePropArr[i] = propOld[i];
// }
// free(dstOld);
// free(propOld);
// ve.dstLocMap.reserve(ve.eCap);
// }
// #pragma omp parallel for
// for(U64 i = 0; i < count; i++){
// vv.ePropArr[vv.outDeg + i] = eProps[i];
// vv.dstArr[vv.outDeg + i] = dstIds[i];
// ve.dstLocMap[dstIds[i]] = i;
// }
// vv.outDeg += count;
// }
//typedef const vProp_t& (*processEdgeFunc)(const eProp_t& eProp, const vProp_t& srcProp, const vProp_t& dstProp);
//typedef const vProp_t& (*reduceFunc)(const vProp_t& temp, const vProp_t& res);
//---------------------------------- VERTEX ------------------------------------------
/*inline I64 insertVertex(const VProp& vProp = 0){
if(deletedVertices.empty()){
vProps.push_back(vProp);
outEdges.push_back(new EdgeArrayBlock<eProp_t>);
//valid.push_back(true);
return (vProps.size() - 1);
}
else{
I64 vidx = deletedVertices.top();
//valid[vidx] = true;
deletedVertices.pop();
return vidx;
}
}*/
/*U64 insertManyVertex(U64 count){
U64 startId = vertices.size();
vertices.resize(startId + count);
for(U64 i = 0; i < count; i++){
outEdges.push_back(new EdgeArrayBlock<eProp_t>);
//outEdges.push_back(new EdgeArrayVector<eProp_t>);
}
return startId;
}*/
// U64 insertManyVertex(const U64 count, const VProp& vProp = 0){
// const U64 startId = vSize;
// const U64 endId = vSize + count;
// if(vCap < endId){
// vCap = getNextPow2(endId);
// Vertex* __restrict newVer = (Vertex*)aligned_alloc(64, vCap * sizeof(Vertex));
// VExtra* __restrict newExt = (VExtra*)aligned_alloc(64, vCap * sizeof(VExtra));
// #pragma omp parallel for simd
// for(U64 i = 0; i < vSize; i++){
// newVer[i] = vertices[i];
// newExt[i] = vExtras[i];
// }
// free(vertices);
// free(vExtras);
// vertices = newVer;
// vExtras = newExt;
// }
// #pragma omp parallel for
// for(U64 i = startId; i < endId; i++){
// vertices[i].prop = vProp;
// vertices[i].outDeg = 0;
// vExtras[i].eCap = getNextPow2(0);
// vertices[i].dstArr = (Idx*)aligned_alloc(64, vExtras[i].eCap * sizeof(Idx));
// vertices[i].ePropArr = (EProp*)aligned_alloc(64, vExtras[i].eCap * sizeof(EProp));
// new (&vExtras[i].dstLocMap) std::unordered_map<Idx, U64>;
// }
// vSize = endId;
// return startId;
// }
/*inline void deleteVertex(I64 vIdx){
//TODO
const I64 cnt = valid.size();
for(I64 i = 0; i < cnt; i++){
if(valid[i]){
outEdges[i]->deleteEdge(vIdx);
}
}
}*/
/*inline vProp_t& getVProp(I64 vIdx) {
return vProps[vIdx];
}
inline const vProp_t& getVProp(I64 vIdx) const {
return vProps[vIdx];
}
inline void setVProp(I64 vIdx, const vProp_t &vProp){
vProps[vIdx] = vProp;
}
inline U64 getVCount() const {
return (vProps.size() - deletedVertices.size());
}
//----------------------------------- EDGE -------------------------------------------
inline void insertEdge(I64 srcId, I64 dstId, const eProp_t &eProp = {}){
//eCount++;
outEdges[srcId]->insertEdge(dstId, eProp);
}
inline void updateEdge(I64 srcId, I64 dstId, const eProp_t &eProp){
outEdges[srcId]->updateEdge(dstId, eProp);
}
inline void deleteEdge(I64 srcId, I64 dstId){
outEdges[srcId]->deleteEdge(dstId);
//eCount--;
}
inline eProp_t& getEProp(I64 srcId, I64 dstId){
return outEdges[srcId]->getEProp(dstId);
}
inline const eProp_t& getEProp(I64 srcId, I64 dstId) const {
return outEdges[srcId]->getEProp(dstId);
}
inline U64 getECount() const {
return eCount;
}
inline auto getEdgeArray(I64 srcId){
return outEdges[srcId];
}*/
//----------------------------------- ANALYTICS --------------------------------------
/*void run_analysis_algo(processEdgeFunc processEdge, reduceFunc reduce){
while(!activeVertices.empty()){
processing_phase(processEdge, reduce);
commit_phase();
}
}*/
// void run_bfs(I64 rootIdx){
// typedef struct {
// U64 outDeg;
// Idx* dstArr;
// } EdgeInfo;
//
// const U64 maxTh = omp_get_max_threads();
//
// std::vector<EdgeInfo> q;
// U64 qTail = 0;
//
// q.push_back({vertices[rootIdx].outDeg, vertices[rootIdx].dstArr});
// vertices[rootIdx].prop = 0;
//
// U64 iter = 1;
// while((q.size() - qTail) < maxTh) {
// const U64 qHeadOrig = q.size();
// for(U64 qT = qTail; qT < qHeadOrig; qT++){
// //pop qTail
// const EdgeInfo oe = q[qT];
// for(U64 i = 0; i < oe.outDeg; i++){
// const I64 dstId = oe.dstArr[i];
// if(vertices[dstId].prop > iter){
// vertices[dstId].prop = iter;
// q.push_back({vertices[dstId].outDeg, vertices[dstId].dstArr});
// }
// }
// }
// qTail = qHeadOrig;
// iter++;
// }
//
// typedef struct {
// std::vector<EdgeInfo> q;
// U64 qTail;
// U64 iter;
// U8 pad[24];
// } ThQ;
//
// std::vector<ThQ> qVec(maxTh);
//
// // Initialize
// for(U64 i = 0; i < maxTh; i++){
// qVec[i].qTail = 0;
// qVec[i].iter = iter;
// }
//
// //distribute vertices
// U64 idx = 0;
// for(U64 i = qTail; i < q.size(); i++){
// if(idx == maxTh){
// idx = 0;
// }
// qVec[idx].q.push_back(q[i]);
// idx++;
// }
//
//
// #pragma omp parallel
// {
// U64 th = omp_get_thread_num();
// std::vector<EdgeInfo>& q = qVec[th].q;
// U64& qTail = qVec[th].qTail;
// U64& iter = qVec[th].iter;
// while(q.size() - qTail) {
// const U64 qHeadOrig = q.size();
// for(U64 qT = qTail; qT < qHeadOrig; qT++){
// //pop qTail
// const EdgeInfo oe = q[qT];
// for(U64 i = 0; i < oe.outDeg; i++){
// const I64 dstId = oe.dstArr[i];
// if(vertices[dstId].prop > iter){
// vertices[dstId].prop = iter;
// q.push_back({vertices[dstId].outDeg, vertices[dstId].dstArr});
// }
// }
// }
// qTail = qHeadOrig;
// iter++;
// }
// }
// }
//
// void run_bfs_old(I64 rootIdx){
// typedef struct {
// U64 outDeg;
// Idx* dstArr;
// } EdgeInfo;
//
// EdgeInfo* __restrict q = (EdgeInfo*)aligned_alloc(64, vSize * sizeof(EdgeInfo));
// U64 qHead = 1;
// U64 qTail = 0;
//
// q[0] = {vertices[rootIdx].outDeg, vertices[rootIdx].dstArr};
// vertices[rootIdx].prop = 0;
//
// U64 iter = 1;
// while(qHead - qTail) {
// const U64 qHeadOrig = qHead;
// #pragma omp parallel for
// for(U64 qT = qTail; qT < qHeadOrig; qT++){
// //pop qTail
// const EdgeInfo& oe = q[qT];
// for(U64 i = 0; i < oe.outDeg; i++){
// const I64 dstId = oe.dstArr[i];
// if(vertices[dstId].prop > iter){
// vertices[dstId].prop = iter;
// U64 loc;
// #pragma omp atomic capture
// loc = qHead++;
// q[loc] = {vertices[dstId].outDeg, vertices[dstId].dstArr};
// }
// }
// }
// qTail = qHeadOrig;
// iter++;
// }
// }
/*void addVertexToWavefront(I64 vIdx){
activeVertices.push_back(vIdx);
}
inline void processing_phase(processEdgeFunc processEdge, reduceFunc reduce){
const U64 activeCount = activeVertices.size();
#pragma omp parallel for
for(U64 i = 0; i < activeCount; i++){
I64 srcId = activeVertices[i];
auto outEdgeArr = outEdges[srcId];
const U64 outEdgeCount = outEdgeArr.size();
const vProp_t& srcProp = vProps[srcId];
for(U64 i = 0; i < outEdgeCount; i++){
const auto edge = outEdgeArr->edges[i];
const vProp_t& res = processEdge(edge.eProp, srcProp, vProps[edge.dstId]);
vTempProps[edge.dstId] = reduce(vTempProps[edge.dstId], res);
}
}
}
inline void commit_phase(){
const U64 vertexCount = getVCount();
#pragma omp parallel for
for(U64 i = 0; i < vertexCount; i++){
if(vProps[i] != vTempProps[i]){
vProps[i] = vTempProps[i];
omp_set_lock(&lock);
activeVertices.push_back(i);
omp_unset_lock(&lock);
}
}
}*/
//----------------------------------- OTHERS -----------------------------------------
/*void compact(){
}
void garbage_collection(){
}*/
//static GraphTango* buildFromTextCSR(const std::string &fname){
//}
/*static u64 binSearch(const i64* sortedArr, i64 val, u64 s, u64 e){
if((e - s) <= 1){
i64 diffE = sortedArr[e * VECTOR_WIDTH] - val;
i64 diffS = val - sortedArr[s * VECTOR_WIDTH];
if(diffE < diffS){
return e;
}
return s;
}
u64 mid = (s + e) / 2;
u64 midVal = sortedArr[mid * VECTOR_WIDTH];
if(val == midVal){
return mid;
}
else if(val < midVal){
return binSearch(sortedArr, val, s, mid);
}
else {
return binSearch(sortedArr, val, mid, e);
}
}*/
// static GraphTango* buildFromStingerCSR(
// const i64 numThreads,
// const U64 nv,
// const U64 ne,
// const I64* __restrict off,
// const I64* __restrict ind,
// const I64* __restrict weight,
// const VProp& defaultProp = 0)
// {
// auto gra = new GraphTango<VProp, EProp>(numThreads);
//
// gra->vArray.resize(nv);
//
//
////
//// ofstream outf("edgelist.txt");
//// for(u64 v = 0; v < nv; v++){
//// const U64 deg = off[v + 1] - off[v];
//// const I64* __restrict indE = ind + off[v];
//// const I64* __restrict wgtE = weight + off[v];
//// for(u64 e = 0; e < deg; e++){
//// outf << v << " " << indE[e] << "\n";
//// }
//// }
//// outf.close();
//
//// struct {
//// u64 e = 0;
//// u8 pad[56];
//// } cnt[25];
////
////
//// const u64 perThEdge = ne / omp_get_max_threads();
//// const u64 nvVect = (nv + VECTOR_WIDTH - 1)/VECTOR_WIDTH;
//// #pragma omp parallel
//// {
//// u64 th = omp_get_thread_num();
//// u64 target = (th + 1) * perThEdge;
//// cnt[th+1].e = binSearch(off, target, 0, nvVect) * VECTOR_WIDTH;
//// }
////
//// auto& vArr = gra->vertexArray;
//// #pragma omp parallel
//// {
//// const u64 th = omp_get_thread_num();
//// for(u64 v = cnt[th].e; v < cnt[th+1].e; v++){
//// VertexSoA<VProp, EProp>& vSoA = vArr[v / VECTOR_WIDTH];
//// const u64 offset = v % VECTOR_WIDTH;
//// const U64 deg = off[v + 1] - off[v];
//// vSoA.outDegree[offset] = deg;
////
//// const u64 cap = std::max(getNextPow2(deg), 4UL);
//// vSoA.capacity[offset] = cap;
////
//// vSoA.dstIdArr[offset] = (Idx*)globalAllocator.allocPow2(cap * sizeof(Idx));
//// vSoA.ePropArr[offset] = (EProp*)globalAllocator.allocPow2(cap * sizeof(EProp));
//// //vArr[v / VECTOR_WIDTH].dstIdArr[v % VECTOR_WIDTH] = (Idx*)aligned_alloc(64, cap * sizeof(Idx));
//// //vArr[v / VECTOR_WIDTH].ePropArr[v % VECTOR_WIDTH] = (EProp*)aligned_alloc(64, cap * sizeof(EProp));
////
//// new (&vSoA.dstLocMap[offset]) unordered_map<Idx, U64>;
//// vSoA.dstLocMap[offset].reserve(deg);
////
//// const I64* __restrict indE = ind + off[v];
//// const I64* __restrict wgtE = weight + off[v];
////
//// Idx* dstIdArr = vSoA.dstIdArr[offset];
//// EProp* ePropArr = vSoA.ePropArr[offset];
//// auto& dstLocMap = vSoA.dstLocMap[offset];
////
//// for(u64 e = 0; e < deg; e++){
//// ePropArr[e] = wgtE[e];
//// dstIdArr[e] = indE[e];
//// dstLocMap[ind[e]] = e;
//// }
////
//// }
//// }
//
// auto& vArr = gra->vArray;
// #pragma omp parallel for
// for(u64 v = 0; v < nv; v++){
// const U64 deg = off[v + 1] - off[v];
// vArr.setOutDegree(v, deg);
// vArr.setVProp(v, defaultProp);
// const u64 cap = getNextPow2(deg);
// vArr.setCapacity(v, cap);
//
//#ifdef HAS_EDGE_PROP
// vSoA.dstIdArr[offset] = (Idx*)globalAllocator.allocPow2(cap * (sizeof(Idx) + sizeof(EProp)));
// vSoA.ePropArr[offset] = (EProp*)(vSoA.dstIdArr[offset] + cap);
// //vSoA.ePropArr[offset] = (EProp*)globalAllocator.allocPow2(cap * sizeof(EProp));
//#else
// //vSoA.dstIdArr[offset] = (Idx*)globalAllocator.allocPow2(cap * sizeof(Idx));
// vArr.setDstIdArray(v, (Idx*)globalAllocator.allocPow2(cap * sizeof(Idx)));
//#endif
//
// const I64* __restrict indE = ind + off[v];
// const I64* __restrict wgtE = weight + off[v];
//
// I64* __restrict dstIdArr = vArr.getDstIdArray(v);
//#ifdef HAS_EDGE_PROP
// I64* __restrict ePropArr = vSoA.ePropArr[offset];
//#endif
//
//
//#if defined(USE_FULL_HASHMAP)
// auto& dstLocMap = vSoA.dstLocMap[offset];
// new (&dstLocMap) graphite_hashmap;
// dstLocMap.reserve(cap);
// for(u64 e = 0; e < deg; e++){
//#ifdef HAS_EDGE_PROP
// ePropArr[e] = wgtE[e];
//#endif
// dstIdArr[e] = indE[e];
// dstLocMap[ind[e]] = e;
// }
//#elif defined(USE_HYBRID_HASHMAP)
// u64 linearRegion = std::min(deg, HYBRID_HASH_PARTITION);
// for(u64 e = 0; e < linearRegion; e++){
//#ifdef HAS_EDGE_PROP
// ePropArr[e] = wgtE[e];
//#endif
// dstIdArr[e] = indE[e];
// }
// auto& dstLocMap = vSoA.dstLocMap[offset];
// new (&dstLocMap) graphite_hashmap;
// if(deg > HYBRID_HASH_PARTITION){
// dstLocMap.reserve(deg - HYBRID_HASH_PARTITION);
// for(u64 e = HYBRID_HASH_PARTITION; e < deg; e++){
//#ifdef HAS_EDGE_PROP
// ePropArr[e] = wgtE[e];
//#endif
// dstIdArr[e] = indE[e];
// dstLocMap[ind[e]] = e;
// }
// }
//#elif defined(USE_SORTED_EDGES)
// for(u64 e = 0; e < deg; e++){
//#ifdef HAS_EDGE_PROP
// ePropArr[e] = wgtE[e];
//#endif
// dstIdArr[e] = indE[e];
// }
// sort(dstIdArr, dstIdArr + deg);
// vSoA.sortedLen[offset] = deg;
//#elif defined(USE_HYBRID_HASH_V2)
// if(deg < HYBRID_HASH_THRESHOLD){
// //Do not use hashmap
// vArr.dstLocMap[v] = nullptr;
// for(u64 e = 0; e < deg; e++){
// const Idx dstId = indE[e];
//#ifdef HAS_EDGE_PROP
// ePropArr[e] = wgtE[e];
//#endif
// dstIdArr[e] = dstId;
// }
// }
// else{
// //Use hashmap
// //vArr.dstLocMap[v] = (graphite_hashmap*)globalAllocator.allocate(sizeof(graphite_hashmap));
// //new (&vArr.dstLocMap[v]) graphite_hashmap();
// vArr.dstLocMap[v] = new graphite_hashmap();
// for(u64 e = 0; e < deg; e++){
// const Idx dstId = indE[e];
//#ifdef HAS_EDGE_PROP
// ePropArr[e] = wgtE[e];
//#endif
// dstIdArr[e] = dstId;
// vArr.dstLocMap[v][0][dstId] = e;
// //vArr.dstLocMap[v]->at(dstId) = e;
// }
// }
//
//#else
// for(u64 e = 0; e < deg; e++){
// const Idx dstId = indE[e];
//#ifdef HAS_EDGE_PROP
// ePropArr[e] = wgtE[e];
//#endif
// dstIdArr[e] = dstId;
//#ifdef USE_INCOMING_EDGES
// omp_set_lock(&vArr.lock[dstId]);
// vArr.inEdges[dstId].push_back(v);
// omp_unset_lock(&vArr.lock[dstId]);
//#endif
// }
//#if defined(SORT_EDGES_AT_BUILD)
// std::sort(dstIdArr, dstIdArr + deg);
//#endif
//#endif
// }
//
// return gra;
// }
/*static GraphTango* buildFromCSC(const std::string &fname){
}
static GraphTango* buildFromCOO(const std::string &fname){
}*/
// void streamStingerActions(U64 naction, const I64* __restrict__ actions){
//
// std::vector<std::pair<u64, u64> > srcDst;
// for(u64 i = 0; i < naction; i++){
// long src = actions[i*2];
// if(src >= 0){
// srcDst.push_back({actions[i*2], actions[i*2 + 1]});
// }
// else{
// srcDst.push_back({~actions[i*2], ~actions[i*2 + 1]});
// }
//
// }
//
// cout << srcDst.size() << endl;
// cout << "===========insertions============" << endl;
//
// u64 iter = 0;
// u64 totEdge = 0;
// double totElp = 0.0;
//
// u64 nv = vArray.vSize;
//
// while(1){
// iter++;
// if(iter == 50){
// break;
// }
//
// tic();
// for(u64 i = 0; i < 1024*1024; i++){
// insertEdge(srcDst[totEdge].first, srcDst[totEdge].second, 1);
// totEdge++;
// }
// totElp += toc();
//
// cout << totEdge / 1000000.0 / totElp << endl;
// }
//
//
//
//
// cout << "===========Deletions============" << endl;
//
// iter = 0;
// totEdge = 0;
// totElp = 0.0;
//
// while(1){
// iter++;
// if(iter == 50){
// break;
// }
//
// tic();
// for(u64 i = 0; i < 1024*1024; i++){
// deleteEdge(srcDst[totEdge].first, srcDst[totEdge].second);
// totEdge++;
// }
// totElp += toc();
//
// cout << totEdge / 1000000.0 / totElp << endl;
// }
// //Divide work
// int numThreads = omp_get_max_threads();
// int maxTh = 1;
// while(maxTh <= numThreads){
// maxTh *= 2;
// }
// maxTh--;
//
// #pragma omp parallel num_threads(maxTh + 1)
// for(U64 i = 0; i < naction; i++) {
// I64 src = actions[i * 2];
// const I64 mask = 0UL - ((src >> 63) & 1UL);
// src = src ^ mask;
// int mappedTh = src & maxTh;
// if(omp_get_thread_num() == mappedTh){
// I64 dst = actions[i * 2 + 1] ^ mask;
// if(mask == 0UL){
// insertEdge(src, dst, 1);
// }
// else{
// deleteEdge(src, dst);
// }
// }
// }
// }
//similar to what is done by stinger (queue based)
// u64 run_bfs_v1(const Idx& root){
// Idx* __restrict activeList = (Idx*)globalAllocator.allocate(vArray.vSize * sizeof(Idx));
// u64 qHead = 1;
// u64 qTail = 0;
//
// activeList[0] = root;
// vArray.setVProp(root, 0);
//
// U64 iter = 1;
// while(qHead - qTail) {
// const U64 qHeadOrig = qHead;
// #pragma omp parallel for
// for(U64 qT = qTail; qT < qHeadOrig; qT++){
// //pop qTail
// const u64 vIdx = activeList[qT];
// const u64 outDeg = vArray.outDegree[vIdx];
// const Idx* __restrict dstIdArr = vArray.dstIdArr[vIdx];
// for(U64 i = 0; i < outDeg; i++){
// const I64 dstId = dstIdArr[i];
// if(vArray.prop[dstId] > iter){
// vArray.prop[dstId] = iter;
// U64 loc;
// #pragma omp atomic capture
// loc = qHead++;
// activeList[loc] = dstId;
// }
// }
// }
// qTail = qHeadOrig;
// iter++;
// }
// globalAllocator.deallocate(activeList, vArray.vSize * sizeof(Idx));
// return iter;
// }
//
//
// u64 run_bfs_v2(const Idx& root){
// const u64 numV = vArray.vSize;
//
// vector<bool> currAct(numV, 0);
// vector<bool> nextAct(numV, 0);
//
//
// vArray.setVProp(root, 0);
// currAct[root] = 1;
//
// u64 iter = 1;
// bool isChanged = true;
// while(isChanged){
// isChanged = false;
// #pragma omp parallel for num_threads(64)
// for(u64 v = 0; v < vArray.vSize; v++){
// if(currAct[v]){ //active
// currAct[v] = 0;
// const u64 outDeg = vArray.outDegree[v];
// const Idx* __restrict dstIdArr = vArray.dstIdArr[v];
// //how about using AVX here?
// for(U64 i = 0; i < outDeg; i++){
// const I64 dstId = dstIdArr[i];
// if(vArray.prop[dstId] > iter){
// vArray.prop[dstId] = iter;
// // make dstId active for next iter
// if(nextAct[dstId] == 0){ //checking this condition reduces thrashing
// nextAct[dstId] = 1;
// }
// isChanged = true;
// }
// }
// }
// }
// swap(currAct, nextAct);
// iter++;
// }
//
// return iter;
// }
//
//
// u64 run_bfs_v3(const Idx& root){
// const u64 numV = vArray.vSize;
//
// vector<bool> currAct(numV, 0); // wavefront for the current iter
// vector<bool> nextAct(numV, 0); // wavefront for the next iter
//
// currAct[root] = 1;
//
// u64 iter = 0;
// bool isChanged = true;
// while(isChanged){
// isChanged = false;
// #pragma omp parallel for num_threads(32)
// for(u64 v = 0; v < vArray.vSize; v++){
// if(__builtin_expect(currAct[v], 0)){
// currAct[v] = 0;
// if(vArray.prop[v] > iter){
// vArray.prop[v] = iter;
// isChanged = true;
// const u64 outDeg = vArray.outDegree[v];
// const Idx* __restrict dstIdArr = vArray.dstIdArr[v];
// for(U64 i = 0; i < outDeg; i++){
// if(nextAct[dstIdArr[i]] == 0){ //checking this condition should reduces thrashing
// nextAct[dstIdArr[i]] = 1;
// }
// }
// }
// }
// }
// swap(currAct, nextAct);
// iter++;
// }
//
// return iter;
// }
//
//
// u64 run_bfs_v4(const Idx& root){
// const u64 numV = vArray.vSize;
//
// vector<bool> currAct(numV, 0); // wavefront for the current iter
// vector<bool> nextAct(numV, 0); // wavefront for the next iter
// vector<bool> visited(numV, 0); // records visited vertices
//
// currAct[root] = 1;
//
// u64 iter = 0;
// bool isChanged = true;
// while(isChanged){
// isChanged = false;
// #pragma omp parallel for num_threads(32)
// for(u64 v = 0; v < vArray.vSize; v++){
// if (currAct[v]){
// currAct[v] = 0;
// vArray.prop[v] = iter; //update value
// isChanged = true;
// const u64 outDeg = vArray.outDegree[v];
// const Idx* __restrict dstIdArr = vArray.dstIdArr[v];
// for(U64 e = 0; e < outDeg; e++){
// const u64 dstId = dstIdArr[e];
// if(visited[dstId] == 0){
// visited[dstId] = 1;
// nextAct[dstId] = 1;
// }
// }
// }
// }
// swap(currAct, nextAct);
// iter++;
// }
//
// return iter;
// }
//
//
// //queue with visited bitset
// u64 run_bfs_v5(const Idx& root){
// setVPropAll(0xFFFF'FFFF'FFFF'FFFFUL);
// const u64 numV = vArray.vSize;
//
// Idx* __restrict activeList = (Idx*)globalAllocator.allocate(numV * sizeof(Idx));
// vector<bool> visited(numV, 0); // records visited vertices
// u64 qHead = 1;
// u64 qTail = 0;
//
// activeList[0] = root;
// vArray.setVProp(root, 0);
//
// U64 iter = 1;
// while(qHead - qTail) {
// const U64 qHeadOrig = qHead;
// #pragma omp parallel for num_threads(32)
// for(U64 qT = qTail; qT < qHeadOrig; qT++){
// //pop qTail
// const u64 vIdx = activeList[qT];
// const u64 outDeg = vArray.outDegree[vIdx];
// const Idx* __restrict dstIdArr = vArray.dstIdArr[vIdx];
// for(U64 i = 0; i < outDeg; i++){
// const I64 dstId = dstIdArr[i];
// if(!visited[dstId]){
// visited[dstId] = 1;
// vArray.prop[dstId] = iter;
// U64 loc;
// #pragma omp atomic capture
// loc = qHead++;
// activeList[loc] = dstId;
// }
// }
// }
// qTail = qHeadOrig;
// iter++;
// }
// globalAllocator.deallocate(activeList, vArray.vSize * sizeof(Idx));
// return iter;
// }
//
//
// // Same as stinger (incorrect version)
// u64 run_page_rank_v1(VProp epsilon, VProp dampingfactor, u64 maxIter){ //using outgoing edges (push)
//
// setVPropAll(1.0 / vArray.vSize);
// const VProp offset = (1.0 - dampingfactor) / vArray.vSize;
//
// VProp* vTemp = (VProp*)globalAllocator.allocate(vArray.vSize * sizeof(VProp));
//
// u64 iter = 0;
// VProp delta = 1.0;
//
// while(delta > epsilon && iter != maxIter){
//
// delta = 0.0;
//
// //processing phase
// #pragma omp parallel for reduction(+:delta)
// for(u64 v = 0; v < vArray.vSize; v++){
// vTemp[v] = 0;
// const u64 outDeg = vArray.outDegree[v];
// const Idx* __restrict dstIdArr = vArray.dstIdArr[v];
// for(u64 e = 0; e < outDeg; e++){
// const Idx dstId = dstIdArr[e];
// //if(vArray.outDegree[dstId]){ //outDegree of dst can be zero
// vTemp[v] += (vArray.prop[dstId] / vArray.outDegree[dstId]);
// //}
// }
// vTemp[v] = vTemp[v] * dampingfactor + offset;
// VProp myDelta = vTemp[v] - vArray.prop[v];
// if(myDelta < 0){
// myDelta = -myDelta;
// }
// delta += myDelta;
// }
//
// //apply phase
// #pragma omp parallel for
// for(u64 v = 0; v < vArray.vSize; v++){
// vArray.prop[v] = vTemp[v];
// }
//
// iter++;
// }
//
// return iter;
// }
//
//
// // correct version
// u64 run_page_rank_v2(VProp epsilon, VProp dampingfactor, u64 maxIter){ //using outgoing edges (push)
//
// setVPropAll(1.0 / vArray.vSize);
//
// VProp* vTemp = (VProp*)globalAllocator.allocate(vArray.vSize * sizeof(VProp));
// #pragma omp parallel for
// for(u64 v = 0; v < vArray.vSize; v++){
// vTemp[v] = 0;
// }
//
//
// u64 iter = 0;
//
// while(iter != maxIter){
//
// //processing phase
// #pragma omp parallel for
// for(u64 v = 0; v < vArray.vSize; v++){
// const u64 outDeg = vArray.outDegree[v];
// if(outDeg){
// const VProp pushVal = vArray.prop[v] / outDeg;
// const Idx* __restrict dstIdArr = vArray.dstIdArr[v];
// for(u64 e = 0; e < outDeg; e++){
// const u64 dstId = dstIdArr[e];
// #pragma omp atomic
// vTemp[dstId] += pushVal;
// }
// }
// }
//
// //apply phase
// #pragma omp parallel for
// for(u64 v = 0; v < vArray.vSize; v++){
// vArray.prop[v] = dampingfactor + (1 - dampingfactor) * vTemp[v];
// }
//
// iter++;
// }
//
// return iter;
// }
//
//
// u64 run_connected_components_v1(){
// const u64 numV = vArray.vSize;
// VProp* __restrict vProps = vArray.prop;
//
// #pragma omp parallel for
// for(u64 v = 0; v < numV; v++){
// vProps[v] = v;
// }
//
// while(1){
// bool isChanged = false;
// #pragma omp parallel for
// for(u64 v = 0; v < numV; v++){
// const u64 numE = vArray.outDegree[v];
// const Idx* __restrict dstIdArr = vArray.dstIdArr[v];
// for(u64 e = 0; e < numE; e++){
// const Idx dstId = dstIdArr[e];
// if(vProps[v] > vProps[dstId]){
// vProps[v] = vProps[dstId];
// isChanged = true;
// }
// }
// }
//
// if(!isChanged){
// break;
// }
//
// #pragma omp parallel for
// for(u64 v = 0; v < numV; v++){
// while(vProps[v] != vProps[vProps[v]]){
// vProps[v] = vProps[vProps[v]];
// }
// }
// }
//
// u64 components = 1;
// #pragma omp parallel for reduction(+:components)
// for(u64 v = 1; v < numV; v++){
// if(vProps[v] == v){
// components++;
// }
// }
//
// return components;
// }
//
//
//#ifdef USE_INCOMING_EDGES
// // correct version
// u64 run_page_rank_v3(VProp epsilon, VProp dampingfactor, u64 maxIter){ //using incoming edges (pull)
//
// setVPropAll(1.0 / vArray.vSize);
// VProp* vTemp = (VProp*)globalAllocator.allocate(vArray.vSize * sizeof(VProp));
//
// u64 iter = 0;
//
// while(iter != maxIter){
//
// #pragma omp parallel for
// for(u64 v = 0; v < vArray.vSize; v++){
// if(vArray.outDegree[v]){
// vArray.prop[v] = vArray.prop[v] / vArray.outDegree[v];
// }
// }
//
// #pragma omp parallel for
// for(u64 v = 0; v < vArray.vSize; v++){
// VProp sum = 0.0;
// const u64 inDeg = vArray.inEdges[v].size();
// const Idx* __restrict srcIdArr = vArray.inEdges[v].data();
// for(u64 e = 0; e < inDeg; e++){
// const Idx srcId = srcIdArr[e];
// sum += vArray.prop[srcId];
// }
// vTemp[v] = dampingfactor + (1 - dampingfactor) * sum;
// }
//
// #pragma omp parallel for
// for(u64 v = 0; v < vArray.vSize; v++){
// vArray.prop[v] = vTemp[v];
// }
//
// iter++;
// }
//
// return iter;
// }
//
//#endif
//
//
//
// void setVPropAll(const VProp& vProp) {
// #pragma omp parallel for
// for(u64 v = 0; v < vArray.vSize; v++){
// vArray.prop[v] = vProp;
// }
// }
};
|
GB_binop__pow_fp32.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__pow_fp32)
// A.*B function (eWiseMult): GB (_AemultB_08__pow_fp32)
// A.*B function (eWiseMult): GB (_AemultB_02__pow_fp32)
// A.*B function (eWiseMult): GB (_AemultB_04__pow_fp32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__pow_fp32)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__pow_fp32)
// C+=b function (dense accum): GB (_Cdense_accumb__pow_fp32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pow_fp32)
// C=scalar+B GB (_bind1st__pow_fp32)
// C=scalar+B' GB (_bind1st_tran__pow_fp32)
// C=A+scalar GB (_bind2nd__pow_fp32)
// C=A'+scalar GB (_bind2nd_tran__pow_fp32)
// C type: float
// A type: float
// A pattern? 0
// B type: float
// B pattern? 0
// BinaryOp: cij = GB_powf (aij, bij)
#define GB_ATYPE \
float
#define GB_BTYPE \
float
#define GB_CTYPE \
float
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
float aij = GBX (Ax, pA, A_iso)
// 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) \
float 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) \
float t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = GB_powf (x, y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
1
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_POW || GxB_NO_FP32 || GxB_NO_POW_FP32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__pow_fp32)
(
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__pow_fp32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__pow_fp32)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type float
float bwork = (*((float *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
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
float *restrict Cx = (float *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *restrict Cx = (float *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__pow_fp32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool 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) ;
float alpha_scalar ;
float beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((float *) alpha_scalar_in)) ;
beta_scalar = (*((float *) 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__pow_fp32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__pow_fp32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__pow_fp32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__pow_fp32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__pow_fp32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float *Cx = (float *) Cx_output ;
float x = (*((float *) x_input)) ;
float *Bx = (float *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
float bij = GBX (Bx, p, false) ;
Cx [p] = GB_powf (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__pow_fp32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
float *Cx = (float *) Cx_output ;
float *Ax = (float *) Ax_input ;
float y = (*((float *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
float aij = GBX (Ax, p, false) ;
Cx [p] = GB_powf (aij, y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
float aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_powf (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__pow_fp32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
float
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float x = (*((const float *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
float
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
float aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_powf (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__pow_fp32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
float y = (*((const float *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
openmp_pso.h | //
// Created by Zayd Hammoudeh on 10/24/20.
//
#ifndef SERIAL_OPENMP_PSO_H
#define SERIAL_OPENMP_PSO_H
#include <algorithm>
#include <cassert>
#include <cfloat>
#include <cinttypes>
#include <cstring>
#include <ctime>
#include <iostream>
#include <omp.h>
#include <random>
#include <sstream>
#include "base_pso.h"
#include "cpu_config.h"
#include "types_cpu_only.h"
#include "types_general.h"
template<class T>
class OmpParts {
private:
const IntType n_threads_;
const PartLens * part_lens_;
std::vector<T*> parts_;
public:
explicit OmpParts<T>(const PartLens * part_lens)
: n_threads_(part_lens->size()), part_lens_(part_lens) {
assert(this->n_threads_ > 0);
// Create the particle arrays
this->parts_ = std::vector<T*>(this->n_threads_);
for (IntType i = 0; i < this->n_threads_; i++) {
IntType len = (*this->part_lens_)[i];
assert(len > 0);
this->parts_[i] = new T[len];
}
}
/** Delete the particle container */
~OmpParts<T>() {
for (T* part : this->parts_)
delete part;
}
OmpParts<T>(const OmpParts<T> &other)
: n_threads_(other.n_threads_), part_lens_(other.part_lens_) {
// Create the particle arrays
this->parts_ = std::vector<T*>(this->n_threads_);
#pragma omp parallel for default(shared)
for (IntType i = 0; i < this->n_threads_; i++) {
IntType len = (*this->part_lens_)[i];
assert(len > 0);
T* arr = new T[len];
IntType n_bytes = len * sizeof(Param);
memcpy(arr, other.parts_[i], n_bytes);
this->parts_[i] = arr;
}
}
/** Get the array for the specified thread */
T* get(IntType thread_id) const {
assert(thread_id < this->n_threads_);
return this->parts_[thread_id];
}
/** Randomize the memory */
void randomize(const IntType thread_id, PRNG * prng, const Param lo = 0,
const Param hi = 1) const {
assert(thread_id < this->n_threads_);
T* mat = this->parts_[thread_id];
std::uniform_real_distribution<Param> dist(lo, hi);
IntType len = (*this->part_lens_)[thread_id];
for (IntType i = 0; i < len; i++)
mat[i] = dist(*prng);
}
/** Bound the particle locations within the configuration limits */
void clip(IntType tid, Param lo, Param hi) {
assert((long unsigned int)tid < this->parts_.size());
T* mat = this->parts_[tid];
IntType len = (*this->part_lens_)[tid];
for (IntType i = 0; i < len; i++)
mat[i] = std::min(hi, std::max(lo, mat[i]));
}
/** Scale the parameter value by a float */
void scale(IntType tid, Param scalar) {
T* mat = this->parts_[tid];
IntType len = (*this->part_lens_)[tid];
for (IntType i = 0; i < len; i++)
mat[i] *= scalar;
}
/** Sanity compatibility check */
bool isCompatible(const OmpParts<T> &other) const {
bool compat = this->n_threads_ == other.n_threads_;
return compat && this->part_lens_ == other.part_lens_; // part_lens_ checks pointers
}
/** Add the one particle value to the other */
void add(IntType tid, const Param scale, const OmpParts<T> * other) const {
// Sanity check the parameters
assert(tid < this->n_threads_);
assert(this->isCompatible(*other));
this->add(tid, scale, other->parts_[tid]);
}
void add(IntType tid, const Param scale, const T* arr) const {
IntType len = (*this->part_lens_)[tid];
T* mat = this->parts_[tid];
for (IntType i = 0; i < len; i++)
mat[i] += scale * arr[i];
}
};
template<class T>
class OpenmpPSO : public BasePSO<T, LossFunc<T>> {
private:
PRNG ** prngs_;
const IntType n_threads_;
/** Particle vectors */
OmpParts<T> * parts_;
/** Velocity vectors */
OmpParts<T> * velos_;
PartLens part_lens_;
/** Contains best parameters */
T* best_;
/** Simple method to construct the thread-specific seeds. Iterate to improve seed diversity */
void seedPRNGs() {
// Initialize thread specific RNGs
this->prngs_ = new PRNG*[this->n_threads_];
// seed_seq generates nearly u.a.r. seeds
std::seed_seq seq{time(nullptr)};
std::vector<std::uint32_t> seeds(this->n_threads_);
seq.generate(seeds.begin(), seeds.end());
// Did not parallelize here intentionally since operations so fast not worth the overhead
for (IntType i = 0; i < this->n_threads_; i++) {
this->prngs_[i] = new PRNG(seeds[i]);
if (this->config_->d())
std::cout << "Seed Thread #" << i << ": " << seeds[i] << "\n";
}
}
/** Copy the best vector into the memory */
void copyParticle(T* src, T* dest = nullptr) {
memcpy(dest, src, this->config_->dim() * sizeof(Param));
}
void fit_() {
// Random variables setting part directions
auto r_p = OmpParts<T>(&this->part_lens_);
auto r_g = OmpParts<T>(&this->part_lens_);
// Construct the best positions
OmpParts<T> pos_best = (*this->parts_); // Relies on copy constructor
this->updateBest(pos_best);
if (this->config_->d())
this->printBest(0);
for (IntType itr = 1; itr <= this->config_->n_iter(); itr++) {
#pragma omp parallel default(shared) // NOLINT(openmp-use-default-none)
{
IntType tid = omp_get_thread_num();
PRNG * prng = this->prngs_[tid];
r_p.randomize(tid, prng);
r_g.randomize(tid, prng);
this->velos_->scale(tid, this->config_->momentum()); // Attenuate the velocity
this->updateVeloWithDiff(tid, this->config_->rate_point(), r_p, pos_best);
this->updateVeloWithBest(tid, this->config_->rate_global(), r_g);
// Update the particle positions
this->parts_->add(tid, this->config_->lr(), this->velos_);
//Ensure that the points and velocities are within the valid grid
Param v_bound = this->config_->bound_hi() - this->config_->bound_lo();
this->velos_->clip(tid, -v_bound, v_bound);
this->parts_->clip(tid, this->config_->bound_lo(), this->config_->bound_hi());
}
this->updateBest(pos_best);
if (this->config_->d())
this->printBest(itr);
}
}
void updateBest(OmpParts<T> &pos_best) {
Param t_bl = this->best_loss_;
IntType dim = this->config_->dim();
#pragma omp parallel default(shared) firstprivate(t_bl) // NOLINT(openmp-use-default-none)
{
IntType tid = omp_get_thread_num();
IntType tot_len = this->part_lens_[tid];
T* t_parts = this->parts_->get(tid);
T* t_olds = pos_best.get(tid);
T* t_best = new T[this->config_->dim()];
for (IntType i = 0; i < tot_len; i += dim) {
T* p_cur = t_parts + i;
T* p_old = t_olds + i;
Param l_pos = this->config_->loss_func()(this->config_->dim(), *p_cur,
this->config_->n_ele(), *this->config_->ext_data(),
*this->config_->ext_labels());
Param l_old = this->config_->loss_func()(this->config_->dim(), *p_old,
this->config_->n_ele(), *this->config_->ext_data(),
*this->config_->ext_labels());
// Update the best position for this point
if (l_pos < l_old)
this->copyParticle(p_cur, p_old);
// Update the global best candidate
if (l_pos < t_bl) {
t_bl = l_pos;
this->copyParticle(p_cur, t_best);
}
}
// Update the overall best result
#pragma omp critical
{
if (t_bl < this->best_loss_) {
this->best_loss_ = t_bl;
this->copyParticle(t_best, this->best_);
}
}
}
}
/** Use the difference between teh point's best and its current position to update the velocity */
void updateVeloWithDiff(IntType tid, Param scalar, OmpParts<T> &r, OmpParts<T> &ref) {
// Ensure the shapes are compatible
assert(r.isCompatible(ref));
assert(this->velos_->isCompatible(r));
T* r_T = r.get(tid);
T* ref_T = ref.get(tid);
T* pos = this->parts_->get(tid);
IntType len = this->part_lens_[tid];
for (IntType i = 0; i < len; i++)
r_T[i] *= ref_T[i] - pos[i];
this->velos_->add(tid, scalar, r_T);
}
void updateVeloWithBest(IntType tid, Param scalar, OmpParts<T> &r) {
// Ensure the shapes are compatible
assert(this->velos_->isCompatible(r));
T* r_T = r.get(tid);
T* pos = this->parts_->get(tid);
T* best = this->getBest();
IntType dim = this->config_->dim();
IntType tot_len = this->part_lens_[tid];
for (IntType i = 0; i < tot_len; i++)
r_T[i] *= best[i % dim] - pos[i];
this->velos_->add(tid, scalar, r_T);
}
public:
explicit OpenmpPSO(CpuConfig<Param,T> *config, IntType n_threads)
: BasePSO<Param, LossFunc<T>>(config), n_threads_(n_threads) {
assert(this->n_threads_ > 0);
omp_set_num_threads(n_threads);
this->prngs_ = nullptr;
this->seedPRNGs();
// Define the length of each thread's parallel block
this->part_lens_ = PartLens(this->n_threads_);
IntType div = (this->config_->n_particle()) / (n_threads);
for (IntType i = 0; i < n_threads - 1; i++)
this->part_lens_[i] = this->config_->dim() * div;
// Handle last thread subset to ensure coverage of whole range
this->part_lens_[n_threads_ - 1] = this->config_->n_particle() - (n_threads_ - 1) * div;
this->part_lens_[n_threads_ - 1] *= this->config_->dim();
this->parts_ = new OmpParts<T>(&this->part_lens_);
this->velos_ = new OmpParts<T>(&this->part_lens_);
// Each threads set of particles can be randomized in parallel
#pragma omp parallel default(shared) // NOLINT(openmp-use-default-none)
{
IntType tid = omp_get_thread_num();
PRNG * prng = this->prngs_[tid];
Param v_max = this->config_->bound_hi() - this->config_->bound_lo();
this->parts_->randomize(tid, prng, this->config_->bound_lo(), this->config_->bound_hi());
this->velos_->randomize(tid, prng, -v_max, v_max);
};
this->best_ = new T[this->config_->dim()];
}
~OpenmpPSO() {
for (IntType i = 0; i < this->n_threads_; i++)
delete this->prngs_[i];
delete this->prngs_;
delete this->parts_;
delete this->velos_;
delete this->best_;
}
/** Returns copy of the best vector */
T* getBest() {
T* best = new T[this->config_->dim()];
this->copyParticle(this->best_, best);
return best;
}
void printBest(const IntType iter = -1) const {
assert(this->is_fit_);
std::cout << this->name();
if (iter >= 0)
std::cout << " Iter " << iter << ":";
for (IntType i = 0; i < this->config_->dim(); i++)
std::cout << " " << this->best_[i];
std::cout << " -- Loss: " << this->best_loss_ << std::endl;
}
/** Name of the serial class */
std::string name() const {
std::stringstream ss;
ss << "OpenMP-CPU(" << this->n_threads_ << ")";
return ss.str();
}
};
#endif //SERIAL_OPENMP_PSO_H
|
JeeIOrbitalSoA.h | //////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory
//
// File created by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory
//////////////////////////////////////////////////////////////////////////////////////
#ifndef QMCPLUSPLUS_EEIJASTROW_OPTIMIZED_SOA_H
#define QMCPLUSPLUS_EEIJASTROW_OPTIMIZED_SOA_H
#include "Configuration.h"
#if !defined(QMC_BUILD_SANDBOX_ONLY)
#include "QMCWaveFunctions/WaveFunctionComponent.h"
#endif
#include "Particle/DistanceTableData.h"
#include "CPU/SIMD/aligned_allocator.hpp"
#include "CPU/SIMD/algorithm.hpp"
#include <map>
#include <numeric>
namespace qmcplusplus
{
/** @ingroup WaveFunctionComponent
* @brief Specialization for three-body Jastrow function using multiple functors
*
*Each pair-type can have distinct function \f$u(r_{ij})\f$.
*For electrons, distinct pair correlation functions are used
*for spins up-up/down-down and up-down/down-up.
*/
template<class FT>
class JeeIOrbitalSoA : public WaveFunctionComponent
{
///type of each component U, dU, d2U;
using valT = typename FT::real_type;
///element position type
using posT = TinyVector<valT, OHMMS_DIM>;
///use the same container
using DistRow = DistanceTableData::DistRow;
using DisplRow = DistanceTableData::DisplRow;
///table index for el-el
const int ee_Table_ID_;
///table index for i-el
const int ei_Table_ID_;
//nuber of particles
int Nelec, Nion;
///number of particles + padded
size_t Nelec_padded;
//number of groups of the target particleset
int eGroups, iGroups;
///reference to the sources (ions)
const ParticleSet& Ions;
///diff value
RealType DiffVal;
///\f$Uat[i] = sum_(j) u_{i,j}\f$
Vector<valT> Uat, oldUk, newUk;
///\f$dUat[i] = sum_(j) du_{i,j}\f$
using gContainer_type = VectorSoaContainer<valT, OHMMS_DIM>;
gContainer_type dUat, olddUk, newdUk;
///\f$d2Uat[i] = sum_(j) d2u_{i,j}\f$
Vector<valT> d2Uat, oldd2Uk, newd2Uk;
/// current values during PbyP
valT cur_Uat, cur_d2Uat;
posT cur_dUat, dUat_temp;
///container for the Jastrow functions
Array<FT*, 3> F;
std::map<std::string, FT*> J3Unique;
//YYYY
std::map<FT*, int> J3UniqueIndex;
/// the cutoff for e-I pairs
std::vector<valT> Ion_cutoff;
/// the electrons around ions within the cutoff radius, grouped by species
Array<std::vector<int>, 2> elecs_inside;
Array<std::vector<valT>, 2> elecs_inside_dist;
Array<std::vector<posT>, 2> elecs_inside_displ;
/// the ids of ions within the cutoff radius of an electron on which a move is proposed
std::vector<int> ions_nearby_old, ions_nearby_new;
/// work buffer size
size_t Nbuffer;
/// compressed distances
aligned_vector<valT> Distjk_Compressed, DistkI_Compressed, DistjI_Compressed;
std::vector<int> DistIndice_k;
/// compressed displacements
gContainer_type Disp_jk_Compressed, Disp_jI_Compressed, Disp_kI_Compressed;
/// work result buffer
VectorSoaContainer<valT, 9> mVGL;
// Used for evaluating derivatives with respect to the parameters
int NumVars;
Array<std::pair<int, int>, 3> VarOffset;
Vector<RealType> dLogPsi;
Array<PosType, 2> gradLogPsi;
Array<RealType, 2> lapLogPsi;
// Temporary store for parameter derivatives of functor
// The first index is the functor index in J3Unique. The second is the parameter index w.r.t. to that
// functor
std::vector<std::vector<RealType>> du_dalpha;
std::vector<std::vector<PosType>> dgrad_dalpha;
std::vector<std::vector<Tensor<RealType, 3>>> dhess_dalpha;
public:
///alias FuncType
using FuncType = FT;
JeeIOrbitalSoA(const std::string& obj_name, const ParticleSet& ions, ParticleSet& elecs, bool is_master = false)
: WaveFunctionComponent("JeeIOrbitalSoA", obj_name),
ee_Table_ID_(elecs.addTable(elecs)),
ei_Table_ID_(elecs.addTable(ions, true)),
Ions(ions),
NumVars(0)
{
if (myName.empty())
throw std::runtime_error("JeeIOrbitalSoA object name cannot be empty!");
init(elecs);
}
~JeeIOrbitalSoA() {}
WaveFunctionComponentPtr makeClone(ParticleSet& elecs) const
{
JeeIOrbitalSoA<FT>* eeIcopy = new JeeIOrbitalSoA<FT>(myName, Ions, elecs, false);
std::map<const FT*, FT*> fcmap;
for (int iG = 0; iG < iGroups; iG++)
for (int eG1 = 0; eG1 < eGroups; eG1++)
for (int eG2 = 0; eG2 < eGroups; eG2++)
{
if (F(iG, eG1, eG2) == 0)
continue;
typename std::map<const FT*, FT*>::iterator fit = fcmap.find(F(iG, eG1, eG2));
if (fit == fcmap.end())
{
FT* fc = new FT(*F(iG, eG1, eG2));
eeIcopy->addFunc(iG, eG1, eG2, fc);
fcmap[F(iG, eG1, eG2)] = fc;
}
}
// Ye: I don't like the following memory allocated by default.
eeIcopy->myVars.clear();
eeIcopy->myVars.insertFrom(myVars);
eeIcopy->NumVars = NumVars;
eeIcopy->dLogPsi.resize(NumVars);
eeIcopy->gradLogPsi.resize(NumVars, Nelec);
eeIcopy->lapLogPsi.resize(NumVars, Nelec);
eeIcopy->VarOffset = VarOffset;
eeIcopy->Optimizable = Optimizable;
return eeIcopy;
}
void init(ParticleSet& p)
{
Nelec = p.getTotalNum();
Nelec_padded = getAlignedSize<valT>(Nelec);
Nion = Ions.getTotalNum();
iGroups = Ions.getSpeciesSet().getTotalNum();
eGroups = p.groups();
Uat.resize(Nelec);
dUat.resize(Nelec);
d2Uat.resize(Nelec);
oldUk.resize(Nelec);
olddUk.resize(Nelec);
oldd2Uk.resize(Nelec);
newUk.resize(Nelec);
newdUk.resize(Nelec);
newd2Uk.resize(Nelec);
F.resize(iGroups, eGroups, eGroups);
F = nullptr;
elecs_inside.resize(eGroups, Nion);
elecs_inside_dist.resize(eGroups, Nion);
elecs_inside_displ.resize(eGroups, Nion);
ions_nearby_old.resize(Nion);
ions_nearby_new.resize(Nion);
Ion_cutoff.resize(Nion, 0.0);
//initialize buffers
Nbuffer = Nelec;
mVGL.resize(Nbuffer);
Distjk_Compressed.resize(Nbuffer);
DistjI_Compressed.resize(Nbuffer);
DistkI_Compressed.resize(Nbuffer);
Disp_jk_Compressed.resize(Nbuffer);
Disp_jI_Compressed.resize(Nbuffer);
Disp_kI_Compressed.resize(Nbuffer);
DistIndice_k.resize(Nbuffer);
}
void initUnique()
{
typename std::map<std::string, FT*>::iterator it(J3Unique.begin()), it_end(J3Unique.end());
du_dalpha.resize(J3Unique.size());
dgrad_dalpha.resize(J3Unique.size());
dhess_dalpha.resize(J3Unique.size());
int ifunc = 0;
while (it != it_end)
{
J3UniqueIndex[it->second] = ifunc;
FT& functor = *(it->second);
int numParams = functor.getNumParameters();
du_dalpha[ifunc].resize(numParams);
dgrad_dalpha[ifunc].resize(numParams);
dhess_dalpha[ifunc].resize(numParams);
++it;
ifunc++;
}
}
void addFunc(int iSpecies, int eSpecies1, int eSpecies2, FT* j)
{
if (eSpecies1 == eSpecies2)
{
//if only up-up is specified, assume spin-unpolarized correlations
if (eSpecies1 == 0)
for (int eG1 = 0; eG1 < eGroups; eG1++)
for (int eG2 = 0; eG2 < eGroups; eG2++)
{
if (F(iSpecies, eG1, eG2) == 0)
F(iSpecies, eG1, eG2) = j;
}
}
else
{
F(iSpecies, eSpecies1, eSpecies2) = j;
F(iSpecies, eSpecies2, eSpecies1) = j;
}
if (j)
{
RealType rcut = 0.5 * j->cutoff_radius;
for (int i = 0; i < Nion; i++)
if (Ions.GroupID[i] == iSpecies)
Ion_cutoff[i] = rcut;
}
else
{
APP_ABORT("JeeIOrbitalSoA::addFunc Jastrow function pointer is NULL");
}
std::stringstream aname;
aname << iSpecies << "_" << eSpecies1 << "_" << eSpecies2;
J3Unique[aname.str()] = j;
initUnique();
}
/** check that correlation information is complete
*/
void check_complete()
{
//check that correlation pointers are either all 0 or all assigned
bool complete = true;
for (int i = 0; i < iGroups; ++i)
{
int nfilled = 0;
bool partial;
for (int e1 = 0; e1 < eGroups; ++e1)
for (int e2 = 0; e2 < eGroups; ++e2)
if (F(i, e1, e2) != 0)
nfilled++;
partial = nfilled > 0 && nfilled < eGroups * eGroups;
if (partial)
app_log() << "J3 eeI is missing correlation for ion " << i << std::endl;
complete = complete && !partial;
}
if (!complete)
{
APP_ABORT("JeeIOrbitalSoA::check_complete J3 eeI is missing correlation components\n see preceding messages "
"for details");
}
//first set radii
for (int i = 0; i < Nion; ++i)
{
FT* f = F(Ions.GroupID[i], 0, 0);
if (f != 0)
Ion_cutoff[i] = .5 * f->cutoff_radius;
}
//then check radii
bool all_radii_match = true;
for (int i = 0; i < iGroups; ++i)
{
if (F(i, 0, 0) != 0)
{
bool radii_match = true;
RealType rcut = F(i, 0, 0)->cutoff_radius;
for (int e1 = 0; e1 < eGroups; ++e1)
for (int e2 = 0; e2 < eGroups; ++e2)
radii_match = radii_match && F(i, e1, e2)->cutoff_radius == rcut;
if (!radii_match)
app_log() << "eeI functors for ion species " << i << " have different radii" << std::endl;
all_radii_match = all_radii_match && radii_match;
}
}
if (!all_radii_match)
{
APP_ABORT("JeeIOrbitalSoA::check_radii J3 eeI are inconsistent for some ion species\n see preceding messages "
"for details");
}
}
/** check in an optimizable parameter
* @param o a super set of optimizable variables
*/
void checkInVariables(opt_variables_type& active)
{
myVars.clear();
typename std::map<std::string, FT*>::iterator it(J3Unique.begin()), it_end(J3Unique.end());
while (it != it_end)
{
(*it).second->checkInVariables(active);
(*it).second->checkInVariables(myVars);
++it;
}
}
/** check out optimizable variables
*/
void checkOutVariables(const opt_variables_type& active)
{
myVars.clear();
typename std::map<std::string, FT*>::iterator it(J3Unique.begin()), it_end(J3Unique.end());
while (it != it_end)
{
(*it).second->myVars.getIndex(active);
myVars.insertFrom((*it).second->myVars);
++it;
}
myVars.getIndex(active);
NumVars = myVars.size();
if (NumVars)
{
dLogPsi.resize(NumVars);
gradLogPsi.resize(NumVars, Nelec);
lapLogPsi.resize(NumVars, Nelec);
VarOffset.resize(iGroups, eGroups, eGroups);
int varoffset = myVars.Index[0];
for (int ig = 0; ig < iGroups; ig++)
for (int jg = 0; jg < eGroups; jg++)
for (int kg = 0; kg < eGroups; kg++)
{
FT* func_ijk = F(ig, jg, kg);
if (func_ijk == nullptr)
continue;
VarOffset(ig, jg, kg).first = func_ijk->myVars.Index.front() - varoffset;
VarOffset(ig, jg, kg).second = func_ijk->myVars.Index.size() + VarOffset(ig, jg, kg).first;
}
}
}
///reset the value of all the unique Two-Body Jastrow functions
void resetParameters(const opt_variables_type& active)
{
if (!Optimizable)
return;
typename std::map<std::string, FT*>::iterator it(J3Unique.begin()), it_end(J3Unique.end());
while (it != it_end)
{
(*it++).second->resetParameters(active);
}
for (int i = 0; i < myVars.size(); ++i)
{
int ii = myVars.Index[i];
if (ii >= 0)
myVars[i] = active[ii];
}
}
/** print the state, e.g., optimizables */
void reportStatus(std::ostream& os)
{
typename std::map<std::string, FT*>::iterator it(J3Unique.begin()), it_end(J3Unique.end());
while (it != it_end)
{
(*it).second->myVars.print(os);
++it;
}
}
void build_compact_list(const ParticleSet& P)
{
const auto& eI_dists = P.getDistTable(ei_Table_ID_).getDistances();
const auto& eI_displs = P.getDistTable(ei_Table_ID_).getDisplacements();
for (int iat = 0; iat < Nion; ++iat)
for (int jg = 0; jg < eGroups; ++jg)
{
elecs_inside(jg, iat).clear();
elecs_inside_dist(jg, iat).clear();
elecs_inside_displ(jg, iat).clear();
}
for (int jg = 0; jg < eGroups; ++jg)
for (int jel = P.first(jg); jel < P.last(jg); jel++)
for (int iat = 0; iat < Nion; ++iat)
if (eI_dists[jel][iat] < Ion_cutoff[iat])
{
elecs_inside(jg, iat).push_back(jel);
elecs_inside_dist(jg, iat).push_back(eI_dists[jel][iat]);
elecs_inside_displ(jg, iat).push_back(eI_displs[jel][iat]);
}
}
LogValueType evaluateLog(const ParticleSet& P, ParticleSet::ParticleGradient_t& G, ParticleSet::ParticleLaplacian_t& L)
{
return evaluateGL(P, G, L, true);
}
PsiValueType ratio(ParticleSet& P, int iat)
{
UpdateMode = ORB_PBYP_RATIO;
const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_);
const DistanceTableData& ee_table = P.getDistTable(ee_Table_ID_);
cur_Uat = computeU(P, iat, P.GroupID[iat], eI_table.getTempDists(), ee_table.getTempDists(), ions_nearby_new);
DiffVal = Uat[iat] - cur_Uat;
return std::exp(static_cast<PsiValueType>(DiffVal));
}
void evaluateRatios(const VirtualParticleSet& VP, std::vector<ValueType>& ratios)
{
for (int k = 0; k < ratios.size(); ++k)
ratios[k] = std::exp(Uat[VP.refPtcl] -
computeU(VP.refPS, VP.refPtcl, VP.refPS.GroupID[VP.refPtcl],
VP.getDistTable(ei_Table_ID_).getDistRow(k),
VP.getDistTable(ee_Table_ID_).getDistRow(k), ions_nearby_old));
}
void evaluateRatiosAlltoOne(ParticleSet& P, std::vector<ValueType>& ratios)
{
const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_);
const auto& eI_dists = eI_table.getDistances();
const DistanceTableData& ee_table = P.getDistTable(ee_Table_ID_);
for (int jg = 0; jg < eGroups; ++jg)
{
const valT sumU = computeU(P, -1, jg, eI_table.getTempDists(), ee_table.getTempDists(), ions_nearby_new);
for (int j = P.first(jg); j < P.last(jg); ++j)
{
// remove self-interaction
valT Uself(0);
for (int iat = 0; iat < Nion; ++iat)
{
const valT& r_Ij = eI_table.getTempDists()[iat];
const valT& r_Ik = eI_dists[j][iat];
if (r_Ij < Ion_cutoff[iat] && r_Ik < Ion_cutoff[iat])
{
const int ig = Ions.GroupID[iat];
Uself += F(ig, jg, jg)->evaluate(ee_table.getTempDists()[j], r_Ij, r_Ik);
}
}
ratios[j] = std::exp(Uat[j] + Uself - sumU);
}
}
}
GradType evalGrad(ParticleSet& P, int iat) { return GradType(dUat[iat]); }
PsiValueType ratioGrad(ParticleSet& P, int iat, GradType& grad_iat)
{
UpdateMode = ORB_PBYP_PARTIAL;
const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_);
const DistanceTableData& ee_table = P.getDistTable(ee_Table_ID_);
computeU3(P, iat, eI_table.getTempDists(), eI_table.getTempDispls(), ee_table.getTempDists(),
ee_table.getTempDispls(), cur_Uat, cur_dUat, cur_d2Uat, newUk, newdUk, newd2Uk, ions_nearby_new);
DiffVal = Uat[iat] - cur_Uat;
grad_iat += cur_dUat;
return std::exp(static_cast<PsiValueType>(DiffVal));
}
inline void restore(int iat) {}
void acceptMove(ParticleSet& P, int iat, bool safe_to_delay = false)
{
const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_);
const DistanceTableData& ee_table = P.getDistTable(ee_Table_ID_);
// get the old value, grad, lapl
computeU3(P, iat, eI_table.getDistRow(iat), eI_table.getDisplRow(iat), ee_table.getOldDists(),
ee_table.getOldDispls(), Uat[iat], dUat_temp, d2Uat[iat], oldUk, olddUk, oldd2Uk, ions_nearby_old);
if (UpdateMode == ORB_PBYP_RATIO)
{ //ratio-only during the move; need to compute derivatives
computeU3(P, iat, eI_table.getTempDists(), eI_table.getTempDispls(), ee_table.getTempDists(),
ee_table.getTempDispls(), cur_Uat, cur_dUat, cur_d2Uat, newUk, newdUk, newd2Uk, ions_nearby_new);
}
#pragma omp simd
for (int jel = 0; jel < Nelec; jel++)
{
Uat[jel] += newUk[jel] - oldUk[jel];
d2Uat[jel] += newd2Uk[jel] - oldd2Uk[jel];
}
for (int idim = 0; idim < OHMMS_DIM; ++idim)
{
valT* restrict save_g = dUat.data(idim);
const valT* restrict new_g = newdUk.data(idim);
const valT* restrict old_g = olddUk.data(idim);
#pragma omp simd aligned(save_g, new_g, old_g: QMC_SIMD_ALIGNMENT)
for (int jel = 0; jel < Nelec; jel++)
save_g[jel] += new_g[jel] - old_g[jel];
}
LogValue += Uat[iat] - cur_Uat;
Uat[iat] = cur_Uat;
dUat(iat) = cur_dUat;
d2Uat[iat] = cur_d2Uat;
const int ig = P.GroupID[iat];
// update compact list elecs_inside
// if the old position exists in elecs_inside
for (int iind = 0; iind < ions_nearby_old.size(); iind++)
{
int jat = ions_nearby_old[iind];
auto iter = std::find(elecs_inside(ig, jat).begin(), elecs_inside(ig, jat).end(), iat);
auto iter_dist = elecs_inside_dist(ig, jat).begin() + std::distance(elecs_inside(ig, jat).begin(), iter);
auto iter_displ = elecs_inside_displ(ig, jat).begin() + std::distance(elecs_inside(ig, jat).begin(), iter);
// sentinel code
#ifndef NDEBUG
if (iter == elecs_inside(ig, jat).end())
{
std::cerr << std::setprecision(std::numeric_limits<valT>::digits10 + 1) << "updating electron iat = " << iat
<< " near ion " << jat << " dist " << eI_table.getDistRow(iat)[jat] << std::endl;
throw std::runtime_error("BUG electron not found in elecs_inside");
}
else if (std::abs(eI_table.getDistRow(iat)[jat] - *iter_dist) >= std::numeric_limits<valT>::epsilon())
{
std::cerr << std::setprecision(std::numeric_limits<valT>::digits10 + 1) << "inconsistent electron iat = " << iat
<< " near ion " << jat << " dist " << eI_table.getDistRow(iat)[jat]
<< " stored value = " << *iter_dist << std::endl;
throw std::runtime_error("BUG eI distance stored value elecs_inside_dist not matching distance table");
}
#endif
if (eI_table.getTempDists()[jat] < Ion_cutoff[jat]) // the new position is still inside
{
*iter_dist = eI_table.getTempDists()[jat];
*iter_displ = eI_table.getTempDispls()[jat];
*std::find(ions_nearby_new.begin(), ions_nearby_new.end(), jat) = -1;
}
else
{
*iter = elecs_inside(ig, jat).back();
elecs_inside(ig, jat).pop_back();
*iter_dist = elecs_inside_dist(ig, jat).back();
elecs_inside_dist(ig, jat).pop_back();
*iter_displ = elecs_inside_displ(ig, jat).back();
elecs_inside_displ(ig, jat).pop_back();
}
}
// if the old position doesn't exist in elecs_inside but the new position do
for (int iind = 0; iind < ions_nearby_new.size(); iind++)
{
int jat = ions_nearby_new[iind];
if (jat >= 0)
{
elecs_inside(ig, jat).push_back(iat);
elecs_inside_dist(ig, jat).push_back(eI_table.getTempDists()[jat]);
elecs_inside_displ(ig, jat).push_back(eI_table.getTempDispls()[jat]);
}
}
}
inline void recompute(const ParticleSet& P)
{
const DistanceTableData& eI_table = P.getDistTable(ei_Table_ID_);
const DistanceTableData& ee_table = P.getDistTable(ee_Table_ID_);
build_compact_list(P);
for (int jel = 0; jel < Nelec; ++jel)
{
computeU3(P, jel, eI_table.getDistRow(jel), eI_table.getDisplRow(jel), ee_table.getDistRow(jel),
ee_table.getDisplRow(jel), Uat[jel], dUat_temp, d2Uat[jel], newUk, newdUk, newd2Uk, ions_nearby_new,
true);
dUat(jel) = dUat_temp;
// add the contribution from the upper triangle
#pragma omp simd
for (int kel = 0; kel < jel; kel++)
{
Uat[kel] += newUk[kel];
d2Uat[kel] += newd2Uk[kel];
}
for (int idim = 0; idim < OHMMS_DIM; ++idim)
{
valT* restrict save_g = dUat.data(idim);
const valT* restrict new_g = newdUk.data(idim);
#pragma omp simd aligned(save_g, new_g: QMC_SIMD_ALIGNMENT)
for (int kel = 0; kel < jel; kel++)
save_g[kel] += new_g[kel];
}
}
}
inline valT computeU(const ParticleSet& P,
int jel,
int jg,
const DistRow& distjI,
const DistRow& distjk,
std::vector<int>& ions_nearby)
{
ions_nearby.clear();
for (int iat = 0; iat < Nion; ++iat)
if (distjI[iat] < Ion_cutoff[iat])
ions_nearby.push_back(iat);
valT Uj = valT(0);
for (int kg = 0; kg < eGroups; ++kg)
{
int kel_counter = 0;
for (int iind = 0; iind < ions_nearby.size(); ++iind)
{
const int iat = ions_nearby[iind];
const int ig = Ions.GroupID[iat];
const valT r_jI = distjI[iat];
for (int kind = 0; kind < elecs_inside(kg, iat).size(); kind++)
{
const int kel = elecs_inside(kg, iat)[kind];
if (kel != jel)
{
DistkI_Compressed[kel_counter] = elecs_inside_dist(kg, iat)[kind];
Distjk_Compressed[kel_counter] = distjk[kel];
DistjI_Compressed[kel_counter] = r_jI;
kel_counter++;
if (kel_counter == Nbuffer)
{
const FT& feeI(*F(ig, jg, kg));
Uj += feeI.evaluateV(kel_counter, Distjk_Compressed.data(), DistjI_Compressed.data(),
DistkI_Compressed.data());
kel_counter = 0;
}
}
}
if ((iind + 1 == ions_nearby.size() || ig != Ions.GroupID[ions_nearby[iind + 1]]) && kel_counter > 0)
{
const FT& feeI(*F(ig, jg, kg));
Uj +=
feeI.evaluateV(kel_counter, Distjk_Compressed.data(), DistjI_Compressed.data(), DistkI_Compressed.data());
kel_counter = 0;
}
}
}
return Uj;
}
inline void computeU3_engine(const ParticleSet& P,
const FT& feeI,
int kel_counter,
valT& Uj,
posT& dUj,
valT& d2Uj,
Vector<valT>& Uk,
gContainer_type& dUk,
Vector<valT>& d2Uk)
{
constexpr valT czero(0);
constexpr valT cone(1);
constexpr valT ctwo(2);
constexpr valT lapfac = OHMMS_DIM - cone;
valT* restrict val = mVGL.data(0);
valT* restrict gradF0 = mVGL.data(1);
valT* restrict gradF1 = mVGL.data(2);
valT* restrict gradF2 = mVGL.data(3);
valT* restrict hessF00 = mVGL.data(4);
valT* restrict hessF11 = mVGL.data(5);
valT* restrict hessF22 = mVGL.data(6);
valT* restrict hessF01 = mVGL.data(7);
valT* restrict hessF02 = mVGL.data(8);
feeI.evaluateVGL(kel_counter, Distjk_Compressed.data(), DistjI_Compressed.data(), DistkI_Compressed.data(), val,
gradF0, gradF1, gradF2, hessF00, hessF11, hessF22, hessF01, hessF02);
// compute the contribution to jel, kel
Uj = simd::accumulate_n(val, kel_counter, Uj);
valT gradF0_sum = simd::accumulate_n(gradF0, kel_counter, czero);
valT gradF1_sum = simd::accumulate_n(gradF1, kel_counter, czero);
valT hessF00_sum = simd::accumulate_n(hessF00, kel_counter, czero);
valT hessF11_sum = simd::accumulate_n(hessF11, kel_counter, czero);
d2Uj -= hessF00_sum + hessF11_sum + lapfac * (gradF0_sum + gradF1_sum);
std::fill_n(hessF11, kel_counter, czero);
for (int idim = 0; idim < OHMMS_DIM; ++idim)
{
valT* restrict jk = Disp_jk_Compressed.data(idim);
valT* restrict jI = Disp_jI_Compressed.data(idim);
valT* restrict kI = Disp_kI_Compressed.data(idim);
valT dUj_x(0);
#pragma omp simd aligned(gradF0, gradF1, gradF2, hessF11, jk, jI, kI: QMC_SIMD_ALIGNMENT) reduction(+ : dUj_x)
for (int kel_index = 0; kel_index < kel_counter; kel_index++)
{
// recycle hessF11
hessF11[kel_index] += kI[kel_index] * jk[kel_index];
dUj_x += gradF1[kel_index] * jI[kel_index];
// destroy jk, kI
const valT temp = jk[kel_index] * gradF0[kel_index];
dUj_x += temp;
jk[kel_index] *= jI[kel_index];
kI[kel_index] = kI[kel_index] * gradF2[kel_index] - temp;
}
dUj[idim] += dUj_x;
valT* restrict jk0 = Disp_jk_Compressed.data(0);
if (idim > 0)
{
#pragma omp simd aligned(jk, jk0: QMC_SIMD_ALIGNMENT)
for (int kel_index = 0; kel_index < kel_counter; kel_index++)
jk0[kel_index] += jk[kel_index];
}
valT* restrict dUk_x = dUk.data(idim);
for (int kel_index = 0; kel_index < kel_counter; kel_index++)
dUk_x[DistIndice_k[kel_index]] += kI[kel_index];
}
valT sum(0);
valT* restrict jk0 = Disp_jk_Compressed.data(0);
#pragma omp simd aligned(jk0, hessF01: QMC_SIMD_ALIGNMENT) reduction(+ : sum)
for (int kel_index = 0; kel_index < kel_counter; kel_index++)
sum += hessF01[kel_index] * jk0[kel_index];
d2Uj -= ctwo * sum;
#pragma omp simd aligned(hessF00, hessF22, gradF0, gradF2, hessF02, hessF11: QMC_SIMD_ALIGNMENT)
for (int kel_index = 0; kel_index < kel_counter; kel_index++)
hessF00[kel_index] = hessF00[kel_index] + hessF22[kel_index] + lapfac * (gradF0[kel_index] + gradF2[kel_index]) -
ctwo * hessF02[kel_index] * hessF11[kel_index];
for (int kel_index = 0; kel_index < kel_counter; kel_index++)
{
const int kel = DistIndice_k[kel_index];
Uk[kel] += val[kel_index];
d2Uk[kel] -= hessF00[kel_index];
}
}
inline void computeU3(const ParticleSet& P,
int jel,
const DistRow& distjI,
const DisplRow& displjI,
const DistRow& distjk,
const DisplRow& displjk,
valT& Uj,
posT& dUj,
valT& d2Uj,
Vector<valT>& Uk,
gContainer_type& dUk,
Vector<valT>& d2Uk,
std::vector<int>& ions_nearby,
bool triangle = false)
{
constexpr valT czero(0);
Uj = czero;
dUj = posT();
d2Uj = czero;
const int jg = P.GroupID[jel];
const int kelmax = triangle ? jel : Nelec;
std::fill_n(Uk.data(), kelmax, czero);
std::fill_n(d2Uk.data(), kelmax, czero);
for (int idim = 0; idim < OHMMS_DIM; ++idim)
std::fill_n(dUk.data(idim), kelmax, czero);
ions_nearby.clear();
for (int iat = 0; iat < Nion; ++iat)
if (distjI[iat] < Ion_cutoff[iat])
ions_nearby.push_back(iat);
for (int kg = 0; kg < eGroups; ++kg)
{
int kel_counter = 0;
for (int iind = 0; iind < ions_nearby.size(); ++iind)
{
const int iat = ions_nearby[iind];
const int ig = Ions.GroupID[iat];
const valT r_jI = distjI[iat];
const posT disp_Ij = displjI[iat];
for (int kind = 0; kind < elecs_inside(kg, iat).size(); kind++)
{
const int kel = elecs_inside(kg, iat)[kind];
if (kel < kelmax && kel != jel)
{
DistkI_Compressed[kel_counter] = elecs_inside_dist(kg, iat)[kind];
DistjI_Compressed[kel_counter] = r_jI;
Distjk_Compressed[kel_counter] = distjk[kel];
Disp_kI_Compressed(kel_counter) = elecs_inside_displ(kg, iat)[kind];
Disp_jI_Compressed(kel_counter) = disp_Ij;
Disp_jk_Compressed(kel_counter) = displjk[kel];
DistIndice_k[kel_counter] = kel;
kel_counter++;
if (kel_counter == Nbuffer)
{
const FT& feeI(*F(ig, jg, kg));
computeU3_engine(P, feeI, kel_counter, Uj, dUj, d2Uj, Uk, dUk, d2Uk);
kel_counter = 0;
}
}
}
if ((iind + 1 == ions_nearby.size() || ig != Ions.GroupID[ions_nearby[iind + 1]]) && kel_counter > 0)
{
const FT& feeI(*F(ig, jg, kg));
computeU3_engine(P, feeI, kel_counter, Uj, dUj, d2Uj, Uk, dUk, d2Uk);
kel_counter = 0;
}
}
}
}
inline void registerData(ParticleSet& P, WFBufferType& buf)
{
if (Bytes_in_WFBuffer == 0)
{
Bytes_in_WFBuffer = buf.current();
buf.add(Uat.begin(), Uat.end());
buf.add(dUat.data(), dUat.end());
buf.add(d2Uat.begin(), d2Uat.end());
Bytes_in_WFBuffer = buf.current() - Bytes_in_WFBuffer;
// free local space
Uat.free();
dUat.free();
d2Uat.free();
}
else
{
buf.forward(Bytes_in_WFBuffer);
}
}
inline LogValueType updateBuffer(ParticleSet& P, WFBufferType& buf, bool fromscratch = false)
{
evaluateGL(P, P.G, P.L, false);
buf.forward(Bytes_in_WFBuffer);
return LogValue;
}
inline void copyFromBuffer(ParticleSet& P, WFBufferType& buf)
{
Uat.attachReference(buf.lendReference<valT>(Nelec), Nelec);
dUat.attachReference(Nelec, Nelec_padded, buf.lendReference<valT>(Nelec_padded * OHMMS_DIM));
d2Uat.attachReference(buf.lendReference<valT>(Nelec), Nelec);
build_compact_list(P);
}
LogValueType evaluateGL(const ParticleSet& P,
ParticleSet::ParticleGradient_t& G,
ParticleSet::ParticleLaplacian_t& L,
bool fromscratch = false)
{
if (fromscratch)
recompute(P);
LogValue = valT(0);
for (int iat = 0; iat < Nelec; ++iat)
{
LogValue += Uat[iat];
G[iat] += dUat[iat];
L[iat] += d2Uat[iat];
}
return LogValue = -LogValue * 0.5;
}
void evaluateDerivatives(ParticleSet& P,
const opt_variables_type& optvars,
std::vector<ValueType>& dlogpsi,
std::vector<ValueType>& dhpsioverpsi)
{
bool recalculate(false);
std::vector<bool> rcsingles(myVars.size(), false);
for (int k = 0; k < myVars.size(); ++k)
{
int kk = myVars.where(k);
if (kk < 0)
continue;
if (optvars.recompute(kk))
recalculate = true;
rcsingles[k] = true;
}
if (recalculate)
{
constexpr valT czero(0);
constexpr valT cone(1);
constexpr valT cminus(-1);
constexpr valT ctwo(2);
constexpr valT lapfac = OHMMS_DIM - cone;
const DistanceTableData& ee_table = P.getDistTable(ee_Table_ID_);
const auto& ee_dists = ee_table.getDistances();
const auto& ee_displs = ee_table.getDisplacements();
build_compact_list(P);
dLogPsi = czero;
gradLogPsi = PosType();
lapLogPsi = czero;
for (int iat = 0; iat < Nion; ++iat)
{
const int ig = Ions.GroupID[iat];
for (int jg = 0; jg < eGroups; ++jg)
for (int jind = 0; jind < elecs_inside(jg, iat).size(); jind++)
{
const int jel = elecs_inside(jg, iat)[jind];
const valT r_Ij = elecs_inside_dist(jg, iat)[jind];
const posT disp_Ij = cminus * elecs_inside_displ(jg, iat)[jind];
const valT r_Ij_inv = cone / r_Ij;
for (int kg = 0; kg < eGroups; ++kg)
for (int kind = 0; kind < elecs_inside(kg, iat).size(); kind++)
{
const int kel = elecs_inside(kg, iat)[kind];
if (kel < jel)
{
const valT r_Ik = elecs_inside_dist(kg, iat)[kind];
const posT disp_Ik = cminus * elecs_inside_displ(kg, iat)[kind];
const valT r_Ik_inv = cone / r_Ik;
const valT r_jk = ee_dists[jel][kel];
const posT disp_jk = ee_displs[jel][kel];
const valT r_jk_inv = cone / r_jk;
FT& func = *F(ig, jg, kg);
int idx = J3UniqueIndex[F(ig, jg, kg)];
func.evaluateDerivatives(r_jk, r_Ij, r_Ik, du_dalpha[idx], dgrad_dalpha[idx], dhess_dalpha[idx]);
int first = VarOffset(ig, jg, kg).first;
int last = VarOffset(ig, jg, kg).second;
std::vector<RealType>& dlog = du_dalpha[idx];
std::vector<PosType>& dgrad = dgrad_dalpha[idx];
std::vector<Tensor<RealType, 3>>& dhess = dhess_dalpha[idx];
for (int p = first, ip = 0; p < last; p++, ip++)
{
RealType& dval = dlog[ip];
PosType& dg = dgrad[ip];
Tensor<RealType, 3>& dh = dhess[ip];
dg[0] *= r_jk_inv;
dg[1] *= r_Ij_inv;
dg[2] *= r_Ik_inv;
PosType gr_ee = dg[0] * disp_jk;
gradLogPsi(p, jel) -= dg[1] * disp_Ij - gr_ee;
lapLogPsi(p, jel) -=
(dh(0, 0) + lapfac * dg[0] - ctwo * dh(0, 1) * dot(disp_jk, disp_Ij) * r_jk_inv * r_Ij_inv +
dh(1, 1) + lapfac * dg[1]);
gradLogPsi(p, kel) -= dg[2] * disp_Ik + gr_ee;
lapLogPsi(p, kel) -=
(dh(0, 0) + lapfac * dg[0] + ctwo * dh(0, 2) * dot(disp_jk, disp_Ik) * r_jk_inv * r_Ik_inv +
dh(2, 2) + lapfac * dg[2]);
dLogPsi[p] -= dval;
}
}
}
}
}
for (int k = 0; k < myVars.size(); ++k)
{
int kk = myVars.where(k);
if (kk < 0)
continue;
dlogpsi[kk] = (ValueType)dLogPsi[k];
RealType sum = 0.0;
for (int i = 0; i < Nelec; i++)
{
#if defined(QMC_COMPLEX)
sum -= 0.5 * lapLogPsi(k, i);
for (int jdim = 0; jdim < OHMMS_DIM; ++jdim)
sum -= P.G[i][jdim].real() * gradLogPsi(k, i)[jdim];
#else
sum -= 0.5 * lapLogPsi(k, i) + dot(P.G[i], gradLogPsi(k, i));
#endif
}
dhpsioverpsi[kk] = (ValueType)sum;
}
}
}
inline GradType evalGradSource(ParticleSet& P, ParticleSet& source, int isrc)
{
ParticleSet::ParticleGradient_t tempG;
ParticleSet::ParticleLaplacian_t tempL;
tempG.resize(P.getTotalNum());
tempL.resize(P.getTotalNum());
QTFull::RealType delta = 0.00001;
QTFull::RealType c1 = 1.0 / delta / 2.0;
QTFull::RealType c2 = 1.0 / delta / delta;
GradType g_return(0.0);
// GRAD TEST COMPUTATION
PosType rI = source.R[isrc];
for (int iondim = 0; iondim < 3; iondim++)
{
source.R[isrc][iondim] = rI[iondim] + delta;
source.update();
P.update();
LogValueType log_p = evaluateLog(P, tempG, tempL);
source.R[isrc][iondim] = rI[iondim] - delta;
source.update();
P.update();
LogValueType log_m = evaluateLog(P, tempG, tempL);
QTFull::RealType log_p_r(0.0), log_m_r(0.0);
log_p_r = log_p.real();
log_m_r = log_m.real();
//symmetric finite difference formula for gradient.
g_return[iondim] = c1 * (log_p_r - log_m_r);
//reset everything to how it was.
source.R[isrc][iondim] = rI[iondim];
}
// this last one makes sure the distance tables and internal neighbourlist correspond to unperturbed source.
source.update();
P.update();
build_compact_list(P);
return g_return;
}
inline GradType evalGradSource(ParticleSet& P,
ParticleSet& source,
int isrc,
TinyVector<ParticleSet::ParticleGradient_t, OHMMS_DIM>& grad_grad,
TinyVector<ParticleSet::ParticleLaplacian_t, OHMMS_DIM>& lapl_grad)
{
ParticleSet::ParticleGradient_t Gp, Gm, dG;
ParticleSet::ParticleLaplacian_t Lp, Lm, dL;
Gp.resize(P.getTotalNum());
Gm.resize(P.getTotalNum());
dG.resize(P.getTotalNum());
Lp.resize(P.getTotalNum());
Lm.resize(P.getTotalNum());
dL.resize(P.getTotalNum());
QTFull::RealType delta = 0.00001;
QTFull::RealType c1 = 1.0 / delta / 2.0;
QTFull::RealType c2 = 1.0 / delta / delta;
GradType g_return(0.0);
// GRAD TEST COMPUTATION
PosType rI = source.R[isrc];
for (int iondim = 0; iondim < 3; iondim++)
{
Lp = 0;
Gp = 0;
Lm = 0;
Gm = 0;
source.R[isrc][iondim] = rI[iondim] + delta;
source.update();
P.update();
LogValueType log_p = evaluateLog(P, Gp, Lp);
source.R[isrc][iondim] = rI[iondim] - delta;
source.update();
P.update();
LogValueType log_m = evaluateLog(P, Gm, Lm);
QTFull::RealType log_p_r(0.0), log_m_r(0.0);
log_p_r = log_p.real();
log_m_r = log_m.real();
dG = Gp - Gm;
dL = Lp - Lm;
//symmetric finite difference formula for gradient.
g_return[iondim] = c1 * (log_p_r - log_m_r);
grad_grad[iondim] += c1 * dG;
lapl_grad[iondim] += c1 * dL;
//reset everything to how it was.
source.R[isrc][iondim] = rI[iondim];
}
// this last one makes sure the distance tables and internal neighbourlist correspond to unperturbed source.
source.update();
P.update();
build_compact_list(P);
return g_return;
}
};
} // namespace qmcplusplus
#endif
|
matrix_op-inl.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2015 by Contributors
* \file matrix_op-inl.h
* \brief Function definition of matrix related operators
*/
#ifndef MXNET_OPERATOR_TENSOR_MATRIX_OP_INL_H_
#define MXNET_OPERATOR_TENSOR_MATRIX_OP_INL_H_
#include <mxnet/operator_util.h>
#include <vector>
#include <string>
#include <algorithm>
#include <utility>
#include <type_traits>
#include "../mshadow_op.h"
#include "../elemwise_op_common.h"
#include "../channel_op_common.h"
#include "../mxnet_op.h"
#include "broadcast_reduce_op.h"
#include "./init_op.h"
#include "../../common/static_array.h"
#include "./slice-inl.h"
#if MXNET_USE_CUDA
#include <thrust/device_vector.h>
#endif
#ifdef __CUDACC__
#include "./pseudo2DTranspose_op-inl.cuh"
#endif
namespace mxnet {
namespace op {
struct ReshapeParam : public dmlc::Parameter<ReshapeParam> {
mxnet::TShape target_shape;
bool keep_highest;
mxnet::Tuple<int> shape;
bool reverse;
DMLC_DECLARE_PARAMETER(ReshapeParam) {
DMLC_DECLARE_FIELD(shape)
.set_default(mxnet::Tuple<int>())
.describe("The target shape");
DMLC_DECLARE_FIELD(reverse)
.set_default(false)
.describe("If true then the special values are inferred from right to left");
DMLC_DECLARE_FIELD(target_shape)
.set_default(mxnet::TShape(0, -1))
.describe("(Deprecated! Use ``shape`` instead.) "
"Target new shape. One and only one dim can be 0, "
"in which case it will be inferred from the rest of dims");
DMLC_DECLARE_FIELD(keep_highest).set_default(false)
.describe("(Deprecated! Use ``shape`` instead.) Whether keep the highest dim unchanged."
"If set to true, then the first dim in target_shape is ignored,"
"and always fixed as input");
}
bool operator==(const ReshapeParam &other) const {
return this->target_shape == other.target_shape &&
this->keep_highest == other.keep_highest &&
this->shape == other.shape &&
this->reverse == other.reverse;
}
};
template<typename IType>
inline mxnet::TShape InferReshapeShape(const mxnet::Tuple<IType>& shape,
const mxnet::TShape& dshape, bool reverse) {
std::vector<IType> dshape_vec;
std::vector<IType> param_shape_vec(shape.begin(), shape.end());
for (int i = 0; i < dshape.ndim(); ++i) {
dshape_vec.push_back(dshape[i]);
}
std::vector<IType> tmp;
size_t src_idx = 0;
int inf_idx = -1;
if (reverse) {
std::reverse(dshape_vec.begin(), dshape_vec.end());
std::reverse(param_shape_vec.begin(), param_shape_vec.end());
}
auto dshape_len = dshape_vec.size();
auto params_len = param_shape_vec.size();
for (size_t i = 0; i < params_len; ++i) {
IType proposed_dim = param_shape_vec[i];
if (proposed_dim == 0) {
// keep same
CHECK_LT(src_idx, dshape_len);
tmp.push_back(dshape_vec[src_idx++]);
} else if (proposed_dim == -1) {
// infer
CHECK_LT(inf_idx, 0) << "One and only one dim can be inferred";
inf_idx = i;
tmp.push_back(1);
src_idx++;
} else if (proposed_dim == -2) {
// copy all remaining dims from source
while (src_idx < dshape_len) {
const int dn = dshape_vec[src_idx++];
tmp.push_back(dn);
}
} else if (proposed_dim == -3) {
// merge two dims from source
CHECK_LT(src_idx, dshape_len-1);
const int d1 = dshape_vec[src_idx++];
const int d2 = dshape_vec[src_idx++];
if (!mxnet::dim_size_is_known(d1) || !mxnet::dim_size_is_known(d2)) {
tmp.push_back(-1);
} else {
tmp.push_back(d1 * d2);
}
} else if (proposed_dim == -4) {
// split the source dim s into two dims
// read the left dim and then the right dim (either can be -1)
CHECK_LT(i + 2, params_len);
CHECK_LT(src_idx, dshape_len);
const int d0 = dshape_vec[src_idx++];
IType d1 = param_shape_vec[++i];
IType d2 = param_shape_vec[++i];
CHECK(d1 != -1 || d2 != -1) << "Split dims cannot both be -1.";
if (d1 == -1 && d0 >= 0) d1 = d0 / d2; // d0 must be known to do this
if (d2 == -1 && d0 >= 0) d2 = d0 / d1; // d0 must be known to do this
CHECK(d1 * d2 == static_cast<IType>(d0) || static_cast<IType>(d0) == IType(-1)) <<
"Split dims " << d1 << ", " << d2 << " do not divide original dim " << d0;
tmp.push_back(d1);
tmp.push_back(d2);
} else {
// greater than 0, new shape
tmp.push_back(proposed_dim);
src_idx++;
}
}
if (inf_idx >= 0) {
if (shape_is_known(dshape)) {
IType new_size = 1;
for (IType x : tmp) new_size *= x;
tmp[inf_idx] = dshape.Size() / new_size;
} else {
tmp[inf_idx] = -1;
}
}
if (reverse) {
std::reverse(param_shape_vec.begin(), param_shape_vec.end());
std::reverse(dshape_vec.begin(), dshape_vec.end());
std::reverse(tmp.begin(), tmp.end());
}
mxnet::TShape oshape(tmp.begin(), tmp.end());
return oshape;
}
inline bool ReverseReshapeInferShape(mxnet::TShape *in, const mxnet::TShape& out) {
if (shape_is_known(*in) && shape_is_known(out)) {
return true;
} else if (!shape_is_known(out)) {
return false;
} else {
int zero_axis = -1;
int known_dim_size_prod = 1;
for (int i = 0; i < in->ndim(); i++) {
if (!mxnet::dim_size_is_known(*in, i)) {
if (zero_axis != -1)
return false; // more than 1 zero found.
else
zero_axis = i;
} else {
known_dim_size_prod *= (*in)[i];
}
}
(*in)[zero_axis] = out.Size() / known_dim_size_prod;
return true;
}
}
inline bool ReshapeShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const ReshapeParam& param_ = nnvm::get<ReshapeParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U) << "Input: [data]";
CHECK_EQ(out_attrs->size(), 1U);
mxnet::TShape &dshape = (*in_attrs)[0];
if (!mxnet::ndim_is_known(dshape)) return false;
mxnet::TShape oshape;
if (param_.shape.ndim() != 0) {
oshape = InferReshapeShape(param_.shape, dshape, param_.reverse);
} else if (param_.target_shape.ndim() != -1) {
LOG(INFO) << "Using target_shape will be deprecated.";
oshape = param_.target_shape;
int neg_count = 0;
index_t inf_idx = 0;
index_t start_idx = param_.keep_highest ? 1 : 0;
if (param_.keep_highest) {
oshape[0] = dshape[0];
}
for (int i = start_idx; i < oshape.ndim(); ++i) {
if (oshape[i] == 0) {
neg_count++;
inf_idx = i;
}
}
if (neg_count == 1) {
oshape[inf_idx] = 1;
oshape[inf_idx] = dshape.Size() / oshape.Size();
}
} else {
return shape_is_known((*out_attrs)[0])
&& ReverseReshapeInferShape(&(*in_attrs)[0], (*out_attrs)[0]);
}
ReverseReshapeInferShape(&dshape, oshape);
#if 0
CHECK_EQ(oshape.Size(), dshape.Size())
<< "Target shape size is different to source. "
<< "Target: " << oshape
<< "\nSource: " << dshape;
#endif
SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape);
return ReverseReshapeInferShape(&(*in_attrs)[0], (*out_attrs)[0]);
}
inline bool FlattenShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
CHECK_EQ(in_attrs->size(), 1U) << "Input: [data]";
CHECK_EQ(out_attrs->size(), 1U);
const mxnet::TShape &dshape = (*in_attrs)[0];
if (!shape_is_known(dshape)) return false;
size_t target_dim = 1;
for (int i = 1; i < dshape.ndim(); ++i) {
target_dim *= dshape[i];
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, mshadow::Shape2(dshape[0], target_dim));
return true;
}
struct TransposeParam : public dmlc::Parameter<TransposeParam> {
mxnet::TShape axes;
DMLC_DECLARE_PARAMETER(TransposeParam) {
DMLC_DECLARE_FIELD(axes).set_default(mxnet::TShape(0, -1))
.describe("Target axis order. By default the axes will be inverted.");
}
bool operator==(const TransposeParam &other) const {
return this->axes == other.axes;
}
};
/*!
* \brief This function performs transpose operation on a 2D matrix by utilizing the L1 cache
* \param in input tensor
* \param out output tensor
* \param row shape of dim 0 of input
* \param col shape of dim 1 of input
* \tparam DType Data type
* \tparam is_addto
*/
template<typename DType, bool is_addto>
MSHADOW_XINLINE void Transpose2D(const DType *in, DType *out, index_t row, index_t col) {
// ensure cache line hits and prevent cache miss for any configuration
// L1 cache size to be utilized = 32kb = 2^15
// Largest size of a single unit of any dtype <= 8 byte = 2^3
// Number of elements - (2^15/2^3) = 2^12
// Block-size - 2^6 v 2^6 (64 v 64)
// But we could leverage unrolling of for loops (for parallelization)
// Block-size - 2^5 v 2^5 (32 v 32) with potential 4 pragma for loop unrolled
// blocksize * blocksize * num_threads = cache_size / dtype_size
// Instead of explicit unroll, let compiler figure out optimal unroll factor
const index_t blocksize = 32;
// collapse 2 parallelizes 2 for loops
// inner 2 for loops aren't parallelized to prevent cache miss
// Microsoft Visual C++ compiler does not support omp collapse
#ifdef _MSC_VER
#pragma omp parallel for
#else
#pragma omp parallel for collapse(2)
#endif // _MSC_VER
for (index_t i = 0; i < row; i += blocksize) {
for (index_t j = 0; j < col; j += blocksize) {
// transpose the block
for (index_t a = j; (a < blocksize + j) && (a < col); ++a) {
for (index_t b = i; (b < blocksize + i) && (b < row); ++b) {
if (!is_addto) {
out[a * row + b] = in[b * col + a];
} else {
out[a * row + b] += in[b * col + a];
}
}
}
}
}
}
inline bool IsIdentityTranspose(const TShape& axes) {
for (dim_t i = 0; i < axes.ndim(); i++) {
if (axes[i] != i) return false;
}
return true;
}
template<typename xpu, bool is_addto = false>
bool TransposeCommonImpl(RunContext ctx,
const TBlob& src,
const TBlob& ret,
const mxnet::TShape& axes) {
// return true when running successfully, otherwise false
using namespace mshadow;
using namespace mshadow::expr;
CHECK_EQ(src.type_flag_, ret.type_flag_);
// zero-size tensor, no need to compute
if (src.shape_.Size() == 0U) return true;
Stream<xpu> *s = ctx.get_stream<xpu>();
#ifdef __CUDACC__
// This transpose can be used only if there exist n and m such that:
// params = (0, ..., n-1, n+m, ..., params.size, n, ..., n+m-1)
// Example: (0, 2, 3, 1) or (0, 3, 1, 2), but not (0, 2, 1, 3).
if (isPseudo2DTranspose(axes)) {
MSHADOW_TYPE_SWITCH(ret.type_flag_, DType, {
transpose_pseudo2D<DType, is_addto>(ret, src, axes, s);
});
return true;
}
#endif
// Special handle the identity case
if (IsIdentityTranspose(axes)) {
MSHADOW_TYPE_SWITCH(ret.type_flag_, DType, {
Tensor<xpu, 1, DType> in = src.get_with_shape<xpu, 1, DType>(mshadow::Shape1(src.Size()), s);
Tensor<xpu, 1, DType> out = ret.get_with_shape<xpu, 1, DType>(mshadow::Shape1(ret.Size()), s);
if (!is_addto) {
// Use memcpy to accelerate the speed
Copy(out, in, s);
} else {
mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::identity, kAddTo>, xpu>::Launch(
s, ret.Size(), out.dptr_, in.dptr_);
}
});
return true;
}
// Handle the general transpose case
MSHADOW_TYPE_SWITCH(ret.type_flag_, DType, {
switch (axes.ndim()) {
case 2: {
Tensor<xpu, 2, DType> in = src.get<xpu, 2, DType>(s);
Tensor<xpu, 2, DType> out = ret.get<xpu, 2, DType>(s);
if (ctx.get_ctx().dev_mask() == cpu::kDevMask) {
Transpose2D<DType, is_addto>(in.dptr_, out.dptr_, in.shape_[0], in.shape_[1]);
} else {
LOG(FATAL) << "Not Implemented. We should never reach here because the 2D case "
"in GPU has been covered by transpose_pseudo2D."
" Report an issue in Github.";
}
break;
}
case 3: {
Tensor<xpu, 3, DType> in = src.get<xpu, 3, DType>(s);
Tensor<xpu, 3, DType> out = ret.get<xpu, 3, DType>(s);
if (!is_addto) {
out = transpose(in, axes.get<3>());
} else {
out += transpose(in, axes.get<3>());
}
break;
}
case 4: {
Tensor<xpu, 4, DType> in = src.get<xpu, 4, DType>(s);
Tensor<xpu, 4, DType> out = ret.get<xpu, 4, DType>(s);
if (!is_addto) {
out = transpose(in, axes.get<4>());
} else {
out += transpose(in, axes.get<4>());
}
break;
}
case 5: {
Tensor<xpu, 5, DType> in = src.get<xpu, 5, DType>(s);
Tensor<xpu, 5, DType> out = ret.get<xpu, 5, DType>(s);
if (!is_addto) {
out = transpose(in, axes.get<5>());
} else {
out += transpose(in, axes.get<5>());
}
break;
}
case 6: {
Tensor<xpu, 6, DType> in = src.get<xpu, 6, DType>(s);
Tensor<xpu, 6, DType> out = ret.get<xpu, 6, DType>(s);
if (!is_addto) {
out = transpose(in, axes.get<6>());
} else {
out += transpose(in, axes.get<6>());
}
break;
}
default:
// return false when dimensions > 6
return false;
break;
}
});
return true;
}
template<typename xpu, bool is_addto = false>
void TransposeImpl(RunContext ctx,
const TBlob& src,
const TBlob& ret,
const mxnet::TShape& axes) {
CHECK_LE(axes.ndim(), 6) << "TransposeImpl supports at most 6 dimensions";
CHECK((TransposeCommonImpl<xpu, is_addto>(ctx, src, ret, axes))) <<
"Failed to execute TransposeImpl Operator";
}
template <bool is_addto>
struct TransposeExKernel {
/*!
* \brief
* \param tid global thread id
* \param out_data output data
* \param in_data input data
* \param strides input strides and output strides
* \param ndim the number of dimension
*/
template <typename DType>
MSHADOW_XINLINE static void Map(index_t tid,
DType *out_data,
const DType *in_data,
const dim_t *strides,
const int ndim
) {
// tid is the index of input data
const dim_t* const out_strides = strides + ndim;
index_t k = tid;
index_t out_id = 0;
for (int i = 0; i < ndim; ++i) {
out_id += (k / strides[i]) * out_strides[i];
k %= strides[i];
}
if (is_addto)
out_data[out_id] += in_data[tid];
else
out_data[out_id] = in_data[tid];
}
};
template<typename xpu, bool is_addto = false>
void TransposeExImpl(RunContext ctx,
const TBlob& src,
const TBlob& ret,
const mxnet::TShape& axes,
mshadow::Tensor<xpu, 1, dim_t>& strides_xpu
) {
/*
* If ndim <= 6, it is not necessary to allocate any space for `strides_xpu`
* If ndim > 6, `strides_xpu` should be allocated `ndim * 2` elements
*/
using namespace mshadow;
using namespace mshadow::expr;
if (TransposeCommonImpl<xpu, is_addto>(ctx, src, ret, axes)) return;
CHECK_GT(axes.ndim(), 6) <<
"Failed to execute TransposeExImpl when axes.ndim() <= 6";
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH(ret.type_flag_, DType, {
CHECK_EQ(strides_xpu.MSize(), axes.ndim() * 2) << \
"If ndim > 6, `strides_xpu` should be allocated `ndim * 2` elements";
const mxnet::TShape &in_shape = src.shape_;
// strides: in_strides and out_strides
const int ndim = axes.ndim();
std::vector<dim_t> strides(ndim * 2);
// compute in_strides
strides[ndim - 1] = 1;
for (int i = ndim - 2; i >= 0; --i) {
strides[i] = strides[i + 1] * in_shape[i + 1];
}
// compute out_strides
std::vector<dim_t> tmp_strides(ndim);
tmp_strides[ndim - 1] = 1;
for (int i = ndim - 2; i >= 0; --i) {
tmp_strides[i] = tmp_strides[i + 1] * in_shape[axes[i + 1]];
}
// reorder tmp_strides to out_strides
dim_t * const out_strides = &strides[ndim];
for (int i = 0; i < ndim; ++i) {
out_strides[axes[i]] = tmp_strides[i];
}
Shape<1> strides_shape;
strides_shape[0] = ndim * 2;
Tensor<cpu, 1, dim_t> strides_cpu(strides.data(), strides_shape);
// copy arguments into xpu context
Copy(strides_xpu, strides_cpu, s);
const DType *in = src.dptr<DType>();
DType *out = ret.dptr<DType>();
if (is_addto) {
mxnet_op::Kernel<TransposeExKernel<true>, xpu>::Launch(s,
in_shape.Size(), out, in, strides_xpu.dptr_, ndim);
} else {
mxnet_op::Kernel<TransposeExKernel<false>, xpu>::Launch(s,
in_shape.Size(), out, in, strides_xpu.dptr_, ndim);
}
});
}
template<typename xpu>
mshadow::Tensor<xpu, 1, dim_t> GetTransposeExWorkspace(
const OpContext& ctx,
const mxnet::TShape& axes
) {
if (axes.ndim() > 6) {
// allocate workspace when axes.ndim() > 6
mshadow::Shape<1> strides_shape;
strides_shape[0] = axes.ndim() * 2;
return ctx.requested[0].get_space_typed<xpu, 1, dim_t>(
strides_shape, ctx.get_stream<xpu>());
}
return {};
}
// matrix transpose
template<typename xpu>
void Transpose(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
if (req[0] == kNullOp) {
return;
}
const TransposeParam& param = nnvm::get<TransposeParam>(attrs.parsed);
CHECK(req[0] == kWriteTo || req[0] == kAddTo)
<< "Transpose only supports kNullOp, kWriteTo and kAddTo";
mxnet::TShape axes;
if (param.axes.ndim() == 0) {
axes = mxnet::TShape(inputs[0].ndim(), -1);
for (int i = 0; i < axes.ndim(); ++i) {
axes[i] = axes.ndim() - 1 - i;
}
} else {
axes = common::CanonicalizeAxes(param.axes);
}
mshadow::Tensor<xpu, 1, dim_t> workspace =
GetTransposeExWorkspace<xpu>(ctx, axes);
if (req[0] == kAddTo) {
TransposeExImpl<xpu, true>(ctx.run_ctx, inputs[0], outputs[0],
axes, workspace);
} else {
TransposeExImpl<xpu, false>(ctx.run_ctx, inputs[0], outputs[0],
axes, workspace);
}
}
inline bool TransposeShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const TransposeParam& param = nnvm::get<TransposeParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
mxnet::TShape& shp = (*in_attrs)[0];
mxnet::TShape& out_shp = (*out_attrs)[0];
if (!mxnet::ndim_is_known(shp) && !mxnet::ndim_is_known(out_shp))
return false; // none of the shapes is known
if (out_shp.ndim() >= 0 && shp.ndim() >= 0)
CHECK_EQ(out_shp.ndim(), shp.ndim());
mxnet::TShape get(std::max(shp.ndim(), out_shp.ndim()), -1);
mxnet::TShape ret(std::max(shp.ndim(), out_shp.ndim()), -1);
if (param.axes.ndim() == 0) {
for (int i = 0; i < shp.ndim(); ++i) {
ret[i] = shp[shp.ndim()-1-i];
}
for (int i = 0; i < out_shp.ndim(); ++i) {
get[shp.ndim()-1-i] = out_shp[i];
}
} else {
CHECK_EQ(std::max(shp.ndim(), out_shp.ndim()), param.axes.ndim());
for (int i = 0; i < shp.ndim(); ++i) {
CHECK(param.axes[i] < static_cast<int64_t>(shp.ndim()));
ret[i] = shp[param.axes[i]];
}
for (int i = 0; i < out_shp.ndim(); ++i) {
get[param.axes[i]] = out_shp[i];
}
}
SHAPE_ASSIGN_CHECK(*in_attrs, 0, get);
SHAPE_ASSIGN_CHECK(*out_attrs, 0, ret);
return shape_is_known(ret);
}
struct ExpandDimParam : public dmlc::Parameter<ExpandDimParam> {
int axis;
DMLC_DECLARE_PARAMETER(ExpandDimParam) {
DMLC_DECLARE_FIELD(axis)
.describe("Position where new axis is to be inserted. Suppose that "
"the input `NDArray`'s dimension is `ndim`, the range of "
"the inserted axis is `[-ndim, ndim]`");
}
bool operator==(const ExpandDimParam &other) const {
return this->axis == other.axis;
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream axis_s;
axis_s << axis;
(*dict)["axis"] = axis_s.str();
}
};
inline bool ExpandDimShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const ExpandDimParam& param = nnvm::get<ExpandDimParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
mxnet::TShape& ishape = (*in_attrs)[0];
mxnet::TShape& oshape = (*out_attrs)[0];
if (!mxnet::ndim_is_known(ishape) && !mxnet::ndim_is_known(oshape)) {
return false;
}
int indim = ishape.ndim();
bool unknown_ishape = false;
if (-1 == indim) {
indim = oshape.ndim() - 1;
unknown_ishape = true;
}
int axis = param.axis;
if (axis < 0) {
axis += indim + 1;
}
CHECK(axis >= 0 && axis <= indim)
<< "axis must be in the range [" << -indim << ", " << indim << "] ("
<< param.axis << " provided)";
mxnet::TShape ret(indim + 1, -1);
for (int i = 0; i < axis; ++i) {
ret[i] = (unknown_ishape? -1 : ishape[i]);
}
ret[axis] = 1;
for (int i = axis+1; i < indim+1; ++i) {
ret[i] = (unknown_ishape? -1 : ishape[i-1]);
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, ret);
ret = mxnet::TShape(indim, -1);
for (int i = 0; i < axis; ++i) ret[i] = oshape[i];
for (int i = axis+1; i < indim+1; ++i) ret[i-1] = oshape[i];
SHAPE_ASSIGN_CHECK(*in_attrs, 0, ret);
return shape_is_known(in_attrs->at(0)) && shape_is_known(out_attrs->at(0));
}
// Currently MKLDNN only supports step = 1 or step has no value
inline bool SupportMKLDNNSlice(const SliceParam& param) {
if (param.step.ndim() == 0U) return true;
for (int i = 0; i < param.step.ndim(); ++i) {
if (param.step[i].has_value() && param.step[i].value() != 1)
return false;
}
return true;
}
inline bool SliceForwardInferStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1);
CHECK_EQ(out_attrs->size(), 1);
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
const auto& in_stype = in_attrs->at(0);
auto& out_stype = out_attrs->at(0);
bool dispatched = false;
const auto dispatch_ex = DispatchMode::kFComputeEx;
// If step = 1, no need to fallback; otherwise fallback to dense
bool trivial_step = false;
if (param.step.ndim() == 0U) {
trivial_step = true;
} else if (param.step.ndim() == 1U
&& (!param.step[0].has_value() || param.step[0].value() == 1)) {
trivial_step = true;
}
if (in_stype == kDefaultStorage) {
#if MXNET_USE_ONEDNN == 1
if (dev_mask == Context::kCPU && MKLDNNEnvSet()
&& SupportMKLDNNSlice(param)) {
dispatched = storage_type_assign(&out_stype, kDefaultStorage,
dispatch_mode, dispatch_ex);
}
#endif
if (!dispatched) {
dispatched = storage_type_assign(&out_stype, kDefaultStorage,
dispatch_mode, DispatchMode::kFCompute);
}
}
if (!dispatched && in_stype == kCSRStorage && trivial_step) {
dispatched = storage_type_assign(&out_stype, kCSRStorage,
dispatch_mode, dispatch_ex);
}
if (!dispatched) {
dispatched = dispatch_fallback(out_attrs, dispatch_mode);
}
return dispatched;
}
// slice the indptr of a csr
struct SliceCsrIndPtr {
template<typename IType>
MSHADOW_XINLINE static void Map(int i, IType* out, const IType* in, const IType* base) {
KERNEL_ASSIGN(out[i], kWriteTo, in[i] - *base);
}
};
/*
* a wrapper to launch SliceCsrIndPtr kernel.
* slice [src[begin] .. src[end]) and store in dst[0, end - begin)
*/
template<typename xpu, typename IType>
void SliceCsrIndPtrImpl(const int begin, const int end, RunContext ctx,
const IType* src, IType* dst) {
using namespace mshadow;
using namespace mxnet_op;
Stream<xpu> *s = ctx.get_stream<xpu>();
int indptr_len = end - begin + 1;
Kernel<SliceCsrIndPtr, xpu>::Launch(s, indptr_len, dst, src + begin, src + begin);
}
/*
* Slice a CSR NDArray for first dimension
*/
template<typename xpu>
void SliceDimOneCsrImpl(const mxnet::TShape &begin, const mxnet::TShape &end, const OpContext& ctx,
const NDArray &in, const NDArray &out) {
using namespace mshadow;
using namespace mxnet_op;
using namespace csr;
nnvm::dim_t begin_row = begin[0];
nnvm::dim_t end_row = end[0];
nnvm::dim_t indptr_len = end_row - begin_row + 1;
out.CheckAndAllocAuxData(kIndPtr, Shape1(indptr_len));
// assume idx indptr share the same type
MSHADOW_IDX_TYPE_SWITCH(in.aux_type(kIndPtr), RType, {
MSHADOW_IDX_TYPE_SWITCH(in.aux_type(kIdx), IType, {
MSHADOW_TYPE_SWITCH(in.dtype(), DType, {
RType* in_indptr = in.aux_data(kIndPtr).dptr<RType>();
RType* out_indptr = out.aux_data(kIndPtr).dptr<RType>();
SliceCsrIndPtrImpl<xpu, RType>(begin_row, end_row, ctx.run_ctx, in_indptr, out_indptr);
Stream<xpu> *s = ctx.get_stream<xpu>();
RType nnz = 0;
mshadow::Copy(Tensor<cpu, 1, RType>(&nnz, Shape1(1)),
Tensor<xpu, 1, RType>(out_indptr + indptr_len - 1, Shape1(1), s));
// return csr zeros if nnz = 0
if (nnz == 0) {
out.set_aux_shape(kIdx, Shape1(0));
return;
}
// copy indices and values
out.CheckAndAllocAuxData(kIdx, Shape1(nnz));
out.CheckAndAllocData(Shape1(nnz));
IType* in_idx = in.aux_data(kIdx).dptr<IType>();
IType* out_idx = out.aux_data(kIdx).dptr<IType>();
DType* in_data = in.data().dptr<DType>();
DType* out_data = out.data().dptr<DType>();
RType offset = 0;
mshadow::Copy(Tensor<cpu, 1, RType>(&offset, Shape1(1)),
Tensor<xpu, 1, RType>(in_indptr + begin_row, Shape1(1), s));
mshadow::Copy(Tensor<xpu, 1, IType>(out_idx, Shape1(nnz), s),
Tensor<xpu, 1, IType>(in_idx + offset, Shape1(nnz), s), s);
mshadow::Copy(Tensor<xpu, 1, DType>(out_data, Shape1(nnz), s),
Tensor<xpu, 1, DType>(in_data + offset, Shape1(nnz), s), s);
});
});
});
}
/*!
* \brief slice a CSRNDArray for two dimensions
*/
struct SliceDimTwoCsrAssign {
/*!
* \brief This function slices a CSRNDArray on axis one between begin_col and end_col
* \param i loop index
* \param out_idx output csr ndarray column indices
* \param out_data output csr ndarray data
* \param out_indptr output csr ndarray row index pointer
* \param in_idx input csr ndarray column indices
* \param in_data input csr ndarray data
* \param in_indptr input csr ndarray row index pointer
* \param begin_col begin column indice
* \param end_col end column indice
*/
template<typename IType, typename RType, typename DType>
MSHADOW_XINLINE static void Map(int i,
IType* out_idx, DType* out_data,
const RType* out_indptr,
const IType* in_idx, const DType* in_data,
const RType* in_indptr,
const int begin_col, const int end_col) {
RType ind = out_indptr[i];
for (RType j = in_indptr[i]; j < in_indptr[i+1]; j++) {
// indices of CSRNDArray are in ascending order per row
if (in_idx[j] >= end_col) {
break;
} else if (in_idx[j] >= begin_col) {
out_idx[ind] = in_idx[j] - begin_col;
out_data[ind] = in_data[j];
ind++;
}
}
}
};
/*
* Slice a CSR NDArray for two dimensions
*/
template<typename xpu>
void SliceDimTwoCsrImpl(const mxnet::TShape &begin, const mxnet::TShape &end, const OpContext& ctx,
const NDArray &in, const NDArray &out);
template<typename xpu>
void SliceCsrImpl(const SliceParam ¶m, const OpContext& ctx,
const NDArray &in, OpReqType req, const NDArray &out) {
if (req == kNullOp) return;
CHECK_NE(req, kAddTo) << "kAddTo for Slice on CSR input is not supported";
CHECK_NE(req, kWriteInplace) << "kWriteInplace for Slice on CSR input is not supported";
const mxnet::TShape ishape = in.shape();
const mxnet::TShape oshape = out.shape();
int N = ishape.ndim();
mxnet::TShape begin(N, -1), end(N, -1);
for (int i = 0; i < N; ++i) {
int s = 0;
if (i < param.begin.ndim() && param.begin[i]) {
s = *param.begin[i];
if (s < 0) s += ishape[i];
}
begin[i] = s;
end[i] = s + oshape[i];
}
switch (N) {
case 1: {
SliceDimOneCsrImpl<xpu>(begin, end, ctx, in, out);
break;
}
case 2: {
SliceDimTwoCsrImpl<xpu>(begin, end, ctx, in, out);
break;
}
default:
LOG(FATAL) << "CSR is only for 2-D shape";
break;
}
}
template<typename xpu>
void SliceEx(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
CHECK_EQ(inputs.size(), 1);
CHECK_EQ(outputs.size(), 1);
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
auto in_stype = inputs[0].storage_type();
if (in_stype == kCSRStorage) {
SliceCsrImpl<xpu>(param, ctx, inputs[0], req[0], outputs[0]);
} else {
LOG(FATAL) << "Slice not implemented for storage type" << in_stype;
}
}
template<int ndim>
inline bool GetIndexRange(const mxnet::TShape& dshape,
const mxnet::Tuple<dmlc::optional<index_t>>& param_begin,
const mxnet::Tuple<dmlc::optional<index_t>>& param_end,
const mxnet::Tuple<dmlc::optional<index_t>>& param_step,
common::StaticArray<index_t, ndim>* begin,
common::StaticArray<index_t, ndim>* end,
common::StaticArray<index_t, ndim>* step) {
// Function returns false if output is zero-sized, true otherwise.
bool zero_size_shape = false;
CHECK_NE(dshape.ndim(), 0U);
CHECK_LE(param_begin.ndim(), dshape.ndim())
<< "Slicing axis exceeds data dimensions";
CHECK_LE(param_end.ndim(), dshape.ndim())
<< "Slicing axis exceeds data dimensions";
CHECK_EQ(param_begin.ndim(), param_end.ndim())
<< "begin and end must have the same length";
CHECK_EQ(ndim, dshape.ndim())
<< "Static array size=" << ndim
<< " is not equal to data shape ndim=" << dshape.ndim();
if (param_step.ndim() > 0) {
CHECK_EQ(param_step.ndim(), param_begin.ndim())
<< "step and begin must have the same length";
}
for (int i = 0; i < param_begin.ndim(); ++i) {
index_t s = param_step.ndim() > 0 && param_step[i].has_value() ? param_step[i].value() : 1;
CHECK_NE(s, 0) << "slice op step[" << i << "] cannot be 0";
index_t b = 0, e = 0;
const index_t len = dshape[i];
if (len > 0) {
b = param_begin[i].has_value() ? param_begin[i].value() : (s < 0 ? len - 1 : 0);
e = param_end[i].has_value() ? param_end[i].value() : (s < 0 ? -1 : len);
if (b < 0) {
b += len;
}
if (e < 0 && param_end[i].has_value()) {
e += len;
}
// move the begin and end to correct position for calculating dim size
b = (b < 0 && s > 0) ? 0 : b;
b = (b > len - 1 && s < 0) ? len - 1 : b;
// if the start value lead to empty tensor under step s, use -1 for indication
b = (b < 0 || b > len - 1) ? -1 : b;
e = e > -1 ? e : -1;
e = e > len ? len : e;
} else if (len == 0) {
b = 0;
e = 0;
}
(*begin)[i] = b;
(*end)[i] = e;
(*step)[i] = s;
// checking begin==end
if (b == e) {
zero_size_shape = true;
}
}
for (int i = param_begin.ndim(); i < dshape.ndim(); ++i) {
(*begin)[i] = 0;
(*end)[i] = dshape[i];
(*step)[i] = 1;
}
return zero_size_shape;
}
inline void SetSliceOpOutputDimSize(const mxnet::TShape& dshape,
const index_t i, const index_t b,
const index_t e, const index_t s,
mxnet::TShape* oshape) {
if (!mxnet::dim_size_is_known(dshape, i)) {
(*oshape)[i] = -1;
return;
}
if (e != b && b >= 0) {
if (s > 0) {
(*oshape)[i] = e > b ? (e - b - 1) / s + 1 : 0;
} else {
(*oshape)[i] = e < b ? (b - e - 1) / (-s) + 1 : 0;
}
} else {
(*oshape)[i] = 0;
}
}
inline bool SliceOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
const mxnet::TShape& dshape = (*in_attrs)[0];
if (!mxnet::ndim_is_known(dshape)) return false;
CHECK_GT(dshape.ndim(), 0) << "slice only works for ndim > 0";
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
mxnet::TShape oshape = dshape;
MXNET_NDIM_SWITCH(dshape.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
GetIndexRange(dshape, param.begin, param.end, param.step, &begin, &end, &step);
for (int i = 0; i < param.begin.ndim(); ++i) {
const index_t b = begin[i], e = end[i], s = step[i];
SetSliceOpOutputDimSize(dshape, i, b, e, s, &oshape);
}
})
SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape);
return shape_is_known(dshape) && shape_is_known(oshape);
}
template<int ndim, int req, typename xpu>
struct slice_forward;
template<int ndim, int req>
struct slice_forward<ndim, req, gpu> {
// i is the i-th row after flattening out into 2D tensor
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* data,
const mshadow::Shape<ndim> dshape,
const mshadow::Shape<ndim> oshape,
const common::StaticArray<index_t, ndim> begin,
const common::StaticArray<index_t, ndim> step) {
const index_t data_last_dim_size = dshape[ndim-1];
const index_t out_last_dim_size = oshape[ndim-1];
const index_t step_last_dim = step[ndim-1];
const index_t begin_last_dim = begin[ndim-1];
const index_t j = i % out_last_dim_size;
index_t irow = 0; // row id of flattend 2D data
index_t stride = 1;
index_t idx = i / out_last_dim_size;
#pragma unroll
for (int k = ndim - 2; k >= 0; --k) {
irow += stride * ((idx % oshape[k]) * step[k] + begin[k]);
idx /= oshape[k];
stride *= dshape[k];
}
KERNEL_ASSIGN(out[i], req,
data[irow * data_last_dim_size + j * step_last_dim + begin_last_dim]);
}
};
template<int ndim, int req>
struct slice_forward<ndim, req, cpu> {
// i is the i-th row after flattening out into 2D tensor
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* data,
const mshadow::Shape<ndim> dshape,
const mshadow::Shape<ndim> oshape,
const common::StaticArray<index_t, ndim> begin,
const common::StaticArray<index_t, ndim> step) {
const index_t data_last_dim_size = dshape[ndim-1];
const index_t out_last_dim_size = oshape[ndim-1];
const index_t step_last_dim = step[ndim-1];
const index_t begin_last_dim = begin[ndim-1];
index_t out_offset = i * out_last_dim_size;
for (index_t j = 0; j < out_last_dim_size; ++j) {
index_t irow = 0; // row id of flattend 2D data
index_t stride = 1;
index_t idx = i;
#pragma unroll
for (int k = ndim - 2; k >= 0; --k) {
irow += stride * ((idx % oshape[k]) * step[k] + begin[k]);
idx /= oshape[k];
stride *= dshape[k];
}
KERNEL_ASSIGN(out[out_offset++], req,
data[irow * data_last_dim_size + j * step_last_dim + begin_last_dim]);
}
}
};
template<typename xpu>
void SliceOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
if (req[0] == kNullOp) return;
using namespace mshadow;
Stream<xpu>* s = ctx.get_stream<xpu>();
const TBlob& data = inputs[0];
const TBlob& out = outputs[0];
if (out.Size() == 0) return;
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
MXNET_NDIM_SWITCH(data.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
GetIndexRange(data.shape_, param.begin, param.end, param.step, &begin, &end, &step);
MSHADOW_TYPE_SWITCH_WITH_BOOL(out.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
size_t num_threads = out.shape_.FlatTo2D()[0];
if (std::is_same<xpu, gpu>::value) {
num_threads *= out.shape_.get<ndim>()[ndim - 1];
}
mxnet_op::Kernel<slice_forward<ndim, Req, xpu>, xpu>::Launch(s, num_threads,
out.dptr<DType>(), data.dptr<DType>(),
data.shape_.get<ndim>(), out.shape_.get<ndim>(), begin, step);
})
})
})
}
template<int ndim, int req, typename xpu>
struct slice_assign;
template<int ndim, int req>
struct slice_assign<ndim, req, cpu> {
// i is the i-th row after flattening out into 2D tensor
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* val,
const mshadow::Shape<ndim> oshape,
const mshadow::Shape<ndim> vshape,
const common::StaticArray<index_t, ndim> begin,
const common::StaticArray<index_t, ndim> step) {
const index_t data_last_dim_size = oshape[ndim-1];
const index_t out_last_dim_size = vshape[ndim-1];
const index_t step_last_dim = step[ndim-1];
const index_t begin_last_dim = begin[ndim-1];
index_t offset = i * out_last_dim_size;
for (index_t j = 0; j < out_last_dim_size; ++j) {
index_t irow = 0; // row id of flattend 2D out
index_t stride = 1;
index_t idx = i;
#pragma unroll
for (int k = ndim - 2; k >= 0; --k) {
irow += stride * ((idx % vshape[k]) * step[k] + begin[k]);
idx /= vshape[k];
stride *= oshape[k];
}
KERNEL_ASSIGN(out[irow * data_last_dim_size + j * step_last_dim + begin_last_dim],
req, val[offset++]);
}
}
};
template<int ndim, int req>
struct slice_assign<ndim, req, gpu> {
// i is the i-th row after flattening out into 2D tensor
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* val,
const mshadow::Shape<ndim> oshape,
const mshadow::Shape<ndim> vshape,
const common::StaticArray<index_t, ndim> begin,
const common::StaticArray<index_t, ndim> step) {
const index_t data_last_dim_size = oshape[ndim-1];
const index_t out_last_dim_size = vshape[ndim-1];
const index_t step_last_dim = step[ndim-1];
const index_t begin_last_dim = begin[ndim-1];
const index_t j = i % out_last_dim_size;
index_t irow = 0; // row id of flattend 2D out
index_t stride = 1;
index_t idx = i / out_last_dim_size;
#pragma unroll
for (int k = ndim - 2; k >= 0; --k) {
irow += stride * ((idx % vshape[k]) * step[k] + begin[k]);
idx /= vshape[k];
stride *= oshape[k];
}
KERNEL_ASSIGN(out[irow * data_last_dim_size + j * step_last_dim + begin_last_dim],
req, val[i]);
}
};
template<typename xpu>
void SliceOpBackward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
if (req[0] == kNullOp) return;
using namespace mshadow;
Stream<xpu>* s = ctx.get_stream<xpu>();
const TBlob& ograd = inputs[0];
const TBlob& igrad = outputs[0];
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
if (req[0] == kWriteTo) {
Fill(s, igrad, req[0], 0);
} else if (req[0] == kWriteInplace) {
LOG(FATAL) << "_slice_backward does not support kWriteInplace";
}
if (ograd.Size() == 0) return;
MXNET_NDIM_SWITCH(ograd.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
GetIndexRange(igrad.shape_, param.begin, param.end, param.step, &begin, &end, &step);
MSHADOW_TYPE_SWITCH(ograd.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
int num_threads = ograd.shape_.FlatTo2D()[0];
if (std::is_same<xpu, gpu>::value) {
num_threads *= ograd.shape_.get<ndim>()[ndim - 1];
}
mxnet_op::Kernel<slice_assign<ndim, Req, xpu>, xpu>::Launch(s, num_threads,
igrad.dptr<DType>(), ograd.dptr<DType>(),
igrad.shape_.get<ndim>(), ograd.shape_.get<ndim>(), begin, step);
})
})
})
}
inline bool SliceAssignOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
CHECK_EQ(in_attrs->size(), 2U);
CHECK_EQ(out_attrs->size(), 1U);
const mxnet::TShape& dshape = (*in_attrs)[0];
if (!mxnet::ndim_is_known(dshape)) return false;
mxnet::TShape vshape = dshape; // vshape is the value shape on the right hand side
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
MXNET_NDIM_SWITCH(dshape.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
GetIndexRange(dshape, param.begin, param.end, param.step, &begin, &end, &step);
for (int i = 0; i < param.begin.ndim(); ++i) {
const index_t b = begin[i], e = end[i], s = step[i];
SetSliceOpOutputDimSize(dshape, i, b, e, s, &vshape);
}
})
SHAPE_ASSIGN_CHECK(*in_attrs, 1, vshape);
SHAPE_ASSIGN_CHECK(*out_attrs, 0, dshape);
return true;
}
template<typename xpu>
void SliceAssignOpForward(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;
CHECK_EQ(inputs.size(), 2U); // data[index] = val, data and val are two inputs
CHECK_EQ(outputs.size(), 1U);
if (req[0] == kNullOp) return;
Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob& data = inputs[0];
const TBlob& val = inputs[1];
const TBlob& out = outputs[0];
if (req[0] == kWriteTo) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
Tensor<xpu, 1, DType> in = inputs[0].FlatTo1D<xpu, DType>(s);
Tensor<xpu, 1, DType> out = outputs[0].FlatTo1D<xpu, DType>(s);
Copy(out, in, s);
});
} else if (req[0] != kWriteInplace) {
LOG(FATAL) << "_slice_assign only supports kWriteTo and kWriteInplace";
}
const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed);
MXNET_NDIM_SWITCH(data.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
bool zero_size_shape = GetIndexRange(data.shape_, param.begin, param.end, param.step,
&begin, &end, &step);
if (zero_size_shape) {
return; // slice_assign of zero-sized subspace needs no operation.
}
MSHADOW_TYPE_SWITCH(out.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
index_t num_threads = val.shape_.FlatTo2D()[0];
if (std::is_same<xpu, gpu>::value) {
num_threads *= val.shape_.get<ndim>()[ndim - 1];
}
mxnet_op::Kernel<slice_assign<ndim, Req, xpu>, xpu>::Launch(s, num_threads,
out.dptr<DType>(), val.dptr<DType>(),
out.shape_.get<ndim>(), val.shape_.get<ndim>(), begin, step);
})
})
})
}
struct SliceAssignScalarParam : public dmlc::Parameter<SliceAssignScalarParam> {
double scalar;
mxnet::Tuple<dmlc::optional<index_t>> begin, end;
mxnet::Tuple<dmlc::optional<index_t>> step;
DMLC_DECLARE_PARAMETER(SliceAssignScalarParam) {
DMLC_DECLARE_FIELD(scalar)
.set_default(0)
.describe("The scalar value for assignment.");
DMLC_DECLARE_FIELD(begin)
.describe("starting indices for the slice operation, supports negative indices.");
DMLC_DECLARE_FIELD(end)
.describe("ending indices for the slice operation, supports negative indices.");
DMLC_DECLARE_FIELD(step)
.set_default(mxnet::Tuple<dmlc::optional<index_t>>())
.describe("step for the slice operation, supports negative values.");
}
};
inline bool SliceAssignScalarOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
const mxnet::TShape& dshape = (*in_attrs)[0];
if (!shape_is_known(dshape)) return false;
SHAPE_ASSIGN_CHECK(*out_attrs, 0, dshape);
return true;
}
template<int ndim>
struct slice_assign_scalar {
// i is the i-th row after flattening out into 2D tensor
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType val,
const OpReqType req,
const mshadow::Shape<ndim> oshape,
const mshadow::Shape<ndim> vshape,
const common::StaticArray<index_t, ndim> begin,
const common::StaticArray<index_t, ndim> step) {
const index_t data_last_dim_size = oshape[ndim-1];
const index_t out_last_dim_size = vshape[ndim-1];
const index_t step_last_dim = step[ndim-1];
const index_t begin_last_dim = begin[ndim-1];
for (index_t j = 0; j < out_last_dim_size; ++j) {
index_t irow = 0; // row id of flattend 2D out
index_t stride = 1;
index_t idx = i;
#pragma unroll
for (int k = ndim - 2; k >= 0; --k) {
irow += stride * ((idx % vshape[k]) * step[k] + begin[k]);
idx /= vshape[k];
stride *= oshape[k];
}
KERNEL_ASSIGN(out[irow * data_last_dim_size + j * step_last_dim + begin_last_dim], req, val);
}
}
};
template<typename xpu>
void SliceAssignScalarOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
using namespace mshadow;
Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob& data = inputs[0];
const TBlob& out = outputs[0];
if (req[0] == kWriteTo) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
Tensor<xpu, 1, DType> in = inputs[0].FlatTo1D<xpu, DType>(s);
Tensor<xpu, 1, DType> out = outputs[0].FlatTo1D<xpu, DType>(s);
Copy(out, in, s);
});
} else if (req[0] != kWriteInplace) {
LOG(FATAL) << "_crop_assign_scalar only supports kWriteTo and kWriteInplace";
}
mxnet::TShape vshape = data.shape_;
const SliceAssignScalarParam& param = nnvm::get<SliceAssignScalarParam>(attrs.parsed);
MXNET_NDIM_SWITCH(data.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
bool zero_size_shape = GetIndexRange(data.shape_, param.begin, param.end, param.step,
&begin, &end, &step);
if (zero_size_shape) {
return; // slice_assign of zero-sized subspaced needs no operation.
}
for (index_t i = 0; i < param.begin.ndim(); ++i) {
const index_t b = begin[i], e = end[i], s = step[i];
SetSliceOpOutputDimSize(data.shape_, i, b, e, s, &vshape);
}
MSHADOW_TYPE_SWITCH_WITH_BOOL(out.type_flag_, DType, {
mxnet_op::Kernel<slice_assign_scalar<ndim>, xpu>::Launch(s, vshape.FlatTo2D()[0],
out.dptr<DType>(), static_cast<DType>(param.scalar), req[0],
out.shape_.get<ndim>(), vshape.get<ndim>(), begin, step);
})
})
}
struct SliceAxisParam : public dmlc::Parameter<SliceAxisParam> {
int axis;
index_t begin;
dmlc::optional<index_t> end;
DMLC_DECLARE_PARAMETER(SliceAxisParam) {
DMLC_DECLARE_FIELD(axis)
.describe("Axis along which to be sliced, supports negative indexes.");
DMLC_DECLARE_FIELD(begin)
.describe("The beginning index along the axis to be sliced, "
" supports negative indexes.");
DMLC_DECLARE_FIELD(end)
.describe("The ending index along the axis to be sliced, "
" supports negative indexes.");
}
};
inline void GetSliceAxisParams(const SliceAxisParam& param, const mxnet::TShape& ishape,
int* axis, index_t* begin, index_t* end) {
*axis = param.axis;
if (*axis < 0) {
*axis += ishape.ndim();
}
CHECK(*axis < ishape.ndim() && *axis >= 0) <<
"Transformed axis must be smaller than the source ndim and larger than zero! Recieved axis=" <<
param.axis << ", src_ndim=" << ishape.ndim() << ", transformed axis=" << *axis;
index_t axis_size = static_cast<index_t>(ishape[*axis]);
*begin = param.begin;
*end = -1;
if (*begin < 0) {
*begin += axis_size;
}
if (axis_size > 0) {
if (!static_cast<bool>(param.end)) {
*end = axis_size;
} else {
*end = param.end.value();
if (*end < 0) {
*end += axis_size;
}
}
CHECK(*end <= axis_size) << "Invalid end for end=" << *end << " as axis_size is " << axis_size;
CHECK((*begin < *end))
<< "Invalid begin, end, get begin=" << param.begin << ", end=" << param.end;
} else {
*begin = 0;
*end = 0;
}
CHECK(*end >= 0)
<< "Invalid begin, end, get begin=" << param.begin << ", end=" << param.end;
CHECK(*begin >= 0) << "Invalid begin for begin=" << param.begin;
}
inline bool SliceAxisShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const SliceAxisParam& param = nnvm::get<SliceAxisParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
mxnet::TShape& ishape = (*in_attrs)[0];
if (!mxnet::ndim_is_known(ishape)) return false;
int axis;
index_t begin, end;
GetSliceAxisParams(param, ishape, &axis, &begin, &end);
if (!mxnet::dim_size_is_known(ishape, axis)) {
SHAPE_ASSIGN_CHECK(*out_attrs, 0, ishape);
return false;
}
mxnet::TShape shape(ishape.ndim(), -1);
for (int i = 0; i < ishape.ndim(); ++i) {
if (i == axis) {
shape[i] = static_cast<index_t>(end - begin);
} else {
shape[i] = ishape[i];
}
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, shape);
return shape_is_known(shape);
}
template<typename xpu>
void SliceAxis(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::expr;
const SliceAxisParam& param = nnvm::get<SliceAxisParam>(attrs.parsed);
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
int axis;
index_t begin, end;
GetSliceAxisParams(param, inputs[0].shape_, &axis, &begin, &end);
int ndim = outputs[0].ndim();
if (axis + 1 == ndim) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
mshadow::Tensor<xpu, 2, DType> in =
inputs[0].FlatTo2D<xpu, DType>(s);
mshadow::Tensor<xpu, 2, DType> out =
outputs[0].FlatTo2D<xpu, DType>(s);
ASSIGN_DISPATCH(out, req[0], slice<1>(in, begin, end));
});
} else {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
mshadow::Tensor<xpu, 3, DType> in =
inputs[0].FlatTo3D<xpu, DType>(axis, s);
mshadow::Tensor<xpu, 3, DType> out =
outputs[0].FlatTo3D<xpu, DType>(axis, s);
ASSIGN_DISPATCH(out, req[0], slice<1>(in, begin, end));
});
}
}
// Backward pass of broadcast over the given axis
template<typename xpu>
void SliceAxisGrad_(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
if (outputs[0].shape_.Size() == 0) {
return;
}
const SliceAxisParam& param = nnvm::get<SliceAxisParam>(attrs.parsed);
using namespace mshadow::op;
using namespace mshadow::expr;
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
int axis;
index_t begin, end;
GetSliceAxisParams(param, outputs[0].shape_, &axis, &begin, &end);
int ndim = outputs[0].shape_.ndim();
if (axis + 1 == ndim) {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
mshadow::Tensor<xpu, 2, DType> ograd =
inputs[0].FlatTo2D<xpu, DType>(s);
mshadow::Tensor<xpu, 2, DType> igrad =
outputs[0].FlatTo2D<xpu, DType>(s);
if (req[0] == kAddTo) {
slice<1>(igrad, begin, end) += F<identity>(ograd);
} else if (req[0] == kWriteTo) {
igrad = 0.0f;
slice<1>(igrad, begin, end) = F<identity>(ograd);
} else {
CHECK_EQ(req[0], kNullOp);
}
});
} else {
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
mshadow::Tensor<xpu, 3, DType> ograd =
inputs[0].FlatTo3D<xpu, DType>(axis, s);
mshadow::Tensor<xpu, 3, DType> igrad =
outputs[0].FlatTo3D<xpu, DType>(axis, s);
if (req[0] == kAddTo) {
slice<1>(igrad, begin, end) += F<identity>(ograd);
} else if (req[0] == kWriteTo) {
igrad = 0.0f;
slice<1>(igrad, begin, end) = F<identity>(ograd);
} else {
CHECK_EQ(req[0], kNullOp);
}
});
}
}
struct SliceLikeParam : public dmlc::Parameter<SliceLikeParam> {
mxnet::Tuple<int> axes;
DMLC_DECLARE_PARAMETER(SliceLikeParam) {
DMLC_DECLARE_FIELD(axes).set_default(mxnet::Tuple<int>())
.describe("List of axes on which input data will be sliced according to the "
"corresponding size of the second input. By default will slice on "
"all axes. Negative axes are supported.");
}
};
inline bool SliceLikeShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const SliceLikeParam& param = nnvm::get<SliceLikeParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 2U);
CHECK_EQ(out_attrs->size(), 1U);
mxnet::TShape& ishape = (*in_attrs)[0];
mxnet::TShape& from_shape = (*in_attrs)[1];
if (!mxnet::ndim_is_known(ishape) || !mxnet::ndim_is_known(from_shape)) {
return false;
}
if (param.axes.ndim() == 0) {
CHECK_EQ(ishape.ndim(), from_shape.ndim())
<< "By default slice_axis performs slice on all axes, but ndim mismatch "
"for inputs: " << ishape.ndim() << " vs. " << from_shape.ndim();
for (int i = 0; i < ishape.ndim(); ++i) {
CHECK_GE(ishape[i], from_shape[i])
<< "Slice axis " << i << " with size " << from_shape[i]
<< "exceeds limit of input with size " << ishape[i];
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, from_shape);
} else {
mxnet::TShape shape(ishape);
for (int i = 0; i < param.axes.ndim(); ++i) {
int axis = param.axes[i];
if (axis < 0) {
axis += ishape.ndim();
}
CHECK_GE(axis, 0)
<< "Slice axis: " << param.axes[i] << " too small";
CHECK_GT(ishape.ndim(), axis)
<< "Slice axis: " << axis << " exceeds first input: " << ishape.ndim();
CHECK_GT(from_shape.ndim(), axis)
<< "Slice axis: " << axis << " exceeds second input: " << from_shape.ndim();
shape[axis] = from_shape[axis];
CHECK_GE(ishape[axis], from_shape[axis])
<< "Slice axis " << axis << " with size " << from_shape[axis]
<< "exceeds limit of input with size " << ishape[axis];
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, shape);
}
return true;
}
inline void SliceLikeInferRanges(const mxnet::TShape& dshape,
const mxnet::TShape& fshape,
const mxnet::Tuple<int>& axes,
mxnet::Tuple<dmlc::optional<index_t>>* param_begin,
mxnet::Tuple<dmlc::optional<index_t>>* param_end,
mxnet::Tuple<dmlc::optional<index_t>>* param_step) {
std::vector<dmlc::optional<index_t>> pb(dshape.ndim());
std::vector<dmlc::optional<index_t>> pe(dshape.ndim());
std::vector<dmlc::optional<index_t>> ps(dshape.ndim());
if (axes.ndim() == 0) {
for (int i = 0; i < dshape.ndim(); ++i) {
pb[i] = 0;
pe[i] = fshape[i];
ps[i] = 1;
}
} else {
for (int i = 0; i < axes.ndim(); ++i) {
int axis = axes[i];
if (axis < 0) {
axis += dshape.ndim();
}
CHECK_GE(axis, 0)
<< "Slice axis: " << axes[i] << " too small";
CHECK_LT(axis, dshape.ndim())
<< "Slice axis: " << axis << " exceeds first input: " << dshape.ndim();
CHECK_LT(axis, fshape.ndim())
<< "Slice axis: " << axis << " exceeds first input: " << fshape.ndim();
pb[axis] = 0;
pe[axis] = fshape[axis];
ps[axis] = 1;
}
}
*param_begin = mxnet::Tuple<dmlc::optional<index_t>>(pb.begin(), pb.end());
*param_end = mxnet::Tuple<dmlc::optional<index_t>>(pe.begin(), pe.end());
*param_step = mxnet::Tuple<dmlc::optional<index_t>>(ps.begin(), ps.end());
}
template<typename xpu>
void SliceLikeForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 2U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
using namespace mshadow::expr;
const SliceLikeParam& param = nnvm::get<SliceLikeParam>(attrs.parsed);
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob& data = inputs[0];
const TBlob& out = outputs[0];
const mxnet::TShape& ishape = data.shape_;
const mxnet::TShape& from_shape = inputs[1].shape_;
mxnet::Tuple<dmlc::optional<index_t>> param_begin;
mxnet::Tuple<dmlc::optional<index_t>> param_end;
mxnet::Tuple<dmlc::optional<index_t>> param_step;
SliceLikeInferRanges(ishape, from_shape, param.axes, ¶m_begin, ¶m_end, ¶m_step);
MXNET_NDIM_SWITCH(data.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
GetIndexRange(data.shape_, param_begin, param_end, param_step, &begin, &end, &step);
MSHADOW_TYPE_SWITCH(out.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
int num_threads = out.shape_.FlatTo2D()[0];
if (std::is_same<xpu, gpu>::value) {
num_threads *= out.shape_.get<ndim>()[ndim - 1];
}
mxnet_op::Kernel<slice_forward<ndim, Req, xpu>, xpu>::Launch(s,
num_threads, out.dptr<DType>(), data.dptr<DType>(),
data.shape_.get<ndim>(), out.shape_.get<ndim>(), begin, step);
})
})
})
}
template<typename xpu>
void SliceLikeBackward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 2U);
CHECK_EQ(req.size(), 2U);
using namespace mshadow;
Stream<xpu>* s = ctx.get_stream<xpu>();
if (req[1] != kNullOp && req[1] != kAddTo) {
Fill(s, outputs[1], req[1], 0); // Second input not relavant to gradients.
}
if (req[0] == kNullOp) return;
const TBlob& ograd = inputs[0];
const TBlob& igrad = outputs[0];
const SliceLikeParam& param = nnvm::get<SliceLikeParam>(attrs.parsed);
if (req[0] == kWriteTo) {
Fill(s, igrad, req[0], 0);
} else if (req[0] == kWriteInplace) {
LOG(FATAL) << "_slice_like_backward does not support kWriteInplace";
}
const mxnet::TShape& ishape = ograd.shape_;
const mxnet::TShape& from_shape = outputs[1].shape_;
mxnet::Tuple<dmlc::optional<index_t>> param_begin;
mxnet::Tuple<dmlc::optional<index_t>> param_end;
mxnet::Tuple<dmlc::optional<index_t>> param_step;
SliceLikeInferRanges(ishape, from_shape, param.axes, ¶m_begin, ¶m_end, ¶m_step);
MXNET_NDIM_SWITCH(ograd.ndim(), ndim, {
common::StaticArray<index_t, ndim> begin, end, step;
GetIndexRange(ograd.shape_, param_begin, param_end, param_step, &begin, &end, &step);
MSHADOW_TYPE_SWITCH(ograd.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], Req, {
int num_threads = ograd.shape_.FlatTo2D()[0];
if (std::is_same<xpu, gpu>::value) {
num_threads *= ograd.shape_.get<ndim>()[ndim - 1];
}
mxnet_op::Kernel<slice_assign<ndim, Req, xpu>, xpu>::Launch(s, num_threads,
igrad.dptr<DType>(), ograd.dptr<DType>(),
igrad.shape_.get<ndim>(), ograd.shape_.get<ndim>(), begin, step);
})
})
})
}
struct ClipParam : public dmlc::Parameter<ClipParam> {
real_t a_min, a_max;
DMLC_DECLARE_PARAMETER(ClipParam) {
DMLC_DECLARE_FIELD(a_min)
.describe("Minimum value");
DMLC_DECLARE_FIELD(a_max)
.describe("Maximum value");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream a_min_s, a_max_s;
a_min_s << a_min;
a_max_s << a_max;
(*dict)["a_min"] = a_min_s.str();
(*dict)["a_max"] = a_max_s.str();
}
};
struct clip {
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* datas,
const float a_min, const float a_max) {
DType data = datas[i];
if (data > a_max) {
out[i] = a_max;
} else if (data < a_min) {
out[i] = a_min;
} else {
out[i] = data;
}
}
};
struct clip_grad {
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* grad, const DType* datas,
const float a_min, const float a_max) {
DType data = datas[i];
if (data > a_max) {
out[i] = 0;
} else if (data < a_min) {
out[i] = 0;
} else {
out[i] = grad[i];
}
}
};
template<typename xpu>
void Clip(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;
const ClipParam& param = nnvm::get<ClipParam>(attrs.parsed);
CHECK_EQ(inputs[0].type_flag_, outputs[0].type_flag_);
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
mxnet_op::Kernel<mxnet::op::clip, xpu>::Launch(s, outputs[0].Size(), outputs[0].dptr<DType>(),
inputs[0].dptr<DType>(),
param.a_min, param.a_max);
});
}
template<typename xpu>
void ClipEx(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<NDArray>& inputs,
const std::vector<OpReqType>& req,
const std::vector<NDArray>& outputs) {
CHECK_EQ(inputs[0].dtype(), outputs[0].dtype());
CHECK_EQ(inputs[0].storage_type(), outputs[0].storage_type());
CHECK_NE(inputs[0].storage_type(), kDefaultStorage);
UnaryOp::MapToFCompute<xpu>(attrs, ctx, inputs, req, outputs, Clip<xpu>);
}
template<typename xpu>
void ClipGrad_(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 mxnet_op;
const ClipParam& param = nnvm::get<ClipParam>(attrs.parsed);
CHECK_EQ(inputs[0].type_flag_, outputs[0].type_flag_);
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
Kernel<clip_grad, xpu>::Launch(s, outputs[0].Size(), outputs[0].dptr<DType>(),
inputs[0].dptr<DType>(), inputs[1].dptr<DType>(), param.a_min, param.a_max);
});
}
/*!
* \brief The parameters of the repeat operator include
* the number of repeating time and axis (optional).
* The parameters will be later used to deduce the
* output ndarray shape in bool RepeatShape() function.
*/
struct RepeatParam : public dmlc::Parameter<RepeatParam> {
int repeats = 1;
dmlc::optional<int> axis;
DMLC_DECLARE_PARAMETER(RepeatParam) {
DMLC_DECLARE_FIELD(repeats)
.describe("The number of repetitions for each element.");
DMLC_DECLARE_FIELD(axis)
.set_default(dmlc::optional<int>())
.describe("The axis along which to repeat values."
" The negative numbers are interpreted counting from the backward."
" By default, use the flattened input array,"
" and return a flat output array.");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream repeats_s, axis_s;
repeats_s << repeats;
axis_s << axis;
(*dict)["repeats"] = repeats_s.str();
(*dict)["axis"] = axis_s.str();
}
};
/*!
* \brief Helper function for getting user input params for the operator repeat.
* Sanity check the user input values.
*/
inline void GetRepeatParams(const RepeatParam& param, const mxnet::TShape& ishape,
int* repeats, dmlc::optional<int>* axisOpt) {
*repeats = param.repeats;
CHECK_GE(*repeats, 0) << "repeats cannot be a negative number";
*axisOpt = param.axis;
if (static_cast<bool>(*axisOpt)) {
int ndims = ishape.ndim();
int axis = axisOpt->value();
if (axis < 0) {
axis += ndims;
}
CHECK(axis >= 0 && axis < ndims) << "axis = " << axisOpt->value() << " out of bounds";
}
}
inline bool RepeatOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const RepeatParam& param = nnvm::get<RepeatParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
const mxnet::TShape& ishape = (*in_attrs)[0];
if (!mxnet::ndim_is_known(ishape)) {
return false;
}
int repeats = 0;
dmlc::optional<int> axisOpt;
GetRepeatParams(param, ishape, &repeats, &axisOpt);
// If 0 repeats, return an empty 1-dim, 0-size array
if (0 == repeats) {
SHAPE_ASSIGN_CHECK(*out_attrs, 0, mxnet::TShape(1, 0));
return true;
}
// If repeats > 0, multiply the size of the corresponding axis by repeats
if (static_cast<bool>(axisOpt)) {
int ndims = ishape.ndim();
int axis = axisOpt.value();
if (axis < 0) {
axis += ndims;
}
mxnet::TShape shape(ishape.ndim(), -1);
for (int i = 0; i < ishape.ndim(); ++i) {
if (i == axis) {
shape[i] = repeats * ishape[i];
} else {
shape[i] = ishape[i];
}
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, shape);
} else { // If axis is not input by user, return a flat 1D array of size = in.size*repeats
mxnet::TShape shape(1, ishape.Size() * repeats);
SHAPE_ASSIGN_CHECK(*out_attrs, 0, shape);
}
return shape_is_known(out_attrs->at(0));
}
inline bool RepeatOpType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
if ((*in_attrs)[0] != -1) {
TYPE_ASSIGN_CHECK(*out_attrs, 0, (*in_attrs)[0]);
} else if ((*out_attrs)[0] != -1) {
TYPE_ASSIGN_CHECK(*in_attrs, 0, (*out_attrs)[0]);
}
return true;
}
/*!
* \brief Reshape the input and output tensors for
* using broadcast_to to achieve the funcitonality
* of operator repeat.
* \return a pair of mxnet::TShape's, first is the reshaped
* input shape, second is the reshaped output shape.
*/
inline std::pair<mxnet::TShape, mxnet::TShape> ReshapeInputOutputForRepeatOp(
const mxnet::TShape& ishape,
const dmlc::optional<int>& axisOpt,
const int repeats) {
if (static_cast<bool>(axisOpt)) {
int axis = axisOpt.value();
int ndim = ishape.ndim();
if (axis < 0) {
axis += ndim;
}
CHECK(axis >= 0 && axis < ishape.ndim()) << "Invalid input of axis";
// reshape the input tensor by adding a dim at the (axis+1)-th dim
mxnet::TShape rshape(ishape.ndim()+1, 1);
// the shape we want to broadcast to
mxnet::TShape bshape(rshape.ndim(), 1);
int i = 0;
while (i <= axis) {
rshape[i] = bshape[i] = ishape[i];
++i;
}
rshape[i] = 1;
bshape[i] = repeats;
while (i < ishape.ndim()) {
rshape[i+1] = ishape[i];
bshape[i+1] = ishape[i];
++i;
}
return std::make_pair(rshape, bshape);
} else {
// axis is not input by user
// reshape the tensor into shape (ishape.Size(), 1)
// then add one dim at axis = 1 and broadcast to
// shape (ishape.Size(), repeats)
mxnet::TShape rshape(2, 1);
rshape[0] = ishape.Size();
rshape[1] = 1;
mxnet::TShape bshape(2, 1);
bshape[0] = rshape[0];
bshape[1] = repeats;
return std::make_pair(rshape, bshape);
}
}
template<typename xpu>
void RepeatOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
const TBlob& iTBlob = inputs[0];
const mxnet::TShape& ishape = iTBlob.shape_;
if (!shape_is_known(ishape)) return;
int repeats = 0;
dmlc::optional<int> axisOpt;
const RepeatParam& param = nnvm::get<RepeatParam>(attrs.parsed);
GetRepeatParams(param, ishape, &repeats, &axisOpt);
if (0 == repeats) return;
std::pair<mxnet::TShape, mxnet::TShape> rshapes = \
ReshapeInputOutputForRepeatOp(ishape, axisOpt, repeats);
// reshaped input tblob
TBlob iblob(inputs[0].dptr_, rshapes.first, inputs[0].dev_mask(),
inputs[0].type_flag_, inputs[0].dev_id());
std::vector<TBlob> newInputs = {iblob};
// reshaped output tblob
TBlob oblob(outputs[0].dptr_, rshapes.second, outputs[0].dev_mask(),
outputs[0].type_flag_, outputs[0].dev_id());
std::vector<TBlob> newOutputs = {oblob};
BroadcastCompute<xpu>(attrs, ctx, newInputs, req, newOutputs);
}
/*!
* \brief Compute the gradient of the loss function
* with respect to the input of the operator.
* Backpropagation is employed to implement the
* chain rule.
* \param inputs the gradient of the loss function
* with respect to the outputs of the operator
* \param outputs the gradient of the loss function
* with respect to the inputs of the operator
*/
template<typename xpu>
void RepeatOpBackward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
const mxnet::TShape& oshape = outputs[0].shape_;
if (!shape_is_known(oshape)) return;
int repeats = 0;
dmlc::optional<int> axisOpt;
const RepeatParam& param = nnvm::get<RepeatParam>(attrs.parsed);
GetRepeatParams(param, oshape, &repeats, &axisOpt);
if (0 == repeats) return;
std::pair<mxnet::TShape, mxnet::TShape> rshapes =
ReshapeInputOutputForRepeatOp(oshape, axisOpt, repeats);
// reshaped output grad tblob
TBlob oblob(outputs[0].dptr_, rshapes.first, outputs[0].dev_mask(),
outputs[0].type_flag_, outputs[0].dev_id());
std::vector<TBlob> newOutputs = {oblob};
// reshaped input grad tblob
TBlob iblob(inputs[0].dptr_, rshapes.second, inputs[0].dev_mask(),
inputs[0].type_flag_, inputs[0].dev_id());
std::vector<TBlob> newInputs = {iblob};
#if !defined(__CUDACC__)
ReduceAxesComputeImpl<xpu, mshadow::red::sum, false, false>(
ctx, newInputs, req, newOutputs, rshapes.first);
#else
ReduceAxesRTCComputeImpl(ctx, newInputs, req, newOutputs, rshapes.first,
"red::sum{}", nullptr, false);
#endif
}
struct TileParam : public dmlc::Parameter<TileParam> {
mxnet::Tuple<int> reps;
DMLC_DECLARE_PARAMETER(TileParam) {
DMLC_DECLARE_FIELD(reps)
.describe("The number of times for repeating the tensor a. Each dim size of reps"
" must be a positive integer."
" If reps has length d, the result will have dimension of max(d, a.ndim);"
" If a.ndim < d, a is promoted to be d-dimensional by prepending new axes."
" If a.ndim > d, reps is promoted to a.ndim by pre-pending 1's to it.");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream reps_s;
reps_s << reps;
(*dict)["reps"] = reps_s.str();
}
};
inline bool TileOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
const TileParam& param = nnvm::get<TileParam>(attrs.parsed);
const mxnet::TShape& ishape = (*in_attrs)[0];
if (!shape_is_known(ishape)) {
return false;
}
const mxnet::Tuple<int>& reps = param.reps;
// If reps is empty, return a identical input array
if (reps.ndim() == 0) {
SHAPE_ASSIGN_CHECK(*out_attrs, 0, ishape);
return true;
}
mxnet::TShape oshape(std::max(ishape.ndim(), reps.ndim()), -1);
int i1 = ishape.ndim() - 1;
int i2 = reps.ndim() - 1;
for (int i = oshape.ndim() - 1; i >= 0; --i) {
if (i1 >= 0 && i2 >= 0) {
oshape[i] = ishape[i1--] * reps[i2--];
} else if (i1 >= 0) {
oshape[i] = ishape[i1--];
} else if (i2 >= 0) {
oshape[i] = reps[i2--];
}
}
// If reps contains 0s, oshape is a zero-size shape.
// Need to distinguish between np_shape mode and legacy mode.
if (!Imperative::Get()->is_np_shape()) {
common::ConvertToNumpyShape(&oshape);
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape);
return shape_is_known(oshape);
}
inline bool TileOpType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
if ((*in_attrs)[0] != -1) {
TYPE_ASSIGN_CHECK(*out_attrs, 0, (*in_attrs)[0]);
} else if ((*out_attrs)[0] != -1) {
TYPE_ASSIGN_CHECK(*in_attrs, 0, (*out_attrs)[0]);
}
return true;
}
/*!
* \brief Reshape the input and output tensors for
* using broadcast_to to achieve the functionality
* of operator tile.
* \return a pair of mxnet::TShape's, first is the reshaped
* input shape, second is the reshaped output shape.
*/
inline std::pair<mxnet::TShape, mxnet::TShape> ReshapeInputOutputForTileOp(
const mxnet::TShape& ishape,
const mxnet::Tuple<int>& reps) {
if (reps.ndim() == 0) {
return std::make_pair(ishape, ishape);
}
// The shape we want to broadcast to
mxnet::TShape bshape(std::max(ishape.ndim(), reps.ndim()) * 2, 1);
// The shape of the input tensor after adding new axes before each dim
mxnet::TShape rshape(bshape.ndim(), 1);
int i1 = ishape.ndim() - 1;
int i2 = reps.ndim() - 1;
for (int i = bshape.ndim() - 1; i >= 0; --i) {
if (0 == (i & 1)) {
bshape[i] = (i2 >= 0? reps[i2--] : 1);
rshape[i] = 1;
} else {
rshape[i] = bshape[i] = (i1 >= 0? ishape[i1--] : 1);
}
}
return std::make_pair(rshape, bshape);
}
/*!
* \brief Implementation of tiling the input tensor a based
* on the user-input shape, reps.
* If a.ndim < reps.ndim, new axes are pre-pended to a. For example,
* the input tensor has shape (3,), and the reps is (2, 4); the input
* tensor would be reshaped to (1, 3).
* If a.ndim > reps.ndim, pre-pending 1's to reps. For example,
* the input tensor has shape (2, 3, 4, 5), and reps is (2, 2);
* the reps would be changed to (1, 1, 2, 2).
* Suppose we have a.ndim = reps.ndim now. To achieve tiling,
* we utilize the operator broadcast_to. For example, for a tensor
* of shape (2, 3, 4, 5) and reps (2, 8, 9, 3), we first reshape
* the tensor to the shape (1, 2, 1, 3, 1, 4, 1, 5) by adding
* one axis before each dimension. Then, we want to broadcast
* the new tensor to shape (2, 2, 8, 3, 9, 4, 3, 5). The final
* output tensor would have shape (2*2, 8*3, 9*4, 3*5).
*/
template<typename xpu>
void TileOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
if (inputs[0].Size() == 0) return;
const mxnet::TShape& ishape = inputs[0].shape_;
const mxnet::Tuple<int>& reps = nnvm::get<TileParam>(attrs.parsed).reps;
// If any one of the number in reps is zero, return immediately
for (int i = 0; i < reps.ndim(); ++i) {
if (0 == reps[i]) return;
}
std::pair<mxnet::TShape, mxnet::TShape> rshapes = ReshapeInputOutputForTileOp(ishape, reps);
// reshaped input tblob
TBlob iblob(inputs[0].dptr_, rshapes.first, inputs[0].dev_mask(),
inputs[0].type_flag_, inputs[0].dev_id());
std::vector<TBlob> newInputs = {iblob};
// reshaped output tblob
TBlob oblob(outputs[0].dptr_, rshapes.second, outputs[0].dev_mask(),
outputs[0].type_flag_, outputs[0].dev_id());
std::vector<TBlob> newOutputs = {oblob};
BroadcastCompute<xpu>(attrs, ctx, newInputs, req, newOutputs);
}
/*!
* \brief Compute the gradient of the loss function
* with respect to the input of the operator.
* Backpropagation is employed to implement the
* chain rule.
* \param inputs the gradient of the loss function
* with respect to the outputs of the operator
* \param outputs the gradient of the loss function
* with respect to the inputs of the operator
*/
template<typename xpu>
void TileOpBackward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
if (inputs[0].Size() == 0) return;
const mxnet::TShape& oshape = outputs[0].shape_;
const mxnet::Tuple<int>& reps = nnvm::get<TileParam>(attrs.parsed).reps;
// If any one of the number in reps is zero, return immediately
for (int i = 0; i < reps.ndim(); ++i) {
if (0 == reps[i]) return;
}
std::pair<mxnet::TShape, mxnet::TShape> rshapes = ReshapeInputOutputForTileOp(oshape, reps);
// reshaped output grad tblob
TBlob oblob(outputs[0].dptr_, rshapes.first, outputs[0].dev_mask(),
outputs[0].type_flag_, outputs[0].dev_id());
std::vector<TBlob> newOutputs = {oblob};
// reshaped input grad tblob
TBlob iblob(inputs[0].dptr_, rshapes.second, inputs[0].dev_mask(),
inputs[0].type_flag_, inputs[0].dev_id());
std::vector<TBlob> newInputs = {iblob};
#if !defined(__CUDACC__)
ReduceAxesComputeImpl<xpu, mshadow::red::sum, false, false>(
ctx, newInputs, req, newOutputs, rshapes.first);
#else
ReduceAxesRTCComputeImpl(ctx, newInputs, req, newOutputs, rshapes.first,
"red::sum{}", nullptr, false);
#endif
}
struct ReverseParam : public dmlc::Parameter<ReverseParam> {
mxnet::Tuple<int> axis;
DMLC_DECLARE_PARAMETER(ReverseParam) {
DMLC_DECLARE_FIELD(axis)
.describe("The axis which to reverse elements.");
}
};
#define REVERSE_MAX_DIM 10U
struct reverse {
MSHADOW_XINLINE static index_t ReverseIndex(index_t idx,
index_t nreversedim,
const index_t * stride_,
const index_t * trailing_) {
index_t outputIndex = idx;
for (index_t i = 0; i < nreversedim; ++i) {
const index_t low = outputIndex % trailing_[i];
index_t high = outputIndex / trailing_[i];
const index_t x = high%stride_[i];
high /= stride_[i];
outputIndex = (high*stride_[i] + stride_[i] - 1 - x)*trailing_[i] + low;
}
return outputIndex;
}
#ifdef __CUDACC__
template<typename DType>
__device__ static void Map(index_t index, index_t nreversedim, const DType *src, DType *dst,
const index_t * stride_,
const index_t * trailing_) {
__shared__ index_t stride_share[REVERSE_MAX_DIM];
__shared__ index_t trailing_share[REVERSE_MAX_DIM];
if (threadIdx.x < REVERSE_MAX_DIM) {
stride_share[threadIdx.x] = stride_[threadIdx.x];
trailing_share[threadIdx.x] = trailing_[threadIdx.x];
}
__syncthreads();
index_t new_idx = ReverseIndex(index, nreversedim, stride_share, trailing_share);
dst[new_idx] = src[index];
}
#else
template<typename DType>
MSHADOW_XINLINE static void Map(index_t index, index_t nreversedim, const DType *src, DType *dst,
const index_t * stride_,
const index_t * trailing_) {
index_t new_idx = ReverseIndex(index, nreversedim, stride_, trailing_);
dst[new_idx] = src[index];
}
#endif
};
template<typename xpu>
void ReverseOpForward(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 mxnet_op;
const ReverseParam& param = nnvm::get<ReverseParam>(attrs.parsed);
CHECK_EQ(inputs[0].type_flag_, outputs[0].type_flag_);
CHECK_LT(param.axis.ndim(), REVERSE_MAX_DIM);
Stream<xpu> *s = ctx.get_stream<xpu>();
const mxnet::TShape& ishape = inputs[0].shape_;
std::vector<index_t> stride_(param.axis.ndim());
std::vector<index_t> trailing_(param.axis.ndim());
index_t reverse_index = 0;
for (int axis : param.axis) {
CHECK_LT(axis, ishape.ndim());
stride_[reverse_index] = ishape[axis];
trailing_[reverse_index] = 1;
for (int i2 = axis + 1; i2 < ishape.ndim(); ++i2) {
trailing_[reverse_index] *= ishape[i2];
}
reverse_index++;
}
#ifdef __CUDACC__
mshadow::Tensor<xpu, 1, uint8_t> workspace =
ctx.requested[0].get_space_typed<xpu, 1, uint8_t>(
mshadow::Shape1(reverse_index * sizeof(index_t) * 2), s);
auto stride_workspace = workspace.dptr_;
auto trailing_workspace = workspace.dptr_ + reverse_index * sizeof(index_t);
cudaMemcpyAsync(stride_workspace, thrust::raw_pointer_cast(stride_.data()),
stride_.size() * sizeof(index_t),
cudaMemcpyHostToDevice, mshadow::Stream<gpu>::GetStream(s));
cudaMemcpyAsync(trailing_workspace, thrust::raw_pointer_cast(trailing_.data()),
trailing_.size() * sizeof(index_t),
cudaMemcpyHostToDevice, mshadow::Stream<gpu>::GetStream(s));
#endif
#ifdef __CUDACC__
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
Kernel<reverse, xpu>::Launch(s, inputs[0].Size(), reverse_index,
inputs[0].dptr<DType>(), outputs[0].dptr<DType>(),
reinterpret_cast<index_t*>(stride_workspace), reinterpret_cast<index_t*>(trailing_workspace));
});
#else
MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, {
Kernel<reverse, xpu>::Launch(s, inputs[0].Size(), reverse_index,
inputs[0].dptr<DType>(), outputs[0].dptr<DType>(),
stride_.data(), trailing_.data());
});
#endif
}
struct StackParam : public dmlc::Parameter<StackParam> {
int axis;
int num_args;
DMLC_DECLARE_PARAMETER(StackParam) {
DMLC_DECLARE_FIELD(axis)
.set_default(0)
.describe("The axis in the result array along which the input arrays are stacked.");
DMLC_DECLARE_FIELD(num_args).set_lower_bound(1)
.describe("Number of inputs to be stacked.");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream axis_s, num_args_s;
axis_s << axis;
num_args_s << num_args;
(*dict)["axis"] = axis_s.str();
(*dict)["num_args"] = num_args_s.str();
}
};
inline bool StackOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const StackParam& param = dmlc::get<StackParam>(attrs.parsed);
mxnet::TShape dshape;
for (const mxnet::TShape& i : (*in_attrs)) {
shape_assign(&dshape, i);
}
if (!shape_is_known(dshape)) return false;
mxnet::TShape oshape(dshape.ndim() + 1, -1);
int axis = CheckAxis(param.axis, oshape.ndim());
for (int i = 0; i < axis; ++i) {
oshape[i] = dshape[i];
}
oshape[axis] = param.num_args;
for (index_t i = axis + 1; i < oshape.ndim(); ++i) {
oshape[i] = dshape[i-1];
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape);
return shape_is_known(oshape);
}
template<typename xpu>
void StackOpForward(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;
const StackParam& param = dmlc::get<StackParam>(attrs.parsed);
int axis = CheckAxis(param.axis, outputs[0].ndim());
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH_WITH_BOOL(outputs[0].type_flag_, DType, {
std::vector<Tensor<xpu, 3, DType> > data(inputs.size());
Tensor<xpu, 3, DType> out;
size_t leading = 1, trailing = 1;
for (int i = 0; i < axis; ++i) {
leading *= outputs[0].shape_[i];
}
for (int i = axis + 1; i < outputs[0].ndim(); ++i) {
trailing *= outputs[0].shape_[i];
}
size_t mid = outputs[0].shape_[axis];
Shape<3> oshape = Shape3(leading, mid, trailing);
out = outputs[0].get_with_shape<xpu, 3, DType>(oshape, s);
for (size_t i = 0; i < inputs.size(); ++i) {
Shape<3> dshape = Shape3(leading, 1, trailing);
data[i] = inputs[i].get_with_shape<xpu, 3, DType>(dshape, s);
}
Concatenate(data, &out, 1, req[0]);
})
}
template<typename xpu>
void StackOpBackward(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;
const StackParam& param = dmlc::get<StackParam>(attrs.parsed);
int axis = CheckAxis(param.axis, inputs[0].ndim());
Stream<xpu> *s = ctx.get_stream<xpu>();
MSHADOW_TYPE_SWITCH_WITH_BOOL(inputs[0].type_flag_, DType, {
std::vector<Tensor<xpu, 3, DType> > grad_in(outputs.size());
Tensor<xpu, 3, DType> grad;
size_t leading = 1, trailing = 1;
for (int i = 0; i < axis; ++i) {
leading *= inputs[0].shape_[i];
}
for (int i = axis + 1; i < inputs[0].ndim(); ++i) {
trailing *= inputs[0].shape_[i];
}
size_t mid = inputs[0].shape_[axis];
Shape<3> oshape = Shape3(leading, mid, trailing);
grad = inputs[0].get_with_shape<xpu, 3, DType>(oshape, s);
for (size_t i = 0; i < outputs.size(); ++i) {
Shape<3> dshape = Shape3(leading, 1, trailing);
grad_in[i] = outputs[i].get_with_shape<xpu, 3, DType>(dshape, s);
}
Split(grad, &grad_in, 1, req);
})
}
struct SqueezeParam : public dmlc::Parameter<SqueezeParam> {
dmlc::optional<mxnet::Tuple<int>> axis;
DMLC_DECLARE_PARAMETER(SqueezeParam) {
DMLC_DECLARE_FIELD(axis)
.set_default(dmlc::optional<mxnet::Tuple<int>>())
.describe("Selects a subset of the single-dimensional entries in the shape."
" If an axis is selected with shape entry greater than one, an error is raised.");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream axis_s;
axis_s << axis;
(*dict)["axis"] = axis_s.str();
}
};
// Given a shape that may have dim size equal to 0,
// move all the zeros to the last of the shape array
// and keep the relative order of the non-zero values.
// Returns the new shape size after moving all zeros to the end.
inline size_t SqueezeShapeHelper(mxnet::TShape* shape) {
CHECK(shape != nullptr);
size_t count = 0;
for (int i = 0; i < shape->ndim(); ++i) {
if ((*shape)[i] == -1) {
++count;
} else {
std::swap((*shape)[i], (*shape)[i-count]);
}
}
return shape->ndim() - count;
}
inline bool SqueezeShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector *in_attrs,
mxnet::ShapeVector *out_attrs) {
const SqueezeParam& param = nnvm::get<SqueezeParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U) << "Input: [data]";
CHECK_EQ(out_attrs->size(), 1U);
const mxnet::TShape& dshape = in_attrs->at(0);
const int dndim = dshape.ndim();
if (!shape_is_known(dshape)) return false;
mxnet::TShape oshape = dshape;
if (param.axis.has_value()) {
// preprocess axis
mxnet::Tuple<int> axes = param.axis.value();
for (int i = 0; i < axes.ndim(); ++i) {
if (axes[i] < 0) {
axes[i] += dndim;
CHECK_GE(axes[i], 0)
<< "axis " << axes[i] - dndim << " is out of bounds for array of dimension " << dndim;
}
CHECK_LT(axes[i], dndim)
<< "axis " << axes[i] << " is out of bounds for array of dimension " << dndim;
CHECK_EQ(dshape[axes[i]], 1)
<< "cannot select an axis to squeeze out which has size="
<< dshape[axes[i]] << " not equal to one";
CHECK_NE(oshape[axes[i]], -1) << "duplicate value in axis";
oshape[axes[i]] = -1;
}
} else {
for (int i = 0; i < oshape.ndim(); ++i) {
if (oshape[i] == 1) oshape[i] = -1;
}
}
size_t oshape_size = SqueezeShapeHelper(&oshape);
if (oshape_size == 0) { // corner case when dshape is (1, 1, 1, 1)
oshape[0] = 1;
oshape_size = 1;
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, mxnet::TShape(oshape.data(), oshape.data()+oshape_size));
return true;
}
struct DepthToSpaceParam : public dmlc::Parameter<DepthToSpaceParam> {
int block_size;
DMLC_DECLARE_PARAMETER(DepthToSpaceParam) {
DMLC_DECLARE_FIELD(block_size)
.describe("Blocks of [block_size. block_size] are moved");
}
};
inline bool DepthToSpaceOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs) {
const DepthToSpaceParam& param = nnvm::get<DepthToSpaceParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
CHECK_EQ(in_attrs->at(0).ndim(), 4) << "Operation Depth To Space requires exactly 4D tensor";
mxnet::TShape expected_out(4, -1);
mxnet::TShape& in_shape = in_attrs->at(0);
if (!mxnet::ndim_is_known(in_shape)) {
return false;
}
int block = param.block_size;
CHECK_NE(block, 0) << "block_size must be a positive integer value";
CHECK_NE(in_shape[1], 0) << "Depth dimension:1 cannot be 0";
CHECK_EQ(in_shape[1] % (block * block), 0)
<< "Cannot perform Depth To Space operation on the specified tensor."
" Dimension:1(depth dimension) should be a multiple of 'block^2'";
CHECK_NE(in_shape[0], 0)
<< "Operation requires a 4D tensor. Size of dimension:0 cannot be 0";
CHECK_NE(in_shape[2], 0)
<< "Operation requires a 4D tensor. Size of dimension:2 cannot be 0";
CHECK_NE(in_shape[3], 0)
<< "Operation requires a 4D tensor. Size of dimension:3 cannot be 0";
expected_out[0] = in_shape[0];
expected_out[1] = in_shape[1] / (block * block);
int i = 2;
while (i < expected_out.ndim()) {
expected_out[i] = in_shape[i] * block;
++i;
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, expected_out);
return shape_is_known(expected_out);
}
inline bool DepthToSpaceOpType(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);
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;
}
/*!
* \brief This function updates the value of input index from where the data element
* needs to be fetched and written out to the ith location in output tensor
* \param index_position index within offset array to get offset of given dimension
* \param dim_size size of current dimension
* \param idx output tensor index
* \param inp_index index within input tensor from where value is retrieved
* \param offset_arr array containing the linear offset of input tensor
*/
MSHADOW_XINLINE void update_index(index_t index_position, index_t dim_size, index_t *idx,
index_t *inp_index, const index_t* offset_arr) {
index_t next_idx_val = *idx / dim_size;
*inp_index += (*idx - next_idx_val * dim_size) * offset_arr[index_position];
*idx = next_idx_val;
}
/*!
* \brief This function performs the tensor transpose (0, 1, 2, 3, 4, 5) ->
* (0, 3, 4, 1, 5, 2) by computing linear index within input tensor to be mapped
* to the ith index of output tensor
* \param i tensor index
* \param out_data output tensor
* \param in_data input tensor
* \param block size of chunks to be moved out of depth dimension
* \param size array containing the size of each dimension of input tensor
* \param offset_arr array containing the linear offset of input tensor
*/
template<int req>
struct depth_to_space_forward {
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out_data, const DType* in_data,
const int block, const index_t* size, const index_t* offset_arr) {
index_t inp_index = 0, idx = i, dim_size;
dim_size = block;
update_index(2, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[3];
update_index(5, dim_size, &idx, &inp_index, offset_arr);
dim_size = block;
update_index(1, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[2];
update_index(4, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[1] / (block * block);
update_index(3, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[0];
update_index(0, dim_size, &idx, &inp_index, offset_arr);
KERNEL_ASSIGN(out_data[i], req, in_data[inp_index]);
}
};
/*!
* \brief This function calculates the linear offset for each dimension of
* input tensor and stores them in an array, which is later used in
* performing depth_to_space operation
* \param i global thread id
* \param offset_arr array to be populated with offset values
* \param size array to be populated with size of each dimension of input tensor
* \param block size of chunks to be moved out of depth dimension
* \param size0 size of Dim 0 of input tensor
* \param size1 size of Dim 1 of input tensor
* \param size2 size of Dim 2 of input tensor
* \param size3 size of Dim 3 of input tensor
*/
template<int req>
struct compute_offset_for_depth_to_space {
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* offset_arr, DType* size, const int block,
const index_t size0, const index_t size1, const index_t size2,
const index_t size3) {
size[0] = size0;
size[1] = size1;
size[2] = size2;
size[3] = size3;
offset_arr[5] = 1;
offset_arr[4] = offset_arr[5] * size[3];
offset_arr[3] = offset_arr[4] * size[2];
offset_arr[2] = offset_arr[3] * size[1] / (block * block);
offset_arr[1] = offset_arr[2] * block;
offset_arr[0] = offset_arr[1] * block;
}
};
template<typename xpu>
void DepthToSpaceOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob& in_data = inputs[0];
const TBlob& out_data = outputs[0];
const DepthToSpaceParam& param = nnvm::get<DepthToSpaceParam>(attrs.parsed);
using namespace mxnet_op;
int block = param.block_size;
mshadow::Tensor<xpu, 1, char> workspace =
ctx.requested[0].get_space_typed<xpu, 1, char>(mshadow::Shape1(sizeof(index_t) * 10), s);
char* workspace_curr_ptr = workspace.dptr_;
index_t* offset_arr = reinterpret_cast<index_t*>(workspace_curr_ptr);
index_t* size = reinterpret_cast<index_t*>(workspace_curr_ptr + sizeof(index_t) * 6);
MSHADOW_TYPE_SWITCH(out_data.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, {
Kernel<compute_offset_for_depth_to_space<req_type>, xpu>::Launch(
s, 1, offset_arr, size, block, in_data.shape_[0], in_data.shape_[1],
in_data.shape_[2], in_data.shape_[3]);
Kernel<depth_to_space_forward<req_type>, xpu>::Launch(
s, out_data.Size(), out_data.dptr<DType>(), in_data.dptr<DType>(),
block, size, offset_arr);
});
});
}
inline bool SpaceToDepthOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs) {
const DepthToSpaceParam& param = nnvm::get<DepthToSpaceParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
CHECK_EQ(out_attrs->size(), 1U);
CHECK_EQ(in_attrs->at(0).ndim(), 4) << "Operation Space To Depth requires exactly 4D tensor";
mxnet::TShape expected_out(in_attrs->at(0).ndim(), -1);
mxnet::TShape& in_shape = in_attrs->at(0);
if (!mxnet::ndim_is_known(in_shape)) {
return false;
}
int block = param.block_size;
CHECK_NE(block, 0) << "block_size must be a positive integer value";
CHECK_NE(in_shape[0], 0)
<< "Operation requires a 4D tensor. Size of dimension:0 cannot be 0";
CHECK_NE(in_shape[1], 0) << "Depth dimension:1 cannot be 0";
CHECK_NE(in_shape[2], 0)
<< "Operation requires a 4D tensor. Size of dimension:2 cannot be 0";
CHECK_EQ(in_shape[2] % block, 0)
<< "Cannot perform Depth To Space operation on the specified tensor."
" Dimension:2(1st Space dimension) should be a multiple of 'block' ";
CHECK_NE(in_shape[3], 0)
<< "Operation requires a 4D tensor. Size of dimension:3 cannot be 0";
CHECK_EQ(in_shape[3] % block, 0)
<< "Cannot perform Depth To Space operation on the specified tensor."
" Dimension:3(2nd space dimension) should be a multiple of 'block' ";
expected_out[0] = in_shape[0];
expected_out[1] = in_shape[1] * block * block;
int i = 2;
while (i < expected_out.ndim()) {
expected_out[i] = in_shape[i] / block;
++i;
}
SHAPE_ASSIGN_CHECK(*out_attrs, 0, expected_out);
return shape_is_known(expected_out);
}
inline bool SpaceToDepthOpType(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);
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;
}
/*!
* \brief This function preforms the tensor transpose (0, 1, 2, 3, 4, 5) ->
* (0, 3, 5, 1, 2, 4) by computing linear index within input tensor to be mapped
* to the ith index of output tensor
* \param i tensor index
* \param out_data output tensor
* \param in_data input tensor
* \param block size of chunks to be moved out of depth dimension
* \param size array containing the size of each dimension of input tensor
* \param offset_arr array containing the linear offset of input tensor
*/
template<int req>
struct space_to_depth_forward {
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* out_data, const DType* in_data, const int block,
const index_t* size, const index_t* offset_arr) {
index_t inp_index = 0, idx = i, dim_size;
dim_size = size[3] / block;
update_index(4, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[2] / block;
update_index(2, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[1];
update_index(1, dim_size, &idx, &inp_index, offset_arr);
dim_size = block;
update_index(5, dim_size, &idx, &inp_index, offset_arr);
dim_size = block;
update_index(3, dim_size, &idx, &inp_index, offset_arr);
dim_size = size[0];
update_index(0, dim_size, &idx, &inp_index, offset_arr);
KERNEL_ASSIGN(out_data[i], req, in_data[inp_index]);
}
};
/*!
* \brief This function calculates the linear offset for each dimension of
* input tensor and stores them in an array, which is later used in
* performing space_to_depth operation
* \param i global thread id
* \param offset_arr array to be populated with offset values
* \param size array to be populated with size of each dimension of input tensor
* \param block size of chunks to be moved out of depth dimension
* \param size0 size of Dim 0 of input tensor
* \param size1 size of Dim 1 of input tensor
* \param size2 size of Dim 2 of input tensor
* \param size3 size of Dim 3 of input tensor
*/
template<int req>
struct compute_offset_for_space_to_depth {
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType* offset_arr, DType* size, const int block,
const index_t size0, const index_t size1,
const index_t size2, const index_t size3) {
size[0] = size0;
size[1] = size1;
size[2] = size2;
size[3] = size3;
offset_arr[5] = 1;
offset_arr[4] = offset_arr[5] * block;
offset_arr[3] = offset_arr[4] * size[3] / block;
offset_arr[2] = offset_arr[3] * block;
offset_arr[1] = offset_arr[2] * size[2] / block;
offset_arr[0] = offset_arr[1] * size[1];
}
};
template<typename xpu>
void SpaceToDepthOpForward(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), 1U);
CHECK_EQ(req.size(), 1U);
mshadow::Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob& in_data = inputs[0];
const TBlob& out_data = outputs[0];
const DepthToSpaceParam& param = nnvm::get<DepthToSpaceParam>(attrs.parsed);
using namespace mxnet_op;
int block = param.block_size;
mshadow::Tensor<xpu, 1, char> workspace =
ctx.requested[0].get_space_typed<xpu, 1, char>(mshadow::Shape1(sizeof(index_t) * 10), s);
char* workspace_curr_ptr = workspace.dptr_;
index_t* offset_arr = reinterpret_cast<index_t*>(workspace_curr_ptr);
index_t* size = reinterpret_cast<index_t*>(workspace_curr_ptr + sizeof(index_t) * 6);
MSHADOW_TYPE_SWITCH(out_data.type_flag_, DType, {
MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, {
Kernel<compute_offset_for_space_to_depth<req_type>, xpu>::Launch(
s, 1, offset_arr, size, block, in_data.shape_[0], in_data.shape_[1],
in_data.shape_[2], in_data.shape_[3]);
Kernel<space_to_depth_forward<req_type>, xpu>::Launch(
s, out_data.Size(), out_data.dptr<DType>(), in_data.dptr<DType>(),
block, size, offset_arr);
});
});
}
namespace split_enum {
enum SplitOpInputs {kData};
} // namespace split_enum
struct SplitParam : public dmlc::Parameter<SplitParam> {
mxnet::TShape indices;
int axis;
bool squeeze_axis;
int sections;
DMLC_DECLARE_PARAMETER(SplitParam) {
DMLC_DECLARE_FIELD(indices)
.describe("Indices of splits. The elements should denote the boundaries of at which split"
" is performed along the `axis`.");
DMLC_DECLARE_FIELD(axis).set_default(1)
.describe("Axis along which to split.");
DMLC_DECLARE_FIELD(squeeze_axis).set_default(0)
.describe("If true, Removes the axis with length 1 from the shapes of the output arrays."
" **Note** that setting `squeeze_axis` to ``true`` removes axis with length 1"
" only along the `axis` which it is split."
" Also `squeeze_axis` can be set to ``true``"
" only if ``input.shape[axis] == num_outputs``.");
DMLC_DECLARE_FIELD(sections).set_default(0)
.describe("Number of sections if equally splitted. Default to 0 which means split by indices.");
}
void SetAttrDict(std::unordered_map<std::string, std::string>* dict) {
std::ostringstream indices_s, axis_s, squeeze_axis_s, sections_s;
indices_s << indices;
axis_s << axis;
squeeze_axis_s << squeeze_axis;
sections_s << sections;
(*dict)["indices"] = indices_s.str();
(*dict)["axis"] = axis_s.str();
(*dict)["squeeze_axis"] = squeeze_axis_s.str();
(*dict)["sections"] = sections_s.str();
}
}; // struct SplitParam
inline mxnet::TShape GetSplitIndices(const mxnet::TShape& ishape, int axis, int sections) {
mxnet::TShape indices(sections+1, -1);
indices[0] = 0;
int64_t section_size_b = (int64_t) (ishape[axis] / sections);
int64_t section_size_a = section_size_b + 1;
int section_a = ishape[axis] % sections;
for (int i = 0; i < sections; ++i) {
if ( i < section_a ) {
indices[i+1] = section_size_a * (i + 1);
} else {
indices[i+1] = section_size_b + indices[i];
}
}
return indices;
}
inline bool SplitOpType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
CHECK_EQ(in_attrs->size(), 1U);
int dtype = (*in_attrs)[0];
CHECK_NE(dtype, -1) << "First input must have specified type";
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
out_attrs->clear();
int num_outputs = (param.sections > 0) ? param.sections : param.indices.ndim();
for (int i = 0; i < num_outputs; ++i) {
out_attrs->push_back(dtype);
}
return true;
}
inline bool SplitOpShapeImpl(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs,
const int real_axis) {
using namespace mshadow;
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
mxnet::TShape dshape = in_attrs->at(split_enum::kData);
mxnet::TShape ishape = in_attrs->at(split_enum::kData);
const mxnet::TShape indices =
(param.sections > 0) ? GetSplitIndices(ishape, real_axis, param.sections) : param.indices;
int num_outputs = (param.sections > 0) ? indices.ndim() - 1 : indices.ndim();
// Pre-compute squeezed output shape for future usage
mxnet::TShape squeezed_dshape = dshape;
for (int d = real_axis; d < squeezed_dshape.ndim() - 1; ++d) {
squeezed_dshape[d] = squeezed_dshape[d+1];
}
squeezed_dshape = mxnet::TShape(&squeezed_dshape[0], &squeezed_dshape[squeezed_dshape.ndim()-1]);
// Assign shape to every output
for (int i = 0; i < num_outputs; ++i) {
index_t start = indices[i];
index_t end = (i < num_outputs - 1) ? indices[i + 1] : ishape[real_axis];
if (ishape[real_axis] == 0U) {
end = start;
} else {
CHECK(start <= end)
<< "start " << start << " is not less than end " << end << "for subarray " << i;
CHECK(end <= ishape[real_axis])
<< "end " << end << " is no less than the size of the axis " << ishape[real_axis];
}
dshape[real_axis] = (end - start);
if (param.squeeze_axis) {
CHECK_EQ(end - start, 1U) << "expected axis size of 1 but got " << end - start;
SHAPE_ASSIGN_CHECK(*out_attrs, i, squeezed_dshape);
} else {
SHAPE_ASSIGN_CHECK(*out_attrs, i, dshape);
}
}
mxnet::TShape back_calculate_dshape = ishape;
back_calculate_dshape[real_axis] = 0;
for (int d = 0; d < real_axis; ++d) {
back_calculate_dshape[d] = (*out_attrs)[0][d];
}
if (param.squeeze_axis) {
back_calculate_dshape[real_axis] = num_outputs;
} else {
for (int i = 0; i < num_outputs; ++i) {
back_calculate_dshape[real_axis] += (*out_attrs)[i][real_axis];
}
}
for (int d = real_axis + 1; d < ishape.ndim(); ++d) {
if (param.squeeze_axis) {
back_calculate_dshape[d] = (*out_attrs)[0][d - 1];
} else {
back_calculate_dshape[d] = (*out_attrs)[0][d];
}
}
SHAPE_ASSIGN_CHECK(*in_attrs, split_enum::kData, back_calculate_dshape);
return true;
}
inline bool SplitOpShape(const nnvm::NodeAttrs& attrs,
mxnet::ShapeVector* in_attrs,
mxnet::ShapeVector* out_attrs) {
using namespace mshadow;
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
CHECK_EQ(in_attrs->size(), 1U);
mxnet::TShape dshape = in_attrs->at(split_enum::kData);
if (!mxnet::ndim_is_known(dshape)) return false;
if (param.axis >= 0) {
CHECK_LT(param.axis, dshape.ndim());
} else {
CHECK_LT(param.axis + dshape.ndim(), dshape.ndim());
}
int real_axis = param.axis;
if (real_axis < 0) {
real_axis += dshape.ndim();
}
return SplitOpShapeImpl(attrs, in_attrs, out_attrs, real_axis);
}
struct SplitKernel {
/*!
* \brief Map function for forward split_v2 operator
* \param i global thread id
* \param in_data ptr to input buffer
* \param out_data ptr to ptr of outputs buffer
* \param indices ptr to indices buffer
* \param num_sections # of sections after split
* \param axis_size size of axis to be splitted on
* \param trailing_size step size within the data buffer of the axis to be splitted on
*/
template<typename DType>
static MSHADOW_XINLINE void Map(size_t i,
const DType *in_data, DType** out_data, const size_t* indices,
const size_t num_sections, const size_t axis_size,
const size_t trailing_size) {
size_t idx = i / trailing_size % axis_size;
size_t target = 0;
for (size_t section = 0;
section < num_sections && indices[section] <= idx;
target = section++) {}
DType* target_data = out_data[target];
const size_t mid_idx = idx - indices[target];
const size_t head_idx = i / (trailing_size * axis_size);
const size_t tail_idx = i % trailing_size;
const size_t section_size = indices[target + 1] - indices[target];
const size_t target_idx =
head_idx * trailing_size * section_size + mid_idx * trailing_size + tail_idx;
target_data[target_idx] = in_data[i];
}
};
struct ConcatenateKernel {
/*!
* \brief Map function for backward split_v2 operator
* \param i global thread id
* \param out_grad ptr to ptr of out grads buffer
* \param in_grad ptr to input grad buffer
* \param indices ptr to indices buffer
* \param num_sections # of sections after split
* \param axis_size size of axis to be splitted on
* \param trailing_size step size within the data buffer of the axis to be splitted on
*/
template<typename DType>
static MSHADOW_XINLINE void Map(size_t i,
DType** out_grad, DType* in_grad, const size_t* indices,
const size_t num_sections, const size_t axis_size,
const size_t trailing_size) {
size_t idx = i / trailing_size % axis_size;
size_t src = 0;
for (size_t section = 0;
section < num_sections && indices[section] <= idx;
src = section++) {}
DType* src_grad = out_grad[src];
const size_t mid_idx = idx - indices[src];
const size_t head_idx = i / (trailing_size * axis_size);
const size_t tail_idx = i % trailing_size;
const size_t section_size = indices[src + 1] - indices[src];
const size_t src_idx =
head_idx * trailing_size * section_size + mid_idx * trailing_size + tail_idx;
in_grad[i] = src_grad[src_idx];
}
};
template<typename xpu>
inline void SplitOpForwardImpl(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs,
const int real_axis) {
using namespace mshadow;
using namespace mshadow::expr;
using namespace mxnet_op;
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob& input_data = inputs[split_enum::kData];
size_t leading = 1, trailing = 1;
CHECK_LT(real_axis, input_data.ndim());
size_t mid = input_data.shape_[real_axis];
for (int i = 0; i < real_axis; ++i) {
leading *= input_data.shape_[i];
}
for (int i = real_axis + 1; i < input_data.ndim(); ++i) {
trailing *= input_data.shape_[i];
}
size_t workspace_size = 0;
const mxnet::TShape& ishape = input_data.shape_;
const mxnet::TShape split_pts =
(param.sections > 0) ? GetSplitIndices(ishape, real_axis, param.sections) : param.indices;
std::vector<size_t> indices;
for (const auto& section : split_pts) {
indices.push_back(section);
}
if (param.sections == 0) {
indices.push_back(ishape[real_axis]);
}
workspace_size += indices.size() * sizeof(size_t);
MSHADOW_TYPE_SWITCH(input_data.type_flag_, DType, {
std::vector<DType*> output_data;
for (const TBlob& data : outputs) {
output_data.push_back(data.dptr<DType>());
}
workspace_size += output_data.size() * sizeof(DType*);
Tensor<xpu, 1, char> workspace =
ctx.requested[0].get_space_typed<xpu, 1, char>(Shape1(workspace_size), s);
Tensor<cpu, 1, size_t> indices_cpu_tensor(indices.data(), Shape1(indices.size()));
Tensor<xpu, 1, size_t> indices_xpu_tensor(
reinterpret_cast<size_t*>(workspace.dptr_), Shape1(indices.size()));
Tensor<cpu, 1, DType*> ptrs_cpu_tensor(output_data.data(), Shape1(output_data.size()));
Tensor<xpu, 1, DType*> ptrs_xpu_tensor(
reinterpret_cast<DType**>(workspace.dptr_ + indices.size() * sizeof(size_t)),
Shape1(output_data.size()));
mshadow::Copy(indices_xpu_tensor, indices_cpu_tensor, s);
mshadow::Copy(ptrs_xpu_tensor, ptrs_cpu_tensor, s);
Kernel<SplitKernel, xpu>::Launch(
s, input_data.Size(), input_data.dptr<DType>(), ptrs_xpu_tensor.dptr_,
indices_xpu_tensor.dptr_, indices.size() - 1, mid, trailing);
});
}
template<typename xpu>
inline void SplitOpForward(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;
using namespace mxnet_op;
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(outputs.size(), (param.sections > 0) ? param.sections : param.indices.ndim());
const TBlob& input_data = inputs[split_enum::kData];
int real_axis = param.axis;
if (real_axis < 0) {
real_axis += input_data.ndim();
}
SplitOpForwardImpl<xpu>(attrs, ctx, inputs, req, outputs, real_axis);
}
template<typename xpu>
inline void SplitOpBackwardImpl(const nnvm::NodeAttrs& attrs,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs,
const int real_axis) {
using namespace mshadow;
using namespace mshadow::expr;
using namespace mxnet_op;
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
Stream<xpu> *s = ctx.get_stream<xpu>();
TBlob input_grad = outputs[split_enum::kData];
size_t leading = 1, trailing = 1;
CHECK_LT(real_axis, input_grad.ndim());
size_t mid = input_grad.shape_[real_axis];
for (int i = 0; i < real_axis; ++i) {
leading *= input_grad.shape_[i];
}
for (int i = real_axis + 1; i < input_grad.ndim(); ++i) {
trailing *= input_grad.shape_[i];
}
size_t workspace_size = 0;
const mxnet::TShape& ishape = input_grad.shape_;
const mxnet::TShape split_pts =
(param.sections > 0) ? GetSplitIndices(ishape, real_axis, param.sections) : param.indices;
std::vector<size_t> indices;
for (const auto& section : split_pts) {
indices.push_back(section);
}
if (param.sections == 0) {
indices.push_back(ishape[real_axis]);
}
workspace_size += indices.size() * sizeof(size_t);
MSHADOW_TYPE_SWITCH(input_grad.type_flag_, DType, {
std::vector<DType*> out_grads;
for (const TBlob& output_grad : inputs) {
out_grads.push_back(output_grad.dptr<DType>());
}
workspace_size += out_grads.size() * sizeof(DType*);
Tensor<xpu, 1, char> workspace =
ctx.requested[0].get_space_typed<xpu, 1, char>(Shape1(workspace_size), s);
Tensor<cpu, 1, size_t> indices_cpu_tensor(indices.data(), Shape1(indices.size()));
Tensor<xpu, 1, size_t> indices_xpu_tensor(
reinterpret_cast<size_t*>(workspace.dptr_), Shape1(indices.size()));
Tensor<cpu, 1, DType*> ptrs_cpu_tensor(out_grads.data(), Shape1(inputs.size()));
Tensor<xpu, 1, DType*> ptrs_xpu_tensor(
reinterpret_cast<DType**>(workspace.dptr_ + indices.size() * sizeof(size_t)),
Shape1(inputs.size()));
mshadow::Copy(indices_xpu_tensor, indices_cpu_tensor, s);
mshadow::Copy(ptrs_xpu_tensor, ptrs_cpu_tensor, s);
Kernel<ConcatenateKernel, xpu>::Launch(
s, input_grad.Size(), ptrs_xpu_tensor.dptr_, input_grad.dptr<DType>(),
indices_xpu_tensor.dptr_, indices.size() - 1, mid, trailing);
});
}
template<typename xpu>
inline void SplitOpBackward(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;
using namespace mxnet_op;
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
CHECK_EQ(inputs.size(), (param.sections > 0) ? param.sections : param.indices.ndim())
<< "out grad vector size mush match the output size";
CHECK_EQ(outputs.size(), 1U);
int real_axis = param.axis;
if (real_axis < 0) {
real_axis += outputs[split_enum::kData].ndim();
}
SplitOpBackwardImpl<xpu>(attrs, ctx, inputs, req, outputs, real_axis);
}
inline uint32_t SplitNumOutputs(const NodeAttrs& attrs) {
const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed);
return (param.sections > 0) ? param.sections : param.indices.ndim();
}
} // namespace op
} // namespace mxnet
namespace std {
template<>
struct hash<mxnet::op::TransposeParam> {
size_t operator()(const mxnet::op::TransposeParam& val) {
size_t ret = 0;
ret = dmlc::HashCombine(ret, val.axes);
return ret;
}
};
template<>
struct hash<mxnet::op::ReshapeParam> {
size_t operator()(const mxnet::op::ReshapeParam& val) {
size_t ret = 0;
ret = dmlc::HashCombine(ret, val.target_shape);
ret = dmlc::HashCombine(ret, val.keep_highest);
ret = dmlc::HashCombine(ret, val.shape);
ret = dmlc::HashCombine(ret, val.reverse);
return ret;
}
};
template<>
struct hash<mxnet::op::ExpandDimParam> {
size_t operator()(const mxnet::op::ExpandDimParam& val) {
size_t ret = 0;
ret = dmlc::HashCombine(ret, val.axis);
return ret;
}
};
} // namespace std
#endif // MXNET_OPERATOR_TENSOR_MATRIX_OP_INL_H_
|
tree-vect-stmts.c | /* Statement Analysis and Transformation for Vectorization
Copyright (C) 2003-2020 Free Software Foundation, Inc.
Contributed by Dorit Naishlos <dorit@il.ibm.com>
and Ira Rosen <irar@il.ibm.com>
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "backend.h"
#include "target.h"
#include "rtl.h"
#include "tree.h"
#include "gimple.h"
#include "ssa.h"
#include "optabs-tree.h"
#include "insn-config.h"
#include "recog.h" /* FIXME: for insn_data */
#include "cgraph.h"
#include "dumpfile.h"
#include "alias.h"
#include "fold-const.h"
#include "stor-layout.h"
#include "tree-eh.h"
#include "gimplify.h"
#include "gimple-iterator.h"
#include "gimplify-me.h"
#include "tree-cfg.h"
#include "tree-ssa-loop-manip.h"
#include "cfgloop.h"
#include "explow.h"
#include "tree-ssa-loop.h"
#include "tree-scalar-evolution.h"
#include "tree-vectorizer.h"
#include "builtins.h"
#include "internal-fn.h"
#include "tree-vector-builder.h"
#include "vec-perm-indices.h"
#include "tree-ssa-loop-niter.h"
#include "gimple-fold.h"
#include "regs.h"
#include "attribs.h"
/* For lang_hooks.types.type_for_mode. */
#include "langhooks.h"
/* Return the vectorized type for the given statement. */
tree
stmt_vectype (class _stmt_vec_info *stmt_info)
{
return STMT_VINFO_VECTYPE (stmt_info);
}
/* Return TRUE iff the given statement is in an inner loop relative to
the loop being vectorized. */
bool
stmt_in_inner_loop_p (class _stmt_vec_info *stmt_info)
{
gimple *stmt = STMT_VINFO_STMT (stmt_info);
basic_block bb = gimple_bb (stmt);
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
class loop* loop;
if (!loop_vinfo)
return false;
loop = LOOP_VINFO_LOOP (loop_vinfo);
return (bb->loop_father == loop->inner);
}
/* Record the cost of a statement, either by directly informing the
target model or by saving it in a vector for later processing.
Return a preliminary estimate of the statement's cost. */
unsigned
record_stmt_cost (stmt_vector_for_cost *body_cost_vec, int count,
enum vect_cost_for_stmt kind, stmt_vec_info stmt_info,
int misalign, enum vect_cost_model_location where)
{
if ((kind == vector_load || kind == unaligned_load)
&& STMT_VINFO_GATHER_SCATTER_P (stmt_info))
kind = vector_gather_load;
if ((kind == vector_store || kind == unaligned_store)
&& STMT_VINFO_GATHER_SCATTER_P (stmt_info))
kind = vector_scatter_store;
stmt_info_for_cost si = { count, kind, where, stmt_info, misalign };
body_cost_vec->safe_push (si);
tree vectype = stmt_info ? stmt_vectype (stmt_info) : NULL_TREE;
return (unsigned)
(builtin_vectorization_cost (kind, vectype, misalign) * count);
}
/* Return a variable of type ELEM_TYPE[NELEMS]. */
static tree
create_vector_array (tree elem_type, unsigned HOST_WIDE_INT nelems)
{
return create_tmp_var (build_array_type_nelts (elem_type, nelems),
"vect_array");
}
/* ARRAY is an array of vectors created by create_vector_array.
Return an SSA_NAME for the vector in index N. The reference
is part of the vectorization of STMT_INFO and the vector is associated
with scalar destination SCALAR_DEST. */
static tree
read_vector_array (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
tree scalar_dest, tree array, unsigned HOST_WIDE_INT n)
{
tree vect_type, vect, vect_name, array_ref;
gimple *new_stmt;
gcc_assert (TREE_CODE (TREE_TYPE (array)) == ARRAY_TYPE);
vect_type = TREE_TYPE (TREE_TYPE (array));
vect = vect_create_destination_var (scalar_dest, vect_type);
array_ref = build4 (ARRAY_REF, vect_type, array,
build_int_cst (size_type_node, n),
NULL_TREE, NULL_TREE);
new_stmt = gimple_build_assign (vect, array_ref);
vect_name = make_ssa_name (vect, new_stmt);
gimple_assign_set_lhs (new_stmt, vect_name);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
return vect_name;
}
/* ARRAY is an array of vectors created by create_vector_array.
Emit code to store SSA_NAME VECT in index N of the array.
The store is part of the vectorization of STMT_INFO. */
static void
write_vector_array (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
tree vect, tree array, unsigned HOST_WIDE_INT n)
{
tree array_ref;
gimple *new_stmt;
array_ref = build4 (ARRAY_REF, TREE_TYPE (vect), array,
build_int_cst (size_type_node, n),
NULL_TREE, NULL_TREE);
new_stmt = gimple_build_assign (array_ref, vect);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
/* PTR is a pointer to an array of type TYPE. Return a representation
of *PTR. The memory reference replaces those in FIRST_DR
(and its group). */
static tree
create_array_ref (tree type, tree ptr, tree alias_ptr_type)
{
tree mem_ref;
mem_ref = build2 (MEM_REF, type, ptr, build_int_cst (alias_ptr_type, 0));
/* Arrays have the same alignment as their type. */
set_ptr_info_alignment (get_ptr_info (ptr), TYPE_ALIGN_UNIT (type), 0);
return mem_ref;
}
/* Add a clobber of variable VAR to the vectorization of STMT_INFO.
Emit the clobber before *GSI. */
static void
vect_clobber_variable (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
tree var)
{
tree clobber = build_clobber (TREE_TYPE (var));
gimple *new_stmt = gimple_build_assign (var, clobber);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
/* Utility functions used by vect_mark_stmts_to_be_vectorized. */
/* Function vect_mark_relevant.
Mark STMT_INFO as "relevant for vectorization" and add it to WORKLIST. */
static void
vect_mark_relevant (vec<stmt_vec_info> *worklist, stmt_vec_info stmt_info,
enum vect_relevant relevant, bool live_p)
{
enum vect_relevant save_relevant = STMT_VINFO_RELEVANT (stmt_info);
bool save_live_p = STMT_VINFO_LIVE_P (stmt_info);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"mark relevant %d, live %d: %G", relevant, live_p,
stmt_info->stmt);
/* If this stmt is an original stmt in a pattern, we might need to mark its
related pattern stmt instead of the original stmt. However, such stmts
may have their own uses that are not in any pattern, in such cases the
stmt itself should be marked. */
if (STMT_VINFO_IN_PATTERN_P (stmt_info))
{
/* This is the last stmt in a sequence that was detected as a
pattern that can potentially be vectorized. Don't mark the stmt
as relevant/live because it's not going to be vectorized.
Instead mark the pattern-stmt that replaces it. */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"last stmt in pattern. don't mark"
" relevant/live.\n");
stmt_vec_info old_stmt_info = stmt_info;
stmt_info = STMT_VINFO_RELATED_STMT (stmt_info);
gcc_assert (STMT_VINFO_RELATED_STMT (stmt_info) == old_stmt_info);
save_relevant = STMT_VINFO_RELEVANT (stmt_info);
save_live_p = STMT_VINFO_LIVE_P (stmt_info);
}
STMT_VINFO_LIVE_P (stmt_info) |= live_p;
if (relevant > STMT_VINFO_RELEVANT (stmt_info))
STMT_VINFO_RELEVANT (stmt_info) = relevant;
if (STMT_VINFO_RELEVANT (stmt_info) == save_relevant
&& STMT_VINFO_LIVE_P (stmt_info) == save_live_p)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"already marked relevant/live.\n");
return;
}
worklist->safe_push (stmt_info);
}
/* Function is_simple_and_all_uses_invariant
Return true if STMT_INFO is simple and all uses of it are invariant. */
bool
is_simple_and_all_uses_invariant (stmt_vec_info stmt_info,
loop_vec_info loop_vinfo)
{
tree op;
ssa_op_iter iter;
gassign *stmt = dyn_cast <gassign *> (stmt_info->stmt);
if (!stmt)
return false;
FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
{
enum vect_def_type dt = vect_uninitialized_def;
if (!vect_is_simple_use (op, loop_vinfo, &dt))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
if (dt != vect_external_def && dt != vect_constant_def)
return false;
}
return true;
}
/* Function vect_stmt_relevant_p.
Return true if STMT_INFO, in the loop that is represented by LOOP_VINFO,
is "relevant for vectorization".
A stmt is considered "relevant for vectorization" if:
- it has uses outside the loop.
- it has vdefs (it alters memory).
- control stmts in the loop (except for the exit condition).
CHECKME: what other side effects would the vectorizer allow? */
static bool
vect_stmt_relevant_p (stmt_vec_info stmt_info, loop_vec_info loop_vinfo,
enum vect_relevant *relevant, bool *live_p)
{
class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
ssa_op_iter op_iter;
imm_use_iterator imm_iter;
use_operand_p use_p;
def_operand_p def_p;
*relevant = vect_unused_in_scope;
*live_p = false;
/* cond stmt other than loop exit cond. */
if (is_ctrl_stmt (stmt_info->stmt)
&& STMT_VINFO_TYPE (stmt_info) != loop_exit_ctrl_vec_info_type)
*relevant = vect_used_in_scope;
/* changing memory. */
if (gimple_code (stmt_info->stmt) != GIMPLE_PHI)
if (gimple_vdef (stmt_info->stmt)
&& !gimple_clobber_p (stmt_info->stmt))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vec_stmt_relevant_p: stmt has vdefs.\n");
*relevant = vect_used_in_scope;
}
/* uses outside the loop. */
FOR_EACH_PHI_OR_STMT_DEF (def_p, stmt_info->stmt, op_iter, SSA_OP_DEF)
{
FOR_EACH_IMM_USE_FAST (use_p, imm_iter, DEF_FROM_PTR (def_p))
{
basic_block bb = gimple_bb (USE_STMT (use_p));
if (!flow_bb_inside_loop_p (loop, bb))
{
if (is_gimple_debug (USE_STMT (use_p)))
continue;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vec_stmt_relevant_p: used out of loop.\n");
/* We expect all such uses to be in the loop exit phis
(because of loop closed form) */
gcc_assert (gimple_code (USE_STMT (use_p)) == GIMPLE_PHI);
gcc_assert (bb == single_exit (loop)->dest);
*live_p = true;
}
}
}
if (*live_p && *relevant == vect_unused_in_scope
&& !is_simple_and_all_uses_invariant (stmt_info, loop_vinfo))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vec_stmt_relevant_p: stmt live but not relevant.\n");
*relevant = vect_used_only_live;
}
return (*live_p || *relevant);
}
/* Function exist_non_indexing_operands_for_use_p
USE is one of the uses attached to STMT_INFO. Check if USE is
used in STMT_INFO for anything other than indexing an array. */
static bool
exist_non_indexing_operands_for_use_p (tree use, stmt_vec_info stmt_info)
{
tree operand;
/* USE corresponds to some operand in STMT. If there is no data
reference in STMT, then any operand that corresponds to USE
is not indexing an array. */
if (!STMT_VINFO_DATA_REF (stmt_info))
return true;
/* STMT has a data_ref. FORNOW this means that its of one of
the following forms:
-1- ARRAY_REF = var
-2- var = ARRAY_REF
(This should have been verified in analyze_data_refs).
'var' in the second case corresponds to a def, not a use,
so USE cannot correspond to any operands that are not used
for array indexing.
Therefore, all we need to check is if STMT falls into the
first case, and whether var corresponds to USE. */
gassign *assign = dyn_cast <gassign *> (stmt_info->stmt);
if (!assign || !gimple_assign_copy_p (assign))
{
gcall *call = dyn_cast <gcall *> (stmt_info->stmt);
if (call && gimple_call_internal_p (call))
{
internal_fn ifn = gimple_call_internal_fn (call);
int mask_index = internal_fn_mask_index (ifn);
if (mask_index >= 0
&& use == gimple_call_arg (call, mask_index))
return true;
int stored_value_index = internal_fn_stored_value_index (ifn);
if (stored_value_index >= 0
&& use == gimple_call_arg (call, stored_value_index))
return true;
if (internal_gather_scatter_fn_p (ifn)
&& use == gimple_call_arg (call, 1))
return true;
}
return false;
}
if (TREE_CODE (gimple_assign_lhs (assign)) == SSA_NAME)
return false;
operand = gimple_assign_rhs1 (assign);
if (TREE_CODE (operand) != SSA_NAME)
return false;
if (operand == use)
return true;
return false;
}
/*
Function process_use.
Inputs:
- a USE in STMT_VINFO in a loop represented by LOOP_VINFO
- RELEVANT - enum value to be set in the STMT_VINFO of the stmt
that defined USE. This is done by calling mark_relevant and passing it
the WORKLIST (to add DEF_STMT to the WORKLIST in case it is relevant).
- FORCE is true if exist_non_indexing_operands_for_use_p check shouldn't
be performed.
Outputs:
Generally, LIVE_P and RELEVANT are used to define the liveness and
relevance info of the DEF_STMT of this USE:
STMT_VINFO_LIVE_P (DEF_stmt_vinfo) <-- live_p
STMT_VINFO_RELEVANT (DEF_stmt_vinfo) <-- relevant
Exceptions:
- case 1: If USE is used only for address computations (e.g. array indexing),
which does not need to be directly vectorized, then the liveness/relevance
of the respective DEF_STMT is left unchanged.
- case 2: If STMT_VINFO is a reduction phi and DEF_STMT is a reduction stmt,
we skip DEF_STMT cause it had already been processed.
- case 3: If DEF_STMT and STMT_VINFO are in different nests, then
"relevant" will be modified accordingly.
Return true if everything is as expected. Return false otherwise. */
static opt_result
process_use (stmt_vec_info stmt_vinfo, tree use, loop_vec_info loop_vinfo,
enum vect_relevant relevant, vec<stmt_vec_info> *worklist,
bool force)
{
stmt_vec_info dstmt_vinfo;
enum vect_def_type dt;
/* case 1: we are only interested in uses that need to be vectorized. Uses
that are used for address computation are not considered relevant. */
if (!force && !exist_non_indexing_operands_for_use_p (use, stmt_vinfo))
return opt_result::success ();
if (!vect_is_simple_use (use, loop_vinfo, &dt, &dstmt_vinfo))
return opt_result::failure_at (stmt_vinfo->stmt,
"not vectorized:"
" unsupported use in stmt.\n");
if (!dstmt_vinfo)
return opt_result::success ();
basic_block def_bb = gimple_bb (dstmt_vinfo->stmt);
basic_block bb = gimple_bb (stmt_vinfo->stmt);
/* case 2: A reduction phi (STMT) defined by a reduction stmt (DSTMT_VINFO).
We have to force the stmt live since the epilogue loop needs it to
continue computing the reduction. */
if (gimple_code (stmt_vinfo->stmt) == GIMPLE_PHI
&& STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_reduction_def
&& gimple_code (dstmt_vinfo->stmt) != GIMPLE_PHI
&& STMT_VINFO_DEF_TYPE (dstmt_vinfo) == vect_reduction_def
&& bb->loop_father == def_bb->loop_father)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"reduc-stmt defining reduc-phi in the same nest.\n");
vect_mark_relevant (worklist, dstmt_vinfo, relevant, true);
return opt_result::success ();
}
/* case 3a: outer-loop stmt defining an inner-loop stmt:
outer-loop-header-bb:
d = dstmt_vinfo
inner-loop:
stmt # use (d)
outer-loop-tail-bb:
... */
if (flow_loop_nested_p (def_bb->loop_father, bb->loop_father))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"outer-loop def-stmt defining inner-loop stmt.\n");
switch (relevant)
{
case vect_unused_in_scope:
relevant = (STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_nested_cycle) ?
vect_used_in_scope : vect_unused_in_scope;
break;
case vect_used_in_outer_by_reduction:
gcc_assert (STMT_VINFO_DEF_TYPE (stmt_vinfo) != vect_reduction_def);
relevant = vect_used_by_reduction;
break;
case vect_used_in_outer:
gcc_assert (STMT_VINFO_DEF_TYPE (stmt_vinfo) != vect_reduction_def);
relevant = vect_used_in_scope;
break;
case vect_used_in_scope:
break;
default:
gcc_unreachable ();
}
}
/* case 3b: inner-loop stmt defining an outer-loop stmt:
outer-loop-header-bb:
...
inner-loop:
d = dstmt_vinfo
outer-loop-tail-bb (or outer-loop-exit-bb in double reduction):
stmt # use (d) */
else if (flow_loop_nested_p (bb->loop_father, def_bb->loop_father))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"inner-loop def-stmt defining outer-loop stmt.\n");
switch (relevant)
{
case vect_unused_in_scope:
relevant = (STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_reduction_def
|| STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_double_reduction_def) ?
vect_used_in_outer_by_reduction : vect_unused_in_scope;
break;
case vect_used_by_reduction:
case vect_used_only_live:
relevant = vect_used_in_outer_by_reduction;
break;
case vect_used_in_scope:
relevant = vect_used_in_outer;
break;
default:
gcc_unreachable ();
}
}
/* We are also not interested in uses on loop PHI backedges that are
inductions. Otherwise we'll needlessly vectorize the IV increment
and cause hybrid SLP for SLP inductions. Unless the PHI is live
of course. */
else if (gimple_code (stmt_vinfo->stmt) == GIMPLE_PHI
&& STMT_VINFO_DEF_TYPE (stmt_vinfo) == vect_induction_def
&& ! STMT_VINFO_LIVE_P (stmt_vinfo)
&& (PHI_ARG_DEF_FROM_EDGE (stmt_vinfo->stmt,
loop_latch_edge (bb->loop_father))
== use))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"induction value on backedge.\n");
return opt_result::success ();
}
vect_mark_relevant (worklist, dstmt_vinfo, relevant, false);
return opt_result::success ();
}
/* Function vect_mark_stmts_to_be_vectorized.
Not all stmts in the loop need to be vectorized. For example:
for i...
for j...
1. T0 = i + j
2. T1 = a[T0]
3. j = j + 1
Stmt 1 and 3 do not need to be vectorized, because loop control and
addressing of vectorized data-refs are handled differently.
This pass detects such stmts. */
opt_result
vect_mark_stmts_to_be_vectorized (loop_vec_info loop_vinfo, bool *fatal)
{
class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
unsigned int nbbs = loop->num_nodes;
gimple_stmt_iterator si;
unsigned int i;
basic_block bb;
bool live_p;
enum vect_relevant relevant;
DUMP_VECT_SCOPE ("vect_mark_stmts_to_be_vectorized");
auto_vec<stmt_vec_info, 64> worklist;
/* 1. Init worklist. */
for (i = 0; i < nbbs; i++)
{
bb = bbs[i];
for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
{
stmt_vec_info phi_info = loop_vinfo->lookup_stmt (gsi_stmt (si));
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location, "init: phi relevant? %G",
phi_info->stmt);
if (vect_stmt_relevant_p (phi_info, loop_vinfo, &relevant, &live_p))
vect_mark_relevant (&worklist, phi_info, relevant, live_p);
}
for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
{
stmt_vec_info stmt_info = loop_vinfo->lookup_stmt (gsi_stmt (si));
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"init: stmt relevant? %G", stmt_info->stmt);
if (vect_stmt_relevant_p (stmt_info, loop_vinfo, &relevant, &live_p))
vect_mark_relevant (&worklist, stmt_info, relevant, live_p);
}
}
/* 2. Process_worklist */
while (worklist.length () > 0)
{
use_operand_p use_p;
ssa_op_iter iter;
stmt_vec_info stmt_vinfo = worklist.pop ();
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"worklist: examine stmt: %G", stmt_vinfo->stmt);
/* Examine the USEs of STMT. For each USE, mark the stmt that defines it
(DEF_STMT) as relevant/irrelevant according to the relevance property
of STMT. */
relevant = STMT_VINFO_RELEVANT (stmt_vinfo);
/* Generally, the relevance property of STMT (in STMT_VINFO_RELEVANT) is
propagated as is to the DEF_STMTs of its USEs.
One exception is when STMT has been identified as defining a reduction
variable; in this case we set the relevance to vect_used_by_reduction.
This is because we distinguish between two kinds of relevant stmts -
those that are used by a reduction computation, and those that are
(also) used by a regular computation. This allows us later on to
identify stmts that are used solely by a reduction, and therefore the
order of the results that they produce does not have to be kept. */
switch (STMT_VINFO_DEF_TYPE (stmt_vinfo))
{
case vect_reduction_def:
gcc_assert (relevant != vect_unused_in_scope);
if (relevant != vect_unused_in_scope
&& relevant != vect_used_in_scope
&& relevant != vect_used_by_reduction
&& relevant != vect_used_only_live)
return opt_result::failure_at
(stmt_vinfo->stmt, "unsupported use of reduction.\n");
break;
case vect_nested_cycle:
if (relevant != vect_unused_in_scope
&& relevant != vect_used_in_outer_by_reduction
&& relevant != vect_used_in_outer)
return opt_result::failure_at
(stmt_vinfo->stmt, "unsupported use of nested cycle.\n");
break;
case vect_double_reduction_def:
if (relevant != vect_unused_in_scope
&& relevant != vect_used_by_reduction
&& relevant != vect_used_only_live)
return opt_result::failure_at
(stmt_vinfo->stmt, "unsupported use of double reduction.\n");
break;
default:
break;
}
if (is_pattern_stmt_p (stmt_vinfo))
{
/* Pattern statements are not inserted into the code, so
FOR_EACH_PHI_OR_STMT_USE optimizes their operands out, and we
have to scan the RHS or function arguments instead. */
if (gassign *assign = dyn_cast <gassign *> (stmt_vinfo->stmt))
{
enum tree_code rhs_code = gimple_assign_rhs_code (assign);
tree op = gimple_assign_rhs1 (assign);
i = 1;
if (rhs_code == COND_EXPR && COMPARISON_CLASS_P (op))
{
opt_result res
= process_use (stmt_vinfo, TREE_OPERAND (op, 0),
loop_vinfo, relevant, &worklist, false);
if (!res)
return res;
res = process_use (stmt_vinfo, TREE_OPERAND (op, 1),
loop_vinfo, relevant, &worklist, false);
if (!res)
return res;
i = 2;
}
for (; i < gimple_num_ops (assign); i++)
{
op = gimple_op (assign, i);
if (TREE_CODE (op) == SSA_NAME)
{
opt_result res
= process_use (stmt_vinfo, op, loop_vinfo, relevant,
&worklist, false);
if (!res)
return res;
}
}
}
else if (gcall *call = dyn_cast <gcall *> (stmt_vinfo->stmt))
{
for (i = 0; i < gimple_call_num_args (call); i++)
{
tree arg = gimple_call_arg (call, i);
opt_result res
= process_use (stmt_vinfo, arg, loop_vinfo, relevant,
&worklist, false);
if (!res)
return res;
}
}
}
else
FOR_EACH_PHI_OR_STMT_USE (use_p, stmt_vinfo->stmt, iter, SSA_OP_USE)
{
tree op = USE_FROM_PTR (use_p);
opt_result res
= process_use (stmt_vinfo, op, loop_vinfo, relevant,
&worklist, false);
if (!res)
return res;
}
if (STMT_VINFO_GATHER_SCATTER_P (stmt_vinfo))
{
gather_scatter_info gs_info;
if (!vect_check_gather_scatter (stmt_vinfo, loop_vinfo, &gs_info))
gcc_unreachable ();
opt_result res
= process_use (stmt_vinfo, gs_info.offset, loop_vinfo, relevant,
&worklist, true);
if (!res)
{
if (fatal)
*fatal = false;
return res;
}
}
} /* while worklist */
return opt_result::success ();
}
/* Compute the prologue cost for invariant or constant operands. */
static unsigned
vect_prologue_cost_for_slp_op (slp_tree node, stmt_vec_info stmt_info,
unsigned opno, enum vect_def_type dt,
stmt_vector_for_cost *cost_vec)
{
vec_info *vinfo = stmt_info->vinfo;
gimple *stmt = SLP_TREE_SCALAR_STMTS (node)[0]->stmt;
tree op = gimple_op (stmt, opno);
unsigned prologue_cost = 0;
/* Without looking at the actual initializer a vector of
constants can be implemented as load from the constant pool.
When all elements are the same we can use a splat. */
tree vectype = get_vectype_for_scalar_type (vinfo, TREE_TYPE (op), node);
unsigned group_size = SLP_TREE_SCALAR_STMTS (node).length ();
unsigned num_vects_to_check;
unsigned HOST_WIDE_INT const_nunits;
unsigned nelt_limit;
if (TYPE_VECTOR_SUBPARTS (vectype).is_constant (&const_nunits)
&& ! multiple_p (const_nunits, group_size))
{
num_vects_to_check = SLP_TREE_NUMBER_OF_VEC_STMTS (node);
nelt_limit = const_nunits;
}
else
{
/* If either the vector has variable length or the vectors
are composed of repeated whole groups we only need to
cost construction once. All vectors will be the same. */
num_vects_to_check = 1;
nelt_limit = group_size;
}
tree elt = NULL_TREE;
unsigned nelt = 0;
for (unsigned j = 0; j < num_vects_to_check * nelt_limit; ++j)
{
unsigned si = j % group_size;
if (nelt == 0)
elt = gimple_op (SLP_TREE_SCALAR_STMTS (node)[si]->stmt, opno);
/* ??? We're just tracking whether all operands of a single
vector initializer are the same, ideally we'd check if
we emitted the same one already. */
else if (elt != gimple_op (SLP_TREE_SCALAR_STMTS (node)[si]->stmt,
opno))
elt = NULL_TREE;
nelt++;
if (nelt == nelt_limit)
{
/* ??? We need to pass down stmt_info for a vector type
even if it points to the wrong stmt. */
prologue_cost += record_stmt_cost
(cost_vec, 1,
dt == vect_external_def
? (elt ? scalar_to_vec : vec_construct)
: vector_load,
stmt_info, 0, vect_prologue);
nelt = 0;
}
}
return prologue_cost;
}
/* Function vect_model_simple_cost.
Models cost for simple operations, i.e. those that only emit ncopies of a
single op. Right now, this does not account for multiple insns that could
be generated for the single vector op. We will handle that shortly. */
static void
vect_model_simple_cost (stmt_vec_info stmt_info, int ncopies,
enum vect_def_type *dt,
int ndts,
slp_tree node,
stmt_vector_for_cost *cost_vec,
vect_cost_for_stmt kind = vector_stmt)
{
int inside_cost = 0, prologue_cost = 0;
gcc_assert (cost_vec != NULL);
/* ??? Somehow we need to fix this at the callers. */
if (node)
ncopies = SLP_TREE_NUMBER_OF_VEC_STMTS (node);
if (node)
{
/* Scan operands and account for prologue cost of constants/externals.
??? This over-estimates cost for multiple uses and should be
re-engineered. */
gimple *stmt = SLP_TREE_SCALAR_STMTS (node)[0]->stmt;
tree lhs = gimple_get_lhs (stmt);
for (unsigned i = 0; i < gimple_num_ops (stmt); ++i)
{
tree op = gimple_op (stmt, i);
enum vect_def_type dt;
if (!op || op == lhs)
continue;
if (vect_is_simple_use (op, stmt_info->vinfo, &dt)
&& (dt == vect_constant_def || dt == vect_external_def))
prologue_cost += vect_prologue_cost_for_slp_op (node, stmt_info,
i, dt, cost_vec);
}
}
else
/* Cost the "broadcast" of a scalar operand in to a vector operand.
Use scalar_to_vec to cost the broadcast, as elsewhere in the vector
cost model. */
for (int i = 0; i < ndts; i++)
if (dt[i] == vect_constant_def || dt[i] == vect_external_def)
prologue_cost += record_stmt_cost (cost_vec, 1, scalar_to_vec,
stmt_info, 0, vect_prologue);
/* Adjust for two-operator SLP nodes. */
if (node && SLP_TREE_TWO_OPERATORS (node))
{
ncopies *= 2;
inside_cost += record_stmt_cost (cost_vec, ncopies, vec_perm,
stmt_info, 0, vect_body);
}
/* Pass the inside-of-loop statements to the target-specific cost model. */
inside_cost += record_stmt_cost (cost_vec, ncopies, kind,
stmt_info, 0, vect_body);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_simple_cost: inside_cost = %d, "
"prologue_cost = %d .\n", inside_cost, prologue_cost);
}
/* Model cost for type demotion and promotion operations. PWR is
normally zero for single-step promotions and demotions. It will be
one if two-step promotion/demotion is required, and so on. NCOPIES
is the number of vector results (and thus number of instructions)
for the narrowest end of the operation chain. Each additional
step doubles the number of instructions required. */
static void
vect_model_promotion_demotion_cost (stmt_vec_info stmt_info,
enum vect_def_type *dt,
unsigned int ncopies, int pwr,
stmt_vector_for_cost *cost_vec)
{
int i;
int inside_cost = 0, prologue_cost = 0;
for (i = 0; i < pwr + 1; i++)
{
inside_cost += record_stmt_cost (cost_vec, ncopies, vec_promote_demote,
stmt_info, 0, vect_body);
ncopies *= 2;
}
/* FORNOW: Assuming maximum 2 args per stmts. */
for (i = 0; i < 2; i++)
if (dt[i] == vect_constant_def || dt[i] == vect_external_def)
prologue_cost += record_stmt_cost (cost_vec, 1, vector_stmt,
stmt_info, 0, vect_prologue);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_promotion_demotion_cost: inside_cost = %d, "
"prologue_cost = %d .\n", inside_cost, prologue_cost);
}
/* Returns true if the current function returns DECL. */
static bool
cfun_returns (tree decl)
{
edge_iterator ei;
edge e;
FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
{
greturn *ret = safe_dyn_cast <greturn *> (last_stmt (e->src));
if (!ret)
continue;
if (gimple_return_retval (ret) == decl)
return true;
/* We often end up with an aggregate copy to the result decl,
handle that case as well. First skip intermediate clobbers
though. */
gimple *def = ret;
do
{
def = SSA_NAME_DEF_STMT (gimple_vuse (def));
}
while (gimple_clobber_p (def));
if (is_a <gassign *> (def)
&& gimple_assign_lhs (def) == gimple_return_retval (ret)
&& gimple_assign_rhs1 (def) == decl)
return true;
}
return false;
}
/* Function vect_model_store_cost
Models cost for stores. In the case of grouped accesses, one access
has the overhead of the grouped access attributed to it. */
static void
vect_model_store_cost (stmt_vec_info stmt_info, int ncopies,
enum vect_def_type dt,
vect_memory_access_type memory_access_type,
vec_load_store_type vls_type, slp_tree slp_node,
stmt_vector_for_cost *cost_vec)
{
unsigned int inside_cost = 0, prologue_cost = 0;
stmt_vec_info first_stmt_info = stmt_info;
bool grouped_access_p = STMT_VINFO_GROUPED_ACCESS (stmt_info);
/* ??? Somehow we need to fix this at the callers. */
if (slp_node)
ncopies = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
if (vls_type == VLS_STORE_INVARIANT)
{
if (slp_node)
prologue_cost += vect_prologue_cost_for_slp_op (slp_node, stmt_info,
1, dt, cost_vec);
else
prologue_cost += record_stmt_cost (cost_vec, 1, scalar_to_vec,
stmt_info, 0, vect_prologue);
}
/* Grouped stores update all elements in the group at once,
so we want the DR for the first statement. */
if (!slp_node && grouped_access_p)
first_stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
/* True if we should include any once-per-group costs as well as
the cost of the statement itself. For SLP we only get called
once per group anyhow. */
bool first_stmt_p = (first_stmt_info == stmt_info);
/* We assume that the cost of a single store-lanes instruction is
equivalent to the cost of DR_GROUP_SIZE separate stores. If a grouped
access is instead being provided by a permute-and-store operation,
include the cost of the permutes. */
if (first_stmt_p
&& memory_access_type == VMAT_CONTIGUOUS_PERMUTE)
{
/* Uses a high and low interleave or shuffle operations for each
needed permute. */
int group_size = DR_GROUP_SIZE (first_stmt_info);
int nstmts = ncopies * ceil_log2 (group_size) * group_size;
inside_cost = record_stmt_cost (cost_vec, nstmts, vec_perm,
stmt_info, 0, vect_body);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_store_cost: strided group_size = %d .\n",
group_size);
}
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
/* Costs of the stores. */
if (memory_access_type == VMAT_ELEMENTWISE
|| memory_access_type == VMAT_GATHER_SCATTER)
{
/* N scalar stores plus extracting the elements. */
unsigned int assumed_nunits = vect_nunits_for_cost (vectype);
inside_cost += record_stmt_cost (cost_vec,
ncopies * assumed_nunits,
scalar_store, stmt_info, 0, vect_body);
}
else
vect_get_store_cost (stmt_info, ncopies, &inside_cost, cost_vec);
if (memory_access_type == VMAT_ELEMENTWISE
|| memory_access_type == VMAT_STRIDED_SLP)
{
/* N scalar stores plus extracting the elements. */
unsigned int assumed_nunits = vect_nunits_for_cost (vectype);
inside_cost += record_stmt_cost (cost_vec,
ncopies * assumed_nunits,
vec_to_scalar, stmt_info, 0, vect_body);
}
/* When vectorizing a store into the function result assign
a penalty if the function returns in a multi-register location.
In this case we assume we'll end up with having to spill the
vector result and do piecewise loads as a conservative estimate. */
tree base = get_base_address (STMT_VINFO_DATA_REF (stmt_info)->ref);
if (base
&& (TREE_CODE (base) == RESULT_DECL
|| (DECL_P (base) && cfun_returns (base)))
&& !aggregate_value_p (base, cfun->decl))
{
rtx reg = hard_function_value (TREE_TYPE (base), cfun->decl, 0, 1);
/* ??? Handle PARALLEL in some way. */
if (REG_P (reg))
{
int nregs = hard_regno_nregs (REGNO (reg), GET_MODE (reg));
/* Assume that a single reg-reg move is possible and cheap,
do not account for vector to gp register move cost. */
if (nregs > 1)
{
/* Spill. */
prologue_cost += record_stmt_cost (cost_vec, ncopies,
vector_store,
stmt_info, 0, vect_epilogue);
/* Loads. */
prologue_cost += record_stmt_cost (cost_vec, ncopies * nregs,
scalar_load,
stmt_info, 0, vect_epilogue);
}
}
}
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_store_cost: inside_cost = %d, "
"prologue_cost = %d .\n", inside_cost, prologue_cost);
}
/* Calculate cost of DR's memory access. */
void
vect_get_store_cost (stmt_vec_info stmt_info, int ncopies,
unsigned int *inside_cost,
stmt_vector_for_cost *body_cost_vec)
{
dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info);
int alignment_support_scheme
= vect_supportable_dr_alignment (dr_info, false);
switch (alignment_support_scheme)
{
case dr_aligned:
{
*inside_cost += record_stmt_cost (body_cost_vec, ncopies,
vector_store, stmt_info, 0,
vect_body);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_store_cost: aligned.\n");
break;
}
case dr_unaligned_supported:
{
/* Here, we assign an additional cost for the unaligned store. */
*inside_cost += record_stmt_cost (body_cost_vec, ncopies,
unaligned_store, stmt_info,
DR_MISALIGNMENT (dr_info),
vect_body);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_store_cost: unaligned supported by "
"hardware.\n");
break;
}
case dr_unaligned_unsupported:
{
*inside_cost = VECT_MAX_COST;
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"vect_model_store_cost: unsupported access.\n");
break;
}
default:
gcc_unreachable ();
}
}
/* Function vect_model_load_cost
Models cost for loads. In the case of grouped accesses, one access has
the overhead of the grouped access attributed to it. Since unaligned
accesses are supported for loads, we also account for the costs of the
access scheme chosen. */
static void
vect_model_load_cost (stmt_vec_info stmt_info, unsigned ncopies,
vect_memory_access_type memory_access_type,
slp_instance instance,
slp_tree slp_node,
stmt_vector_for_cost *cost_vec)
{
unsigned int inside_cost = 0, prologue_cost = 0;
bool grouped_access_p = STMT_VINFO_GROUPED_ACCESS (stmt_info);
gcc_assert (cost_vec);
/* ??? Somehow we need to fix this at the callers. */
if (slp_node)
ncopies = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
if (slp_node && SLP_TREE_LOAD_PERMUTATION (slp_node).exists ())
{
/* If the load is permuted then the alignment is determined by
the first group element not by the first scalar stmt DR. */
stmt_vec_info first_stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
/* Record the cost for the permutation. */
unsigned n_perms;
unsigned assumed_nunits
= vect_nunits_for_cost (STMT_VINFO_VECTYPE (first_stmt_info));
unsigned slp_vf = (ncopies * assumed_nunits) / instance->group_size;
vect_transform_slp_perm_load (slp_node, vNULL, NULL,
slp_vf, instance, true,
&n_perms);
inside_cost += record_stmt_cost (cost_vec, n_perms, vec_perm,
first_stmt_info, 0, vect_body);
/* And adjust the number of loads performed. This handles
redundancies as well as loads that are later dead. */
auto_sbitmap perm (DR_GROUP_SIZE (first_stmt_info));
bitmap_clear (perm);
for (unsigned i = 0;
i < SLP_TREE_LOAD_PERMUTATION (slp_node).length (); ++i)
bitmap_set_bit (perm, SLP_TREE_LOAD_PERMUTATION (slp_node)[i]);
ncopies = 0;
bool load_seen = false;
for (unsigned i = 0; i < DR_GROUP_SIZE (first_stmt_info); ++i)
{
if (i % assumed_nunits == 0)
{
if (load_seen)
ncopies++;
load_seen = false;
}
if (bitmap_bit_p (perm, i))
load_seen = true;
}
if (load_seen)
ncopies++;
gcc_assert (ncopies
<= (DR_GROUP_SIZE (first_stmt_info)
- DR_GROUP_GAP (first_stmt_info)
+ assumed_nunits - 1) / assumed_nunits);
}
/* Grouped loads read all elements in the group at once,
so we want the DR for the first statement. */
stmt_vec_info first_stmt_info = stmt_info;
if (!slp_node && grouped_access_p)
first_stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
/* True if we should include any once-per-group costs as well as
the cost of the statement itself. For SLP we only get called
once per group anyhow. */
bool first_stmt_p = (first_stmt_info == stmt_info);
/* We assume that the cost of a single load-lanes instruction is
equivalent to the cost of DR_GROUP_SIZE separate loads. If a grouped
access is instead being provided by a load-and-permute operation,
include the cost of the permutes. */
if (first_stmt_p
&& memory_access_type == VMAT_CONTIGUOUS_PERMUTE)
{
/* Uses an even and odd extract operations or shuffle operations
for each needed permute. */
int group_size = DR_GROUP_SIZE (first_stmt_info);
int nstmts = ncopies * ceil_log2 (group_size) * group_size;
inside_cost += record_stmt_cost (cost_vec, nstmts, vec_perm,
stmt_info, 0, vect_body);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_load_cost: strided group_size = %d .\n",
group_size);
}
/* The loads themselves. */
if (memory_access_type == VMAT_ELEMENTWISE
|| memory_access_type == VMAT_GATHER_SCATTER)
{
/* N scalar loads plus gathering them into a vector. */
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
unsigned int assumed_nunits = vect_nunits_for_cost (vectype);
inside_cost += record_stmt_cost (cost_vec,
ncopies * assumed_nunits,
scalar_load, stmt_info, 0, vect_body);
}
else
vect_get_load_cost (stmt_info, ncopies, first_stmt_p,
&inside_cost, &prologue_cost,
cost_vec, cost_vec, true);
if (memory_access_type == VMAT_ELEMENTWISE
|| memory_access_type == VMAT_STRIDED_SLP)
inside_cost += record_stmt_cost (cost_vec, ncopies, vec_construct,
stmt_info, 0, vect_body);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_load_cost: inside_cost = %d, "
"prologue_cost = %d .\n", inside_cost, prologue_cost);
}
/* Calculate cost of DR's memory access. */
void
vect_get_load_cost (stmt_vec_info stmt_info, int ncopies,
bool add_realign_cost, unsigned int *inside_cost,
unsigned int *prologue_cost,
stmt_vector_for_cost *prologue_cost_vec,
stmt_vector_for_cost *body_cost_vec,
bool record_prologue_costs)
{
dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info);
int alignment_support_scheme
= vect_supportable_dr_alignment (dr_info, false);
switch (alignment_support_scheme)
{
case dr_aligned:
{
*inside_cost += record_stmt_cost (body_cost_vec, ncopies, vector_load,
stmt_info, 0, vect_body);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_load_cost: aligned.\n");
break;
}
case dr_unaligned_supported:
{
/* Here, we assign an additional cost for the unaligned load. */
*inside_cost += record_stmt_cost (body_cost_vec, ncopies,
unaligned_load, stmt_info,
DR_MISALIGNMENT (dr_info),
vect_body);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_load_cost: unaligned supported by "
"hardware.\n");
break;
}
case dr_explicit_realign:
{
*inside_cost += record_stmt_cost (body_cost_vec, ncopies * 2,
vector_load, stmt_info, 0, vect_body);
*inside_cost += record_stmt_cost (body_cost_vec, ncopies,
vec_perm, stmt_info, 0, vect_body);
/* FIXME: If the misalignment remains fixed across the iterations of
the containing loop, the following cost should be added to the
prologue costs. */
if (targetm.vectorize.builtin_mask_for_load)
*inside_cost += record_stmt_cost (body_cost_vec, 1, vector_stmt,
stmt_info, 0, vect_body);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_load_cost: explicit realign\n");
break;
}
case dr_explicit_realign_optimized:
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_load_cost: unaligned software "
"pipelined.\n");
/* Unaligned software pipeline has a load of an address, an initial
load, and possibly a mask operation to "prime" the loop. However,
if this is an access in a group of loads, which provide grouped
access, then the above cost should only be considered for one
access in the group. Inside the loop, there is a load op
and a realignment op. */
if (add_realign_cost && record_prologue_costs)
{
*prologue_cost += record_stmt_cost (prologue_cost_vec, 2,
vector_stmt, stmt_info,
0, vect_prologue);
if (targetm.vectorize.builtin_mask_for_load)
*prologue_cost += record_stmt_cost (prologue_cost_vec, 1,
vector_stmt, stmt_info,
0, vect_prologue);
}
*inside_cost += record_stmt_cost (body_cost_vec, ncopies, vector_load,
stmt_info, 0, vect_body);
*inside_cost += record_stmt_cost (body_cost_vec, ncopies, vec_perm,
stmt_info, 0, vect_body);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_model_load_cost: explicit realign optimized"
"\n");
break;
}
case dr_unaligned_unsupported:
{
*inside_cost = VECT_MAX_COST;
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"vect_model_load_cost: unsupported access.\n");
break;
}
default:
gcc_unreachable ();
}
}
/* Insert the new stmt NEW_STMT at *GSI or at the appropriate place in
the loop preheader for the vectorized stmt STMT_VINFO. */
static void
vect_init_vector_1 (stmt_vec_info stmt_vinfo, gimple *new_stmt,
gimple_stmt_iterator *gsi)
{
if (gsi)
vect_finish_stmt_generation (stmt_vinfo, new_stmt, gsi);
else
{
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_vinfo);
if (loop_vinfo)
{
class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
basic_block new_bb;
edge pe;
if (nested_in_vect_loop_p (loop, stmt_vinfo))
loop = loop->inner;
pe = loop_preheader_edge (loop);
new_bb = gsi_insert_on_edge_immediate (pe, new_stmt);
gcc_assert (!new_bb);
}
else
{
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_vinfo);
basic_block bb;
gimple_stmt_iterator gsi_bb_start;
gcc_assert (bb_vinfo);
bb = BB_VINFO_BB (bb_vinfo);
gsi_bb_start = gsi_after_labels (bb);
gsi_insert_before (&gsi_bb_start, new_stmt, GSI_SAME_STMT);
}
}
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"created new init_stmt: %G", new_stmt);
}
/* Function vect_init_vector.
Insert a new stmt (INIT_STMT) that initializes a new variable of type
TYPE with the value VAL. If TYPE is a vector type and VAL does not have
vector type a vector with all elements equal to VAL is created first.
Place the initialization at GSI if it is not NULL. Otherwise, place the
initialization at the loop preheader.
Return the DEF of INIT_STMT.
It will be used in the vectorization of STMT_INFO. */
tree
vect_init_vector (stmt_vec_info stmt_info, tree val, tree type,
gimple_stmt_iterator *gsi)
{
gimple *init_stmt;
tree new_temp;
/* We abuse this function to push sth to a SSA name with initial 'val'. */
if (! useless_type_conversion_p (type, TREE_TYPE (val)))
{
gcc_assert (TREE_CODE (type) == VECTOR_TYPE);
if (! types_compatible_p (TREE_TYPE (type), TREE_TYPE (val)))
{
/* Scalar boolean value should be transformed into
all zeros or all ones value before building a vector. */
if (VECTOR_BOOLEAN_TYPE_P (type))
{
tree true_val = build_all_ones_cst (TREE_TYPE (type));
tree false_val = build_zero_cst (TREE_TYPE (type));
if (CONSTANT_CLASS_P (val))
val = integer_zerop (val) ? false_val : true_val;
else
{
new_temp = make_ssa_name (TREE_TYPE (type));
init_stmt = gimple_build_assign (new_temp, COND_EXPR,
val, true_val, false_val);
vect_init_vector_1 (stmt_info, init_stmt, gsi);
val = new_temp;
}
}
else
{
gimple_seq stmts = NULL;
if (! INTEGRAL_TYPE_P (TREE_TYPE (val)))
val = gimple_build (&stmts, VIEW_CONVERT_EXPR,
TREE_TYPE (type), val);
else
/* ??? Condition vectorization expects us to do
promotion of invariant/external defs. */
val = gimple_convert (&stmts, TREE_TYPE (type), val);
for (gimple_stmt_iterator gsi2 = gsi_start (stmts);
!gsi_end_p (gsi2); )
{
init_stmt = gsi_stmt (gsi2);
gsi_remove (&gsi2, false);
vect_init_vector_1 (stmt_info, init_stmt, gsi);
}
}
}
val = build_vector_from_val (type, val);
}
new_temp = vect_get_new_ssa_name (type, vect_simple_var, "cst_");
init_stmt = gimple_build_assign (new_temp, val);
vect_init_vector_1 (stmt_info, init_stmt, gsi);
return new_temp;
}
/* Function vect_get_vec_def_for_operand_1.
For a defining stmt DEF_STMT_INFO of a scalar stmt, return a vector def
with type DT that will be used in the vectorized stmt. */
tree
vect_get_vec_def_for_operand_1 (stmt_vec_info def_stmt_info,
enum vect_def_type dt)
{
tree vec_oprnd;
stmt_vec_info vec_stmt_info;
switch (dt)
{
/* operand is a constant or a loop invariant. */
case vect_constant_def:
case vect_external_def:
/* Code should use vect_get_vec_def_for_operand. */
gcc_unreachable ();
/* Operand is defined by a loop header phi. In case of nested
cycles we also may have uses of the backedge def. */
case vect_reduction_def:
case vect_double_reduction_def:
case vect_nested_cycle:
case vect_induction_def:
gcc_assert (gimple_code (def_stmt_info->stmt) == GIMPLE_PHI
|| dt == vect_nested_cycle);
/* Fallthru. */
/* operand is defined inside the loop. */
case vect_internal_def:
{
/* Get the def from the vectorized stmt. */
vec_stmt_info = STMT_VINFO_VEC_STMT (def_stmt_info);
/* Get vectorized pattern statement. */
if (!vec_stmt_info
&& STMT_VINFO_IN_PATTERN_P (def_stmt_info)
&& !STMT_VINFO_RELEVANT (def_stmt_info))
vec_stmt_info = (STMT_VINFO_VEC_STMT
(STMT_VINFO_RELATED_STMT (def_stmt_info)));
gcc_assert (vec_stmt_info);
if (gphi *phi = dyn_cast <gphi *> (vec_stmt_info->stmt))
vec_oprnd = PHI_RESULT (phi);
else
vec_oprnd = gimple_get_lhs (vec_stmt_info->stmt);
return vec_oprnd;
}
default:
gcc_unreachable ();
}
}
/* Function vect_get_vec_def_for_operand.
OP is an operand in STMT_VINFO. This function returns a (vector) def
that will be used in the vectorized stmt for STMT_VINFO.
In the case that OP is an SSA_NAME which is defined in the loop, then
STMT_VINFO_VEC_STMT of the defining stmt holds the relevant def.
In case OP is an invariant or constant, a new stmt that creates a vector def
needs to be introduced. VECTYPE may be used to specify a required type for
vector invariant. */
tree
vect_get_vec_def_for_operand (tree op, stmt_vec_info stmt_vinfo, tree vectype)
{
gimple *def_stmt;
enum vect_def_type dt;
bool is_simple_use;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_vinfo);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_get_vec_def_for_operand: %T\n", op);
stmt_vec_info def_stmt_info;
is_simple_use = vect_is_simple_use (op, loop_vinfo, &dt,
&def_stmt_info, &def_stmt);
gcc_assert (is_simple_use);
if (def_stmt && dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location, " def_stmt = %G", def_stmt);
if (dt == vect_constant_def || dt == vect_external_def)
{
tree stmt_vectype = STMT_VINFO_VECTYPE (stmt_vinfo);
tree vector_type;
if (vectype)
vector_type = vectype;
else if (VECT_SCALAR_BOOLEAN_TYPE_P (TREE_TYPE (op))
&& VECTOR_BOOLEAN_TYPE_P (stmt_vectype))
vector_type = truth_type_for (stmt_vectype);
else
vector_type = get_vectype_for_scalar_type (loop_vinfo, TREE_TYPE (op));
gcc_assert (vector_type);
return vect_init_vector (stmt_vinfo, op, vector_type, NULL);
}
else
return vect_get_vec_def_for_operand_1 (def_stmt_info, dt);
}
/* Function vect_get_vec_def_for_stmt_copy
Return a vector-def for an operand. This function is used when the
vectorized stmt to be created (by the caller to this function) is a "copy"
created in case the vectorized result cannot fit in one vector, and several
copies of the vector-stmt are required. In this case the vector-def is
retrieved from the vector stmt recorded in the STMT_VINFO_RELATED_STMT field
of the stmt that defines VEC_OPRND. VINFO describes the vectorization.
Context:
In case the vectorization factor (VF) is bigger than the number
of elements that can fit in a vectype (nunits), we have to generate
more than one vector stmt to vectorize the scalar stmt. This situation
arises when there are multiple data-types operated upon in the loop; the
smallest data-type determines the VF, and as a result, when vectorizing
stmts operating on wider types we need to create 'VF/nunits' "copies" of the
vector stmt (each computing a vector of 'nunits' results, and together
computing 'VF' results in each iteration). This function is called when
vectorizing such a stmt (e.g. vectorizing S2 in the illustration below, in
which VF=16 and nunits=4, so the number of copies required is 4):
scalar stmt: vectorized into: STMT_VINFO_RELATED_STMT
S1: x = load VS1.0: vx.0 = memref0 VS1.1
VS1.1: vx.1 = memref1 VS1.2
VS1.2: vx.2 = memref2 VS1.3
VS1.3: vx.3 = memref3
S2: z = x + ... VSnew.0: vz0 = vx.0 + ... VSnew.1
VSnew.1: vz1 = vx.1 + ... VSnew.2
VSnew.2: vz2 = vx.2 + ... VSnew.3
VSnew.3: vz3 = vx.3 + ...
The vectorization of S1 is explained in vectorizable_load.
The vectorization of S2:
To create the first vector-stmt out of the 4 copies - VSnew.0 -
the function 'vect_get_vec_def_for_operand' is called to
get the relevant vector-def for each operand of S2. For operand x it
returns the vector-def 'vx.0'.
To create the remaining copies of the vector-stmt (VSnew.j), this
function is called to get the relevant vector-def for each operand. It is
obtained from the respective VS1.j stmt, which is recorded in the
STMT_VINFO_RELATED_STMT field of the stmt that defines VEC_OPRND.
For example, to obtain the vector-def 'vx.1' in order to create the
vector stmt 'VSnew.1', this function is called with VEC_OPRND='vx.0'.
Given 'vx0' we obtain the stmt that defines it ('VS1.0'); from the
STMT_VINFO_RELATED_STMT field of 'VS1.0' we obtain the next copy - 'VS1.1',
and return its def ('vx.1').
Overall, to create the above sequence this function will be called 3 times:
vx.1 = vect_get_vec_def_for_stmt_copy (vinfo, vx.0);
vx.2 = vect_get_vec_def_for_stmt_copy (vinfo, vx.1);
vx.3 = vect_get_vec_def_for_stmt_copy (vinfo, vx.2); */
tree
vect_get_vec_def_for_stmt_copy (vec_info *vinfo, tree vec_oprnd)
{
stmt_vec_info def_stmt_info = vinfo->lookup_def (vec_oprnd);
if (!def_stmt_info)
/* Do nothing; can reuse same def. */
return vec_oprnd;
def_stmt_info = STMT_VINFO_RELATED_STMT (def_stmt_info);
gcc_assert (def_stmt_info);
if (gphi *phi = dyn_cast <gphi *> (def_stmt_info->stmt))
vec_oprnd = PHI_RESULT (phi);
else
vec_oprnd = gimple_get_lhs (def_stmt_info->stmt);
return vec_oprnd;
}
/* Get vectorized definitions for the operands to create a copy of an original
stmt. See vect_get_vec_def_for_stmt_copy () for details. */
void
vect_get_vec_defs_for_stmt_copy (vec_info *vinfo,
vec<tree> *vec_oprnds0,
vec<tree> *vec_oprnds1)
{
tree vec_oprnd = vec_oprnds0->pop ();
vec_oprnd = vect_get_vec_def_for_stmt_copy (vinfo, vec_oprnd);
vec_oprnds0->quick_push (vec_oprnd);
if (vec_oprnds1 && vec_oprnds1->length ())
{
vec_oprnd = vec_oprnds1->pop ();
vec_oprnd = vect_get_vec_def_for_stmt_copy (vinfo, vec_oprnd);
vec_oprnds1->quick_push (vec_oprnd);
}
}
/* Get vectorized definitions for OP0 and OP1. */
void
vect_get_vec_defs (tree op0, tree op1, stmt_vec_info stmt_info,
vec<tree> *vec_oprnds0,
vec<tree> *vec_oprnds1,
slp_tree slp_node)
{
if (slp_node)
{
auto_vec<vec<tree> > vec_defs (SLP_TREE_CHILDREN (slp_node).length ());
vect_get_slp_defs (slp_node, &vec_defs, op1 ? 2 : 1);
*vec_oprnds0 = vec_defs[0];
if (op1)
*vec_oprnds1 = vec_defs[1];
}
else
{
tree vec_oprnd;
vec_oprnds0->create (1);
vec_oprnd = vect_get_vec_def_for_operand (op0, stmt_info);
vec_oprnds0->quick_push (vec_oprnd);
if (op1)
{
vec_oprnds1->create (1);
vec_oprnd = vect_get_vec_def_for_operand (op1, stmt_info);
vec_oprnds1->quick_push (vec_oprnd);
}
}
}
/* Helper function called by vect_finish_replace_stmt and
vect_finish_stmt_generation. Set the location of the new
statement and create and return a stmt_vec_info for it. */
static stmt_vec_info
vect_finish_stmt_generation_1 (stmt_vec_info stmt_info, gimple *vec_stmt)
{
vec_info *vinfo = stmt_info->vinfo;
stmt_vec_info vec_stmt_info = vinfo->add_stmt (vec_stmt);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location, "add new stmt: %G", vec_stmt);
gimple_set_location (vec_stmt, gimple_location (stmt_info->stmt));
/* While EH edges will generally prevent vectorization, stmt might
e.g. be in a must-not-throw region. Ensure newly created stmts
that could throw are part of the same region. */
int lp_nr = lookup_stmt_eh_lp (stmt_info->stmt);
if (lp_nr != 0 && stmt_could_throw_p (cfun, vec_stmt))
add_stmt_to_eh_lp (vec_stmt, lp_nr);
return vec_stmt_info;
}
/* Replace the scalar statement STMT_INFO with a new vector statement VEC_STMT,
which sets the same scalar result as STMT_INFO did. Create and return a
stmt_vec_info for VEC_STMT. */
stmt_vec_info
vect_finish_replace_stmt (stmt_vec_info stmt_info, gimple *vec_stmt)
{
gimple *scalar_stmt = vect_orig_stmt (stmt_info)->stmt;
gcc_assert (gimple_get_lhs (scalar_stmt) == gimple_get_lhs (vec_stmt));
gimple_stmt_iterator gsi = gsi_for_stmt (scalar_stmt);
gsi_replace (&gsi, vec_stmt, true);
return vect_finish_stmt_generation_1 (stmt_info, vec_stmt);
}
/* Add VEC_STMT to the vectorized implementation of STMT_INFO and insert it
before *GSI. Create and return a stmt_vec_info for VEC_STMT. */
stmt_vec_info
vect_finish_stmt_generation (stmt_vec_info stmt_info, gimple *vec_stmt,
gimple_stmt_iterator *gsi)
{
gcc_assert (gimple_code (stmt_info->stmt) != GIMPLE_LABEL);
if (!gsi_end_p (*gsi)
&& gimple_has_mem_ops (vec_stmt))
{
gimple *at_stmt = gsi_stmt (*gsi);
tree vuse = gimple_vuse (at_stmt);
if (vuse && TREE_CODE (vuse) == SSA_NAME)
{
tree vdef = gimple_vdef (at_stmt);
gimple_set_vuse (vec_stmt, gimple_vuse (at_stmt));
/* If we have an SSA vuse and insert a store, update virtual
SSA form to avoid triggering the renamer. Do so only
if we can easily see all uses - which is what almost always
happens with the way vectorized stmts are inserted. */
if ((vdef && TREE_CODE (vdef) == SSA_NAME)
&& ((is_gimple_assign (vec_stmt)
&& !is_gimple_reg (gimple_assign_lhs (vec_stmt)))
|| (is_gimple_call (vec_stmt)
&& !(gimple_call_flags (vec_stmt)
& (ECF_CONST|ECF_PURE|ECF_NOVOPS)))))
{
tree new_vdef = copy_ssa_name (vuse, vec_stmt);
gimple_set_vdef (vec_stmt, new_vdef);
SET_USE (gimple_vuse_op (at_stmt), new_vdef);
}
}
}
gsi_insert_before (gsi, vec_stmt, GSI_SAME_STMT);
return vect_finish_stmt_generation_1 (stmt_info, vec_stmt);
}
/* We want to vectorize a call to combined function CFN with function
decl FNDECL, using VECTYPE_OUT as the type of the output and VECTYPE_IN
as the types of all inputs. Check whether this is possible using
an internal function, returning its code if so or IFN_LAST if not. */
static internal_fn
vectorizable_internal_function (combined_fn cfn, tree fndecl,
tree vectype_out, tree vectype_in)
{
internal_fn ifn;
if (internal_fn_p (cfn))
ifn = as_internal_fn (cfn);
else
ifn = associated_internal_fn (fndecl);
if (ifn != IFN_LAST && direct_internal_fn_p (ifn))
{
const direct_internal_fn_info &info = direct_internal_fn (ifn);
if (info.vectorizable)
{
tree type0 = (info.type0 < 0 ? vectype_out : vectype_in);
tree type1 = (info.type1 < 0 ? vectype_out : vectype_in);
if (direct_internal_fn_supported_p (ifn, tree_pair (type0, type1),
OPTIMIZE_FOR_SPEED))
return ifn;
}
}
return IFN_LAST;
}
static tree permute_vec_elements (tree, tree, tree, stmt_vec_info,
gimple_stmt_iterator *);
/* Check whether a load or store statement in the loop described by
LOOP_VINFO is possible in a fully-masked loop. This is testing
whether the vectorizer pass has the appropriate support, as well as
whether the target does.
VLS_TYPE says whether the statement is a load or store and VECTYPE
is the type of the vector being loaded or stored. MEMORY_ACCESS_TYPE
says how the load or store is going to be implemented and GROUP_SIZE
is the number of load or store statements in the containing group.
If the access is a gather load or scatter store, GS_INFO describes
its arguments. If the load or store is conditional, SCALAR_MASK is the
condition under which it occurs.
Clear LOOP_VINFO_CAN_FULLY_MASK_P if a fully-masked loop is not
supported, otherwise record the required mask types. */
static void
check_load_store_masking (loop_vec_info loop_vinfo, tree vectype,
vec_load_store_type vls_type, int group_size,
vect_memory_access_type memory_access_type,
gather_scatter_info *gs_info, tree scalar_mask)
{
/* Invariant loads need no special support. */
if (memory_access_type == VMAT_INVARIANT)
return;
vec_loop_masks *masks = &LOOP_VINFO_MASKS (loop_vinfo);
machine_mode vecmode = TYPE_MODE (vectype);
bool is_load = (vls_type == VLS_LOAD);
if (memory_access_type == VMAT_LOAD_STORE_LANES)
{
if (is_load
? !vect_load_lanes_supported (vectype, group_size, true)
: !vect_store_lanes_supported (vectype, group_size, true))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"can't use a fully-masked loop because the"
" target doesn't have an appropriate masked"
" load/store-lanes instruction.\n");
LOOP_VINFO_CAN_FULLY_MASK_P (loop_vinfo) = false;
return;
}
unsigned int ncopies = vect_get_num_copies (loop_vinfo, vectype);
vect_record_loop_mask (loop_vinfo, masks, ncopies, vectype, scalar_mask);
return;
}
if (memory_access_type == VMAT_GATHER_SCATTER)
{
internal_fn ifn = (is_load
? IFN_MASK_GATHER_LOAD
: IFN_MASK_SCATTER_STORE);
if (!internal_gather_scatter_fn_supported_p (ifn, vectype,
gs_info->memory_type,
gs_info->offset_vectype,
gs_info->scale))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"can't use a fully-masked loop because the"
" target doesn't have an appropriate masked"
" gather load or scatter store instruction.\n");
LOOP_VINFO_CAN_FULLY_MASK_P (loop_vinfo) = false;
return;
}
unsigned int ncopies = vect_get_num_copies (loop_vinfo, vectype);
vect_record_loop_mask (loop_vinfo, masks, ncopies, vectype, scalar_mask);
return;
}
if (memory_access_type != VMAT_CONTIGUOUS
&& memory_access_type != VMAT_CONTIGUOUS_PERMUTE)
{
/* Element X of the data must come from iteration i * VF + X of the
scalar loop. We need more work to support other mappings. */
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"can't use a fully-masked loop because an access"
" isn't contiguous.\n");
LOOP_VINFO_CAN_FULLY_MASK_P (loop_vinfo) = false;
return;
}
machine_mode mask_mode;
if (!VECTOR_MODE_P (vecmode)
|| !targetm.vectorize.get_mask_mode (vecmode).exists (&mask_mode)
|| !can_vec_mask_load_store_p (vecmode, mask_mode, is_load))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"can't use a fully-masked loop because the target"
" doesn't have the appropriate masked load or"
" store.\n");
LOOP_VINFO_CAN_FULLY_MASK_P (loop_vinfo) = false;
return;
}
/* We might load more scalars than we need for permuting SLP loads.
We checked in get_group_load_store_type that the extra elements
don't leak into a new vector. */
poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
poly_uint64 vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
unsigned int nvectors;
if (can_div_away_from_zero_p (group_size * vf, nunits, &nvectors))
vect_record_loop_mask (loop_vinfo, masks, nvectors, vectype, scalar_mask);
else
gcc_unreachable ();
}
/* Return the mask input to a masked load or store. VEC_MASK is the vectorized
form of the scalar mask condition and LOOP_MASK, if nonnull, is the mask
that needs to be applied to all loads and stores in a vectorized loop.
Return VEC_MASK if LOOP_MASK is null, otherwise return VEC_MASK & LOOP_MASK.
MASK_TYPE is the type of both masks. If new statements are needed,
insert them before GSI. */
static tree
prepare_load_store_mask (tree mask_type, tree loop_mask, tree vec_mask,
gimple_stmt_iterator *gsi)
{
gcc_assert (useless_type_conversion_p (mask_type, TREE_TYPE (vec_mask)));
if (!loop_mask)
return vec_mask;
gcc_assert (TREE_TYPE (loop_mask) == mask_type);
tree and_res = make_temp_ssa_name (mask_type, NULL, "vec_mask_and");
gimple *and_stmt = gimple_build_assign (and_res, BIT_AND_EXPR,
vec_mask, loop_mask);
gsi_insert_before (gsi, and_stmt, GSI_SAME_STMT);
return and_res;
}
/* Determine whether we can use a gather load or scatter store to vectorize
strided load or store STMT_INFO by truncating the current offset to a
smaller width. We need to be able to construct an offset vector:
{ 0, X, X*2, X*3, ... }
without loss of precision, where X is STMT_INFO's DR_STEP.
Return true if this is possible, describing the gather load or scatter
store in GS_INFO. MASKED_P is true if the load or store is conditional. */
static bool
vect_truncate_gather_scatter_offset (stmt_vec_info stmt_info,
loop_vec_info loop_vinfo, bool masked_p,
gather_scatter_info *gs_info)
{
dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info);
data_reference *dr = dr_info->dr;
tree step = DR_STEP (dr);
if (TREE_CODE (step) != INTEGER_CST)
{
/* ??? Perhaps we could use range information here? */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"cannot truncate variable step.\n");
return false;
}
/* Get the number of bits in an element. */
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
scalar_mode element_mode = SCALAR_TYPE_MODE (TREE_TYPE (vectype));
unsigned int element_bits = GET_MODE_BITSIZE (element_mode);
/* Set COUNT to the upper limit on the number of elements - 1.
Start with the maximum vectorization factor. */
unsigned HOST_WIDE_INT count = vect_max_vf (loop_vinfo) - 1;
/* Try lowering COUNT to the number of scalar latch iterations. */
class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
widest_int max_iters;
if (max_loop_iterations (loop, &max_iters)
&& max_iters < count)
count = max_iters.to_shwi ();
/* Try scales of 1 and the element size. */
int scales[] = { 1, vect_get_scalar_dr_size (dr_info) };
wi::overflow_type overflow = wi::OVF_NONE;
for (int i = 0; i < 2; ++i)
{
int scale = scales[i];
widest_int factor;
if (!wi::multiple_of_p (wi::to_widest (step), scale, SIGNED, &factor))
continue;
/* Determine the minimum precision of (COUNT - 1) * STEP / SCALE. */
widest_int range = wi::mul (count, factor, SIGNED, &overflow);
if (overflow)
continue;
signop sign = range >= 0 ? UNSIGNED : SIGNED;
unsigned int min_offset_bits = wi::min_precision (range, sign);
/* Find the narrowest viable offset type. */
unsigned int offset_bits = 1U << ceil_log2 (min_offset_bits);
tree offset_type = build_nonstandard_integer_type (offset_bits,
sign == UNSIGNED);
/* See whether the target supports the operation with an offset
no narrower than OFFSET_TYPE. */
tree memory_type = TREE_TYPE (DR_REF (dr));
if (!vect_gather_scatter_fn_p (loop_vinfo, DR_IS_READ (dr), masked_p,
vectype, memory_type, offset_type, scale,
&gs_info->ifn, &gs_info->offset_vectype))
continue;
gs_info->decl = NULL_TREE;
/* Logically the sum of DR_BASE_ADDRESS, DR_INIT and DR_OFFSET,
but we don't need to store that here. */
gs_info->base = NULL_TREE;
gs_info->element_type = TREE_TYPE (vectype);
gs_info->offset = fold_convert (offset_type, step);
gs_info->offset_dt = vect_constant_def;
gs_info->scale = scale;
gs_info->memory_type = memory_type;
return true;
}
if (overflow && dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"truncating gather/scatter offset to %d bits"
" might change its value.\n", element_bits);
return false;
}
/* Return true if we can use gather/scatter internal functions to
vectorize STMT_INFO, which is a grouped or strided load or store.
MASKED_P is true if load or store is conditional. When returning
true, fill in GS_INFO with the information required to perform the
operation. */
static bool
vect_use_strided_gather_scatters_p (stmt_vec_info stmt_info,
loop_vec_info loop_vinfo, bool masked_p,
gather_scatter_info *gs_info)
{
if (!vect_check_gather_scatter (stmt_info, loop_vinfo, gs_info)
|| gs_info->decl)
return vect_truncate_gather_scatter_offset (stmt_info, loop_vinfo,
masked_p, gs_info);
tree old_offset_type = TREE_TYPE (gs_info->offset);
tree new_offset_type = TREE_TYPE (gs_info->offset_vectype);
gcc_assert (TYPE_PRECISION (new_offset_type)
>= TYPE_PRECISION (old_offset_type));
gs_info->offset = fold_convert (new_offset_type, gs_info->offset);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"using gather/scatter for strided/grouped access,"
" scale = %d\n", gs_info->scale);
return true;
}
/* STMT_INFO is a non-strided load or store, meaning that it accesses
elements with a known constant step. Return -1 if that step
is negative, 0 if it is zero, and 1 if it is greater than zero. */
static int
compare_step_with_zero (stmt_vec_info stmt_info)
{
dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info);
return tree_int_cst_compare (vect_dr_behavior (dr_info)->step,
size_zero_node);
}
/* If the target supports a permute mask that reverses the elements in
a vector of type VECTYPE, return that mask, otherwise return null. */
static tree
perm_mask_for_reverse (tree vectype)
{
poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
/* The encoding has a single stepped pattern. */
vec_perm_builder sel (nunits, 1, 3);
for (int i = 0; i < 3; ++i)
sel.quick_push (nunits - 1 - i);
vec_perm_indices indices (sel, 1, nunits);
if (!can_vec_perm_const_p (TYPE_MODE (vectype), indices))
return NULL_TREE;
return vect_gen_perm_mask_checked (vectype, indices);
}
/* A subroutine of get_load_store_type, with a subset of the same
arguments. Handle the case where STMT_INFO is a load or store that
accesses consecutive elements with a negative step. */
static vect_memory_access_type
get_negative_load_store_type (stmt_vec_info stmt_info, tree vectype,
vec_load_store_type vls_type,
unsigned int ncopies)
{
dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info);
dr_alignment_support alignment_support_scheme;
if (ncopies > 1)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"multiple types with negative step.\n");
return VMAT_ELEMENTWISE;
}
alignment_support_scheme = vect_supportable_dr_alignment (dr_info, false);
if (alignment_support_scheme != dr_aligned
&& alignment_support_scheme != dr_unaligned_supported)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"negative step but alignment required.\n");
return VMAT_ELEMENTWISE;
}
if (vls_type == VLS_STORE_INVARIANT)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"negative step with invariant source;"
" no permute needed.\n");
return VMAT_CONTIGUOUS_DOWN;
}
if (!perm_mask_for_reverse (vectype))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"negative step and reversing not supported.\n");
return VMAT_ELEMENTWISE;
}
return VMAT_CONTIGUOUS_REVERSE;
}
/* STMT_INFO is either a masked or unconditional store. Return the value
being stored. */
tree
vect_get_store_rhs (stmt_vec_info stmt_info)
{
if (gassign *assign = dyn_cast <gassign *> (stmt_info->stmt))
{
gcc_assert (gimple_assign_single_p (assign));
return gimple_assign_rhs1 (assign);
}
if (gcall *call = dyn_cast <gcall *> (stmt_info->stmt))
{
internal_fn ifn = gimple_call_internal_fn (call);
int index = internal_fn_stored_value_index (ifn);
gcc_assert (index >= 0);
return gimple_call_arg (call, index);
}
gcc_unreachable ();
}
/* Function VECTOR_VECTOR_COMPOSITION_TYPE
This function returns a vector type which can be composed with NETLS pieces,
whose type is recorded in PTYPE. VTYPE should be a vector type, and has the
same vector size as the return vector. It checks target whether supports
pieces-size vector mode for construction firstly, if target fails to, check
pieces-size scalar mode for construction further. It returns NULL_TREE if
fails to find the available composition.
For example, for (vtype=V16QI, nelts=4), we can probably get:
- V16QI with PTYPE V4QI.
- V4SI with PTYPE SI.
- NULL_TREE. */
static tree
vector_vector_composition_type (tree vtype, poly_uint64 nelts, tree *ptype)
{
gcc_assert (VECTOR_TYPE_P (vtype));
gcc_assert (known_gt (nelts, 0U));
machine_mode vmode = TYPE_MODE (vtype);
if (!VECTOR_MODE_P (vmode))
return NULL_TREE;
poly_uint64 vbsize = GET_MODE_BITSIZE (vmode);
unsigned int pbsize;
if (constant_multiple_p (vbsize, nelts, &pbsize))
{
/* First check if vec_init optab supports construction from
vector pieces directly. */
scalar_mode elmode = SCALAR_TYPE_MODE (TREE_TYPE (vtype));
poly_uint64 inelts = pbsize / GET_MODE_BITSIZE (elmode);
machine_mode rmode;
if (related_vector_mode (vmode, elmode, inelts).exists (&rmode)
&& (convert_optab_handler (vec_init_optab, vmode, rmode)
!= CODE_FOR_nothing))
{
*ptype = build_vector_type (TREE_TYPE (vtype), inelts);
return vtype;
}
/* Otherwise check if exists an integer type of the same piece size and
if vec_init optab supports construction from it directly. */
if (int_mode_for_size (pbsize, 0).exists (&elmode)
&& related_vector_mode (vmode, elmode, nelts).exists (&rmode)
&& (convert_optab_handler (vec_init_optab, rmode, elmode)
!= CODE_FOR_nothing))
{
*ptype = build_nonstandard_integer_type (pbsize, 1);
return build_vector_type (*ptype, nelts);
}
}
return NULL_TREE;
}
/* A subroutine of get_load_store_type, with a subset of the same
arguments. Handle the case where STMT_INFO is part of a grouped load
or store.
For stores, the statements in the group are all consecutive
and there is no gap at the end. For loads, the statements in the
group might not be consecutive; there can be gaps between statements
as well as at the end. */
static bool
get_group_load_store_type (stmt_vec_info stmt_info, tree vectype, bool slp,
bool masked_p, vec_load_store_type vls_type,
vect_memory_access_type *memory_access_type,
gather_scatter_info *gs_info)
{
vec_info *vinfo = stmt_info->vinfo;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
class loop *loop = loop_vinfo ? LOOP_VINFO_LOOP (loop_vinfo) : NULL;
stmt_vec_info first_stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
dr_vec_info *first_dr_info = STMT_VINFO_DR_INFO (first_stmt_info);
unsigned int group_size = DR_GROUP_SIZE (first_stmt_info);
bool single_element_p = (stmt_info == first_stmt_info
&& !DR_GROUP_NEXT_ELEMENT (stmt_info));
unsigned HOST_WIDE_INT gap = DR_GROUP_GAP (first_stmt_info);
poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
/* True if the vectorized statements would access beyond the last
statement in the group. */
bool overrun_p = false;
/* True if we can cope with such overrun by peeling for gaps, so that
there is at least one final scalar iteration after the vector loop. */
bool can_overrun_p = (!masked_p
&& vls_type == VLS_LOAD
&& loop_vinfo
&& !loop->inner);
/* There can only be a gap at the end of the group if the stride is
known at compile time. */
gcc_assert (!STMT_VINFO_STRIDED_P (first_stmt_info) || gap == 0);
/* Stores can't yet have gaps. */
gcc_assert (slp || vls_type == VLS_LOAD || gap == 0);
if (slp)
{
if (STMT_VINFO_STRIDED_P (first_stmt_info))
{
/* Try to use consecutive accesses of DR_GROUP_SIZE elements,
separated by the stride, until we have a complete vector.
Fall back to scalar accesses if that isn't possible. */
if (multiple_p (nunits, group_size))
*memory_access_type = VMAT_STRIDED_SLP;
else
*memory_access_type = VMAT_ELEMENTWISE;
}
else
{
overrun_p = loop_vinfo && gap != 0;
if (overrun_p && vls_type != VLS_LOAD)
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"Grouped store with gaps requires"
" non-consecutive accesses\n");
return false;
}
/* An overrun is fine if the trailing elements are smaller
than the alignment boundary B. Every vector access will
be a multiple of B and so we are guaranteed to access a
non-gap element in the same B-sized block. */
if (overrun_p
&& gap < (vect_known_alignment_in_bytes (first_dr_info)
/ vect_get_scalar_dr_size (first_dr_info)))
overrun_p = false;
/* If the gap splits the vector in half and the target
can do half-vector operations avoid the epilogue peeling
by simply loading half of the vector only. Usually
the construction with an upper zero half will be elided. */
dr_alignment_support alignment_support_scheme;
tree half_vtype;
if (overrun_p
&& !masked_p
&& (((alignment_support_scheme
= vect_supportable_dr_alignment (first_dr_info, false)))
== dr_aligned
|| alignment_support_scheme == dr_unaligned_supported)
&& known_eq (nunits, (group_size - gap) * 2)
&& known_eq (nunits, group_size)
&& (vector_vector_composition_type (vectype, 2, &half_vtype)
!= NULL_TREE))
overrun_p = false;
if (overrun_p && !can_overrun_p)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"Peeling for outer loop is not supported\n");
return false;
}
int cmp = compare_step_with_zero (stmt_info);
if (cmp < 0)
*memory_access_type = get_negative_load_store_type
(stmt_info, vectype, vls_type, 1);
else
{
gcc_assert (!loop_vinfo || cmp > 0);
*memory_access_type = VMAT_CONTIGUOUS;
}
}
}
else
{
/* We can always handle this case using elementwise accesses,
but see if something more efficient is available. */
*memory_access_type = VMAT_ELEMENTWISE;
/* If there is a gap at the end of the group then these optimizations
would access excess elements in the last iteration. */
bool would_overrun_p = (gap != 0);
/* An overrun is fine if the trailing elements are smaller than the
alignment boundary B. Every vector access will be a multiple of B
and so we are guaranteed to access a non-gap element in the
same B-sized block. */
if (would_overrun_p
&& !masked_p
&& gap < (vect_known_alignment_in_bytes (first_dr_info)
/ vect_get_scalar_dr_size (first_dr_info)))
would_overrun_p = false;
if (!STMT_VINFO_STRIDED_P (first_stmt_info)
&& (can_overrun_p || !would_overrun_p)
&& compare_step_with_zero (stmt_info) > 0)
{
/* First cope with the degenerate case of a single-element
vector. */
if (known_eq (TYPE_VECTOR_SUBPARTS (vectype), 1U))
;
/* Otherwise try using LOAD/STORE_LANES. */
else if (vls_type == VLS_LOAD
? vect_load_lanes_supported (vectype, group_size, masked_p)
: vect_store_lanes_supported (vectype, group_size,
masked_p))
{
*memory_access_type = VMAT_LOAD_STORE_LANES;
overrun_p = would_overrun_p;
}
/* If that fails, try using permuting loads. */
else if (vls_type == VLS_LOAD
? vect_grouped_load_supported (vectype, single_element_p,
group_size)
: vect_grouped_store_supported (vectype, group_size))
{
*memory_access_type = VMAT_CONTIGUOUS_PERMUTE;
overrun_p = would_overrun_p;
}
}
/* As a last resort, trying using a gather load or scatter store.
??? Although the code can handle all group sizes correctly,
it probably isn't a win to use separate strided accesses based
on nearby locations. Or, even if it's a win over scalar code,
it might not be a win over vectorizing at a lower VF, if that
allows us to use contiguous accesses. */
if (*memory_access_type == VMAT_ELEMENTWISE
&& single_element_p
&& loop_vinfo
&& vect_use_strided_gather_scatters_p (stmt_info, loop_vinfo,
masked_p, gs_info))
*memory_access_type = VMAT_GATHER_SCATTER;
}
if (vls_type != VLS_LOAD && first_stmt_info == stmt_info)
{
/* STMT is the leader of the group. Check the operands of all the
stmts of the group. */
stmt_vec_info next_stmt_info = DR_GROUP_NEXT_ELEMENT (stmt_info);
while (next_stmt_info)
{
tree op = vect_get_store_rhs (next_stmt_info);
enum vect_def_type dt;
if (!vect_is_simple_use (op, vinfo, &dt))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
next_stmt_info = DR_GROUP_NEXT_ELEMENT (next_stmt_info);
}
}
if (overrun_p)
{
gcc_assert (can_overrun_p);
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"Data access with gaps requires scalar "
"epilogue loop\n");
LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) = true;
}
return true;
}
/* Analyze load or store statement STMT_INFO of type VLS_TYPE. Return true
if there is a memory access type that the vectorized form can use,
storing it in *MEMORY_ACCESS_TYPE if so. If we decide to use gathers
or scatters, fill in GS_INFO accordingly.
SLP says whether we're performing SLP rather than loop vectorization.
MASKED_P is true if the statement is conditional on a vectorized mask.
VECTYPE is the vector type that the vectorized statements will use.
NCOPIES is the number of vector statements that will be needed. */
static bool
get_load_store_type (stmt_vec_info stmt_info, tree vectype, bool slp,
bool masked_p, vec_load_store_type vls_type,
unsigned int ncopies,
vect_memory_access_type *memory_access_type,
gather_scatter_info *gs_info)
{
vec_info *vinfo = stmt_info->vinfo;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
if (STMT_VINFO_GATHER_SCATTER_P (stmt_info))
{
*memory_access_type = VMAT_GATHER_SCATTER;
if (!vect_check_gather_scatter (stmt_info, loop_vinfo, gs_info))
gcc_unreachable ();
else if (!vect_is_simple_use (gs_info->offset, vinfo,
&gs_info->offset_dt,
&gs_info->offset_vectype))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"%s index use not simple.\n",
vls_type == VLS_LOAD ? "gather" : "scatter");
return false;
}
}
else if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
{
if (!get_group_load_store_type (stmt_info, vectype, slp, masked_p,
vls_type, memory_access_type, gs_info))
return false;
}
else if (STMT_VINFO_STRIDED_P (stmt_info))
{
gcc_assert (!slp);
if (loop_vinfo
&& vect_use_strided_gather_scatters_p (stmt_info, loop_vinfo,
masked_p, gs_info))
*memory_access_type = VMAT_GATHER_SCATTER;
else
*memory_access_type = VMAT_ELEMENTWISE;
}
else
{
int cmp = compare_step_with_zero (stmt_info);
if (cmp < 0)
*memory_access_type = get_negative_load_store_type
(stmt_info, vectype, vls_type, ncopies);
else if (cmp == 0)
{
gcc_assert (vls_type == VLS_LOAD);
*memory_access_type = VMAT_INVARIANT;
}
else
*memory_access_type = VMAT_CONTIGUOUS;
}
if ((*memory_access_type == VMAT_ELEMENTWISE
|| *memory_access_type == VMAT_STRIDED_SLP)
&& !nunits.is_constant ())
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"Not using elementwise accesses due to variable "
"vectorization factor.\n");
return false;
}
/* FIXME: At the moment the cost model seems to underestimate the
cost of using elementwise accesses. This check preserves the
traditional behavior until that can be fixed. */
stmt_vec_info first_stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
if (!first_stmt_info)
first_stmt_info = stmt_info;
if (*memory_access_type == VMAT_ELEMENTWISE
&& !STMT_VINFO_STRIDED_P (first_stmt_info)
&& !(stmt_info == DR_GROUP_FIRST_ELEMENT (stmt_info)
&& !DR_GROUP_NEXT_ELEMENT (stmt_info)
&& !pow2p_hwi (DR_GROUP_SIZE (stmt_info))))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not falling back to elementwise accesses\n");
return false;
}
return true;
}
/* Return true if boolean argument MASK is suitable for vectorizing
conditional operation STMT_INFO. When returning true, store the type
of the definition in *MASK_DT_OUT and the type of the vectorized mask
in *MASK_VECTYPE_OUT. */
static bool
vect_check_scalar_mask (stmt_vec_info stmt_info, tree mask,
vect_def_type *mask_dt_out,
tree *mask_vectype_out)
{
vec_info *vinfo = stmt_info->vinfo;
if (!VECT_SCALAR_BOOLEAN_TYPE_P (TREE_TYPE (mask)))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"mask argument is not a boolean.\n");
return false;
}
if (TREE_CODE (mask) != SSA_NAME)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"mask argument is not an SSA name.\n");
return false;
}
enum vect_def_type mask_dt;
tree mask_vectype;
if (!vect_is_simple_use (mask, stmt_info->vinfo, &mask_dt, &mask_vectype))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"mask use not simple.\n");
return false;
}
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
if (!mask_vectype)
mask_vectype = get_mask_type_for_scalar_type (vinfo, TREE_TYPE (vectype));
if (!mask_vectype || !VECTOR_BOOLEAN_TYPE_P (mask_vectype))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"could not find an appropriate vector mask type.\n");
return false;
}
if (maybe_ne (TYPE_VECTOR_SUBPARTS (mask_vectype),
TYPE_VECTOR_SUBPARTS (vectype)))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"vector mask type %T"
" does not match vector data type %T.\n",
mask_vectype, vectype);
return false;
}
*mask_dt_out = mask_dt;
*mask_vectype_out = mask_vectype;
return true;
}
/* Return true if stored value RHS is suitable for vectorizing store
statement STMT_INFO. When returning true, store the type of the
definition in *RHS_DT_OUT, the type of the vectorized store value in
*RHS_VECTYPE_OUT and the type of the store in *VLS_TYPE_OUT. */
static bool
vect_check_store_rhs (stmt_vec_info stmt_info, tree rhs,
vect_def_type *rhs_dt_out, tree *rhs_vectype_out,
vec_load_store_type *vls_type_out)
{
/* In the case this is a store from a constant make sure
native_encode_expr can handle it. */
if (CONSTANT_CLASS_P (rhs) && native_encode_expr (rhs, NULL, 64) == 0)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"cannot encode constant as a byte sequence.\n");
return false;
}
enum vect_def_type rhs_dt;
tree rhs_vectype;
if (!vect_is_simple_use (rhs, stmt_info->vinfo, &rhs_dt, &rhs_vectype))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
if (rhs_vectype && !useless_type_conversion_p (vectype, rhs_vectype))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"incompatible vector types.\n");
return false;
}
*rhs_dt_out = rhs_dt;
*rhs_vectype_out = rhs_vectype;
if (rhs_dt == vect_constant_def || rhs_dt == vect_external_def)
*vls_type_out = VLS_STORE_INVARIANT;
else
*vls_type_out = VLS_STORE;
return true;
}
/* Build an all-ones vector mask of type MASKTYPE while vectorizing STMT_INFO.
Note that we support masks with floating-point type, in which case the
floats are interpreted as a bitmask. */
static tree
vect_build_all_ones_mask (stmt_vec_info stmt_info, tree masktype)
{
if (TREE_CODE (masktype) == INTEGER_TYPE)
return build_int_cst (masktype, -1);
else if (TREE_CODE (TREE_TYPE (masktype)) == INTEGER_TYPE)
{
tree mask = build_int_cst (TREE_TYPE (masktype), -1);
mask = build_vector_from_val (masktype, mask);
return vect_init_vector (stmt_info, mask, masktype, NULL);
}
else if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (masktype)))
{
REAL_VALUE_TYPE r;
long tmp[6];
for (int j = 0; j < 6; ++j)
tmp[j] = -1;
real_from_target (&r, tmp, TYPE_MODE (TREE_TYPE (masktype)));
tree mask = build_real (TREE_TYPE (masktype), r);
mask = build_vector_from_val (masktype, mask);
return vect_init_vector (stmt_info, mask, masktype, NULL);
}
gcc_unreachable ();
}
/* Build an all-zero merge value of type VECTYPE while vectorizing
STMT_INFO as a gather load. */
static tree
vect_build_zero_merge_argument (stmt_vec_info stmt_info, tree vectype)
{
tree merge;
if (TREE_CODE (TREE_TYPE (vectype)) == INTEGER_TYPE)
merge = build_int_cst (TREE_TYPE (vectype), 0);
else if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (vectype)))
{
REAL_VALUE_TYPE r;
long tmp[6];
for (int j = 0; j < 6; ++j)
tmp[j] = 0;
real_from_target (&r, tmp, TYPE_MODE (TREE_TYPE (vectype)));
merge = build_real (TREE_TYPE (vectype), r);
}
else
gcc_unreachable ();
merge = build_vector_from_val (vectype, merge);
return vect_init_vector (stmt_info, merge, vectype, NULL);
}
/* Build a gather load call while vectorizing STMT_INFO. Insert new
instructions before GSI and add them to VEC_STMT. GS_INFO describes
the gather load operation. If the load is conditional, MASK is the
unvectorized condition and MASK_DT is its definition type, otherwise
MASK is null. */
static void
vect_build_gather_load_calls (stmt_vec_info stmt_info,
gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt,
gather_scatter_info *gs_info,
tree mask)
{
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
int ncopies = vect_get_num_copies (loop_vinfo, vectype);
edge pe = loop_preheader_edge (loop);
enum { NARROW, NONE, WIDEN } modifier;
poly_uint64 gather_off_nunits
= TYPE_VECTOR_SUBPARTS (gs_info->offset_vectype);
tree arglist = TYPE_ARG_TYPES (TREE_TYPE (gs_info->decl));
tree rettype = TREE_TYPE (TREE_TYPE (gs_info->decl));
tree srctype = TREE_VALUE (arglist); arglist = TREE_CHAIN (arglist);
tree ptrtype = TREE_VALUE (arglist); arglist = TREE_CHAIN (arglist);
tree idxtype = TREE_VALUE (arglist); arglist = TREE_CHAIN (arglist);
tree masktype = TREE_VALUE (arglist); arglist = TREE_CHAIN (arglist);
tree scaletype = TREE_VALUE (arglist);
tree real_masktype = masktype;
gcc_checking_assert (types_compatible_p (srctype, rettype)
&& (!mask
|| TREE_CODE (masktype) == INTEGER_TYPE
|| types_compatible_p (srctype, masktype)));
if (mask && TREE_CODE (masktype) == INTEGER_TYPE)
masktype = truth_type_for (srctype);
tree mask_halftype = masktype;
tree perm_mask = NULL_TREE;
tree mask_perm_mask = NULL_TREE;
if (known_eq (nunits, gather_off_nunits))
modifier = NONE;
else if (known_eq (nunits * 2, gather_off_nunits))
{
modifier = WIDEN;
/* Currently widening gathers and scatters are only supported for
fixed-length vectors. */
int count = gather_off_nunits.to_constant ();
vec_perm_builder sel (count, count, 1);
for (int i = 0; i < count; ++i)
sel.quick_push (i | (count / 2));
vec_perm_indices indices (sel, 1, count);
perm_mask = vect_gen_perm_mask_checked (gs_info->offset_vectype,
indices);
}
else if (known_eq (nunits, gather_off_nunits * 2))
{
modifier = NARROW;
/* Currently narrowing gathers and scatters are only supported for
fixed-length vectors. */
int count = nunits.to_constant ();
vec_perm_builder sel (count, count, 1);
sel.quick_grow (count);
for (int i = 0; i < count; ++i)
sel[i] = i < count / 2 ? i : i + count / 2;
vec_perm_indices indices (sel, 2, count);
perm_mask = vect_gen_perm_mask_checked (vectype, indices);
ncopies *= 2;
if (mask && masktype == real_masktype)
{
for (int i = 0; i < count; ++i)
sel[i] = i | (count / 2);
indices.new_vector (sel, 2, count);
mask_perm_mask = vect_gen_perm_mask_checked (masktype, indices);
}
else if (mask)
mask_halftype = truth_type_for (gs_info->offset_vectype);
}
else
gcc_unreachable ();
tree scalar_dest = gimple_get_lhs (stmt_info->stmt);
tree vec_dest = vect_create_destination_var (scalar_dest, vectype);
tree ptr = fold_convert (ptrtype, gs_info->base);
if (!is_gimple_min_invariant (ptr))
{
gimple_seq seq;
ptr = force_gimple_operand (ptr, &seq, true, NULL_TREE);
basic_block new_bb = gsi_insert_seq_on_edge_immediate (pe, seq);
gcc_assert (!new_bb);
}
tree scale = build_int_cst (scaletype, gs_info->scale);
tree vec_oprnd0 = NULL_TREE;
tree vec_mask = NULL_TREE;
tree src_op = NULL_TREE;
tree mask_op = NULL_TREE;
tree prev_res = NULL_TREE;
stmt_vec_info prev_stmt_info = NULL;
if (!mask)
{
src_op = vect_build_zero_merge_argument (stmt_info, rettype);
mask_op = vect_build_all_ones_mask (stmt_info, masktype);
}
for (int j = 0; j < ncopies; ++j)
{
tree op, var;
if (modifier == WIDEN && (j & 1))
op = permute_vec_elements (vec_oprnd0, vec_oprnd0,
perm_mask, stmt_info, gsi);
else if (j == 0)
op = vec_oprnd0
= vect_get_vec_def_for_operand (gs_info->offset, stmt_info);
else
op = vec_oprnd0 = vect_get_vec_def_for_stmt_copy (loop_vinfo,
vec_oprnd0);
if (!useless_type_conversion_p (idxtype, TREE_TYPE (op)))
{
gcc_assert (known_eq (TYPE_VECTOR_SUBPARTS (TREE_TYPE (op)),
TYPE_VECTOR_SUBPARTS (idxtype)));
var = vect_get_new_ssa_name (idxtype, vect_simple_var);
op = build1 (VIEW_CONVERT_EXPR, idxtype, op);
gassign *new_stmt = gimple_build_assign (var, VIEW_CONVERT_EXPR, op);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
op = var;
}
if (mask)
{
if (mask_perm_mask && (j & 1))
mask_op = permute_vec_elements (mask_op, mask_op,
mask_perm_mask, stmt_info, gsi);
else
{
if (j == 0)
vec_mask = vect_get_vec_def_for_operand (mask, stmt_info);
else if (modifier != NARROW || (j & 1) == 0)
vec_mask = vect_get_vec_def_for_stmt_copy (loop_vinfo,
vec_mask);
mask_op = vec_mask;
if (!useless_type_conversion_p (masktype, TREE_TYPE (vec_mask)))
{
poly_uint64 sub1 = TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask_op));
poly_uint64 sub2 = TYPE_VECTOR_SUBPARTS (masktype);
gcc_assert (known_eq (sub1, sub2));
var = vect_get_new_ssa_name (masktype, vect_simple_var);
mask_op = build1 (VIEW_CONVERT_EXPR, masktype, mask_op);
gassign *new_stmt
= gimple_build_assign (var, VIEW_CONVERT_EXPR, mask_op);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
mask_op = var;
}
}
if (modifier == NARROW && masktype != real_masktype)
{
var = vect_get_new_ssa_name (mask_halftype, vect_simple_var);
gassign *new_stmt
= gimple_build_assign (var, (j & 1) ? VEC_UNPACK_HI_EXPR
: VEC_UNPACK_LO_EXPR,
mask_op);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
mask_op = var;
}
src_op = mask_op;
}
tree mask_arg = mask_op;
if (masktype != real_masktype)
{
tree utype, optype = TREE_TYPE (mask_op);
if (TYPE_MODE (real_masktype) == TYPE_MODE (optype))
utype = real_masktype;
else
utype = lang_hooks.types.type_for_mode (TYPE_MODE (optype), 1);
var = vect_get_new_ssa_name (utype, vect_scalar_var);
mask_arg = build1 (VIEW_CONVERT_EXPR, utype, mask_op);
gassign *new_stmt
= gimple_build_assign (var, VIEW_CONVERT_EXPR, mask_arg);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
mask_arg = var;
if (!useless_type_conversion_p (real_masktype, utype))
{
gcc_assert (TYPE_PRECISION (utype)
<= TYPE_PRECISION (real_masktype));
var = vect_get_new_ssa_name (real_masktype, vect_scalar_var);
new_stmt = gimple_build_assign (var, NOP_EXPR, mask_arg);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
mask_arg = var;
}
src_op = build_zero_cst (srctype);
}
gcall *new_call = gimple_build_call (gs_info->decl, 5, src_op, ptr, op,
mask_arg, scale);
stmt_vec_info new_stmt_info;
if (!useless_type_conversion_p (vectype, rettype))
{
gcc_assert (known_eq (TYPE_VECTOR_SUBPARTS (vectype),
TYPE_VECTOR_SUBPARTS (rettype)));
op = vect_get_new_ssa_name (rettype, vect_simple_var);
gimple_call_set_lhs (new_call, op);
vect_finish_stmt_generation (stmt_info, new_call, gsi);
var = make_ssa_name (vec_dest);
op = build1 (VIEW_CONVERT_EXPR, vectype, op);
gassign *new_stmt = gimple_build_assign (var, VIEW_CONVERT_EXPR, op);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
else
{
var = make_ssa_name (vec_dest, new_call);
gimple_call_set_lhs (new_call, var);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_call, gsi);
}
if (modifier == NARROW)
{
if ((j & 1) == 0)
{
prev_res = var;
continue;
}
var = permute_vec_elements (prev_res, var, perm_mask,
stmt_info, gsi);
new_stmt_info = loop_vinfo->lookup_def (var);
}
if (prev_stmt_info == NULL)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
}
/* Prepare the base and offset in GS_INFO for vectorization.
Set *DATAREF_PTR to the loop-invariant base address and *VEC_OFFSET
to the vectorized offset argument for the first copy of STMT_INFO.
STMT_INFO is the statement described by GS_INFO and LOOP is the
containing loop. */
static void
vect_get_gather_scatter_ops (class loop *loop, stmt_vec_info stmt_info,
gather_scatter_info *gs_info,
tree *dataref_ptr, tree *vec_offset)
{
gimple_seq stmts = NULL;
*dataref_ptr = force_gimple_operand (gs_info->base, &stmts, true, NULL_TREE);
if (stmts != NULL)
{
basic_block new_bb;
edge pe = loop_preheader_edge (loop);
new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
gcc_assert (!new_bb);
}
*vec_offset = vect_get_vec_def_for_operand (gs_info->offset, stmt_info,
gs_info->offset_vectype);
}
/* Prepare to implement a grouped or strided load or store using
the gather load or scatter store operation described by GS_INFO.
STMT_INFO is the load or store statement.
Set *DATAREF_BUMP to the amount that should be added to the base
address after each copy of the vectorized statement. Set *VEC_OFFSET
to an invariant offset vector in which element I has the value
I * DR_STEP / SCALE. */
static void
vect_get_strided_load_store_ops (stmt_vec_info stmt_info,
loop_vec_info loop_vinfo,
gather_scatter_info *gs_info,
tree *dataref_bump, tree *vec_offset)
{
struct data_reference *dr = STMT_VINFO_DATA_REF (stmt_info);
class loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
gimple_seq stmts;
tree bump = size_binop (MULT_EXPR,
fold_convert (sizetype, unshare_expr (DR_STEP (dr))),
size_int (TYPE_VECTOR_SUBPARTS (vectype)));
*dataref_bump = force_gimple_operand (bump, &stmts, true, NULL_TREE);
if (stmts)
gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
/* The offset given in GS_INFO can have pointer type, so use the element
type of the vector instead. */
tree offset_type = TREE_TYPE (gs_info->offset);
offset_type = TREE_TYPE (gs_info->offset_vectype);
/* Calculate X = DR_STEP / SCALE and convert it to the appropriate type. */
tree step = size_binop (EXACT_DIV_EXPR, unshare_expr (DR_STEP (dr)),
ssize_int (gs_info->scale));
step = fold_convert (offset_type, step);
step = force_gimple_operand (step, &stmts, true, NULL_TREE);
/* Create {0, X, X*2, X*3, ...}. */
*vec_offset = gimple_build (&stmts, VEC_SERIES_EXPR, gs_info->offset_vectype,
build_zero_cst (offset_type), step);
if (stmts)
gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
}
/* Return the amount that should be added to a vector pointer to move
to the next or previous copy of AGGR_TYPE. DR_INFO is the data reference
being vectorized and MEMORY_ACCESS_TYPE describes the type of
vectorization. */
static tree
vect_get_data_ptr_increment (dr_vec_info *dr_info, tree aggr_type,
vect_memory_access_type memory_access_type)
{
if (memory_access_type == VMAT_INVARIANT)
return size_zero_node;
tree iv_step = TYPE_SIZE_UNIT (aggr_type);
tree step = vect_dr_behavior (dr_info)->step;
if (tree_int_cst_sgn (step) == -1)
iv_step = fold_build1 (NEGATE_EXPR, TREE_TYPE (iv_step), iv_step);
return iv_step;
}
/* Check and perform vectorization of BUILT_IN_BSWAP{16,32,64}. */
static bool
vectorizable_bswap (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt, slp_tree slp_node,
tree vectype_in, stmt_vector_for_cost *cost_vec)
{
tree op, vectype;
gcall *stmt = as_a <gcall *> (stmt_info->stmt);
vec_info *vinfo = stmt_info->vinfo;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
unsigned ncopies;
op = gimple_call_arg (stmt, 0);
vectype = STMT_VINFO_VECTYPE (stmt_info);
poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
/* Multiple types in SLP are handled by creating the appropriate number of
vectorized stmts for each SLP node. Hence, NCOPIES is always 1 in
case of SLP. */
if (slp_node)
ncopies = 1;
else
ncopies = vect_get_num_copies (loop_vinfo, vectype);
gcc_assert (ncopies >= 1);
tree char_vectype = get_same_sized_vectype (char_type_node, vectype_in);
if (! char_vectype)
return false;
poly_uint64 num_bytes = TYPE_VECTOR_SUBPARTS (char_vectype);
unsigned word_bytes;
if (!constant_multiple_p (num_bytes, nunits, &word_bytes))
return false;
/* The encoding uses one stepped pattern for each byte in the word. */
vec_perm_builder elts (num_bytes, word_bytes, 3);
for (unsigned i = 0; i < 3; ++i)
for (unsigned j = 0; j < word_bytes; ++j)
elts.quick_push ((i + 1) * word_bytes - j - 1);
vec_perm_indices indices (elts, 1, num_bytes);
if (!can_vec_perm_const_p (TYPE_MODE (char_vectype), indices))
return false;
if (! vec_stmt)
{
STMT_VINFO_TYPE (stmt_info) = call_vec_info_type;
DUMP_VECT_SCOPE ("vectorizable_bswap");
if (! slp_node)
{
record_stmt_cost (cost_vec,
1, vector_stmt, stmt_info, 0, vect_prologue);
record_stmt_cost (cost_vec,
ncopies, vec_perm, stmt_info, 0, vect_body);
}
return true;
}
tree bswap_vconst = vec_perm_indices_to_tree (char_vectype, indices);
/* Transform. */
vec<tree> vec_oprnds = vNULL;
stmt_vec_info new_stmt_info = NULL;
stmt_vec_info prev_stmt_info = NULL;
for (unsigned j = 0; j < ncopies; j++)
{
/* Handle uses. */
if (j == 0)
vect_get_vec_defs (op, NULL, stmt_info, &vec_oprnds, NULL, slp_node);
else
vect_get_vec_defs_for_stmt_copy (vinfo, &vec_oprnds, NULL);
/* Arguments are ready. create the new vector stmt. */
unsigned i;
tree vop;
FOR_EACH_VEC_ELT (vec_oprnds, i, vop)
{
gimple *new_stmt;
tree tem = make_ssa_name (char_vectype);
new_stmt = gimple_build_assign (tem, build1 (VIEW_CONVERT_EXPR,
char_vectype, vop));
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
tree tem2 = make_ssa_name (char_vectype);
new_stmt = gimple_build_assign (tem2, VEC_PERM_EXPR,
tem, tem, bswap_vconst);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
tem = make_ssa_name (vectype);
new_stmt = gimple_build_assign (tem, build1 (VIEW_CONVERT_EXPR,
vectype, tem2));
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (slp_node)
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
}
if (slp_node)
continue;
if (j == 0)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
vec_oprnds.release ();
return true;
}
/* Return true if vector types VECTYPE_IN and VECTYPE_OUT have
integer elements and if we can narrow VECTYPE_IN to VECTYPE_OUT
in a single step. On success, store the binary pack code in
*CONVERT_CODE. */
static bool
simple_integer_narrowing (tree vectype_out, tree vectype_in,
tree_code *convert_code)
{
if (!INTEGRAL_TYPE_P (TREE_TYPE (vectype_out))
|| !INTEGRAL_TYPE_P (TREE_TYPE (vectype_in)))
return false;
tree_code code;
int multi_step_cvt = 0;
auto_vec <tree, 8> interm_types;
if (!supportable_narrowing_operation (NOP_EXPR, vectype_out, vectype_in,
&code, &multi_step_cvt, &interm_types)
|| multi_step_cvt)
return false;
*convert_code = code;
return true;
}
/* Function vectorizable_call.
Check if STMT_INFO performs a function call that can be vectorized.
If VEC_STMT is also passed, vectorize STMT_INFO: create a vectorized
stmt to replace it, put it in VEC_STMT, and insert it at GSI.
Return true if STMT_INFO is vectorizable in this way. */
static bool
vectorizable_call (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt, slp_tree slp_node,
stmt_vector_for_cost *cost_vec)
{
gcall *stmt;
tree vec_dest;
tree scalar_dest;
tree op;
tree vec_oprnd0 = NULL_TREE, vec_oprnd1 = NULL_TREE;
stmt_vec_info prev_stmt_info;
tree vectype_out, vectype_in;
poly_uint64 nunits_in;
poly_uint64 nunits_out;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
vec_info *vinfo = stmt_info->vinfo;
tree fndecl, new_temp, rhs_type;
enum vect_def_type dt[4]
= { vect_unknown_def_type, vect_unknown_def_type, vect_unknown_def_type,
vect_unknown_def_type };
tree vectypes[ARRAY_SIZE (dt)] = {};
int ndts = ARRAY_SIZE (dt);
int ncopies, j;
auto_vec<tree, 8> vargs;
auto_vec<tree, 8> orig_vargs;
enum { NARROW, NONE, WIDEN } modifier;
size_t i, nargs;
tree lhs;
if (!STMT_VINFO_RELEVANT_P (stmt_info) && !bb_vinfo)
return false;
if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def
&& ! vec_stmt)
return false;
/* Is STMT_INFO a vectorizable call? */
stmt = dyn_cast <gcall *> (stmt_info->stmt);
if (!stmt)
return false;
if (gimple_call_internal_p (stmt)
&& (internal_load_fn_p (gimple_call_internal_fn (stmt))
|| internal_store_fn_p (gimple_call_internal_fn (stmt))))
/* Handled by vectorizable_load and vectorizable_store. */
return false;
if (gimple_call_lhs (stmt) == NULL_TREE
|| TREE_CODE (gimple_call_lhs (stmt)) != SSA_NAME)
return false;
gcc_checking_assert (!stmt_can_throw_internal (cfun, stmt));
vectype_out = STMT_VINFO_VECTYPE (stmt_info);
/* Process function arguments. */
rhs_type = NULL_TREE;
vectype_in = NULL_TREE;
nargs = gimple_call_num_args (stmt);
/* Bail out if the function has more than three arguments, we do not have
interesting builtin functions to vectorize with more than two arguments
except for fma. No arguments is also not good. */
if (nargs == 0 || nargs > 4)
return false;
/* Ignore the arguments of IFN_GOMP_SIMD_LANE, they are magic. */
combined_fn cfn = gimple_call_combined_fn (stmt);
if (cfn == CFN_GOMP_SIMD_LANE)
{
nargs = 0;
rhs_type = unsigned_type_node;
}
int mask_opno = -1;
if (internal_fn_p (cfn))
mask_opno = internal_fn_mask_index (as_internal_fn (cfn));
for (i = 0; i < nargs; i++)
{
op = gimple_call_arg (stmt, i);
if ((int) i == mask_opno)
{
if (!vect_check_scalar_mask (stmt_info, op, &dt[i], &vectypes[i]))
return false;
continue;
}
if (!vect_is_simple_use (op, vinfo, &dt[i], &vectypes[i]))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
/* We can only handle calls with arguments of the same type. */
if (rhs_type
&& !types_compatible_p (rhs_type, TREE_TYPE (op)))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"argument types differ.\n");
return false;
}
if (!rhs_type)
rhs_type = TREE_TYPE (op);
if (!vectype_in)
vectype_in = vectypes[i];
else if (vectypes[i]
&& !types_compatible_p (vectypes[i], vectype_in))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"argument vector types differ.\n");
return false;
}
}
/* If all arguments are external or constant defs, infer the vector type
from the scalar type. */
if (!vectype_in)
vectype_in = get_vectype_for_scalar_type (vinfo, rhs_type, slp_node);
if (vec_stmt)
gcc_assert (vectype_in);
if (!vectype_in)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"no vectype for scalar type %T\n", rhs_type);
return false;
}
/* FORNOW: we don't yet support mixtures of vector sizes for calls,
just mixtures of nunits. E.g. DI->SI versions of __builtin_ctz*
are traditionally vectorized as two VnDI->VnDI IFN_CTZs followed
by a pack of the two vectors into an SI vector. We would need
separate code to handle direct VnDI->VnSI IFN_CTZs. */
if (TYPE_SIZE (vectype_in) != TYPE_SIZE (vectype_out))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"mismatched vector sizes %T and %T\n",
vectype_in, vectype_out);
return false;
}
if (VECTOR_BOOLEAN_TYPE_P (vectype_out)
!= VECTOR_BOOLEAN_TYPE_P (vectype_in))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"mixed mask and nonmask vector types\n");
return false;
}
/* FORNOW */
nunits_in = TYPE_VECTOR_SUBPARTS (vectype_in);
nunits_out = TYPE_VECTOR_SUBPARTS (vectype_out);
if (known_eq (nunits_in * 2, nunits_out))
modifier = NARROW;
else if (known_eq (nunits_out, nunits_in))
modifier = NONE;
else if (known_eq (nunits_out * 2, nunits_in))
modifier = WIDEN;
else
return false;
/* We only handle functions that do not read or clobber memory. */
if (gimple_vuse (stmt))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"function reads from or writes to memory.\n");
return false;
}
/* For now, we only vectorize functions if a target specific builtin
is available. TODO -- in some cases, it might be profitable to
insert the calls for pieces of the vector, in order to be able
to vectorize other operations in the loop. */
fndecl = NULL_TREE;
internal_fn ifn = IFN_LAST;
tree callee = gimple_call_fndecl (stmt);
/* First try using an internal function. */
tree_code convert_code = ERROR_MARK;
if (cfn != CFN_LAST
&& (modifier == NONE
|| (modifier == NARROW
&& simple_integer_narrowing (vectype_out, vectype_in,
&convert_code))))
ifn = vectorizable_internal_function (cfn, callee, vectype_out,
vectype_in);
/* If that fails, try asking for a target-specific built-in function. */
if (ifn == IFN_LAST)
{
if (cfn != CFN_LAST)
fndecl = targetm.vectorize.builtin_vectorized_function
(cfn, vectype_out, vectype_in);
else if (callee && fndecl_built_in_p (callee, BUILT_IN_MD))
fndecl = targetm.vectorize.builtin_md_vectorized_function
(callee, vectype_out, vectype_in);
}
if (ifn == IFN_LAST && !fndecl)
{
if (cfn == CFN_GOMP_SIMD_LANE
&& !slp_node
&& loop_vinfo
&& LOOP_VINFO_LOOP (loop_vinfo)->simduid
&& TREE_CODE (gimple_call_arg (stmt, 0)) == SSA_NAME
&& LOOP_VINFO_LOOP (loop_vinfo)->simduid
== SSA_NAME_VAR (gimple_call_arg (stmt, 0)))
{
/* We can handle IFN_GOMP_SIMD_LANE by returning a
{ 0, 1, 2, ... vf - 1 } vector. */
gcc_assert (nargs == 0);
}
else if (modifier == NONE
&& (gimple_call_builtin_p (stmt, BUILT_IN_BSWAP16)
|| gimple_call_builtin_p (stmt, BUILT_IN_BSWAP32)
|| gimple_call_builtin_p (stmt, BUILT_IN_BSWAP64)))
return vectorizable_bswap (stmt_info, gsi, vec_stmt, slp_node,
vectype_in, cost_vec);
else
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"function is not vectorizable.\n");
return false;
}
}
if (slp_node)
ncopies = 1;
else if (modifier == NARROW && ifn == IFN_LAST)
ncopies = vect_get_num_copies (loop_vinfo, vectype_out);
else
ncopies = vect_get_num_copies (loop_vinfo, vectype_in);
/* Sanity check: make sure that at least one copy of the vectorized stmt
needs to be generated. */
gcc_assert (ncopies >= 1);
vec_loop_masks *masks = (loop_vinfo ? &LOOP_VINFO_MASKS (loop_vinfo) : NULL);
if (!vec_stmt) /* transformation not required. */
{
STMT_VINFO_TYPE (stmt_info) = call_vec_info_type;
DUMP_VECT_SCOPE ("vectorizable_call");
vect_model_simple_cost (stmt_info, ncopies, dt, ndts, slp_node, cost_vec);
if (ifn != IFN_LAST && modifier == NARROW && !slp_node)
record_stmt_cost (cost_vec, ncopies / 2,
vec_promote_demote, stmt_info, 0, vect_body);
if (loop_vinfo && mask_opno >= 0)
{
unsigned int nvectors = (slp_node
? SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node)
: ncopies);
tree scalar_mask = gimple_call_arg (stmt_info->stmt, mask_opno);
vect_record_loop_mask (loop_vinfo, masks, nvectors,
vectype_out, scalar_mask);
}
return true;
}
/* Transform. */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location, "transform call.\n");
/* Handle def. */
scalar_dest = gimple_call_lhs (stmt);
vec_dest = vect_create_destination_var (scalar_dest, vectype_out);
bool masked_loop_p = loop_vinfo && LOOP_VINFO_FULLY_MASKED_P (loop_vinfo);
stmt_vec_info new_stmt_info = NULL;
prev_stmt_info = NULL;
if (modifier == NONE || ifn != IFN_LAST)
{
tree prev_res = NULL_TREE;
vargs.safe_grow (nargs);
orig_vargs.safe_grow (nargs);
for (j = 0; j < ncopies; ++j)
{
/* Build argument list for the vectorized call. */
if (slp_node)
{
auto_vec<vec<tree> > vec_defs (nargs);
vec<tree> vec_oprnds0;
vect_get_slp_defs (slp_node, &vec_defs);
vec_oprnds0 = vec_defs[0];
/* Arguments are ready. Create the new vector stmt. */
FOR_EACH_VEC_ELT (vec_oprnds0, i, vec_oprnd0)
{
size_t k;
for (k = 0; k < nargs; k++)
{
vec<tree> vec_oprndsk = vec_defs[k];
vargs[k] = vec_oprndsk[i];
}
if (modifier == NARROW)
{
/* We don't define any narrowing conditional functions
at present. */
gcc_assert (mask_opno < 0);
tree half_res = make_ssa_name (vectype_in);
gcall *call
= gimple_build_call_internal_vec (ifn, vargs);
gimple_call_set_lhs (call, half_res);
gimple_call_set_nothrow (call, true);
vect_finish_stmt_generation (stmt_info, call, gsi);
if ((i & 1) == 0)
{
prev_res = half_res;
continue;
}
new_temp = make_ssa_name (vec_dest);
gimple *new_stmt
= gimple_build_assign (new_temp, convert_code,
prev_res, half_res);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt,
gsi);
}
else
{
if (mask_opno >= 0 && masked_loop_p)
{
unsigned int vec_num = vec_oprnds0.length ();
/* Always true for SLP. */
gcc_assert (ncopies == 1);
tree mask = vect_get_loop_mask (gsi, masks, vec_num,
vectype_out, i);
vargs[mask_opno] = prepare_load_store_mask
(TREE_TYPE (mask), mask, vargs[mask_opno], gsi);
}
gcall *call;
if (ifn != IFN_LAST)
call = gimple_build_call_internal_vec (ifn, vargs);
else
call = gimple_build_call_vec (fndecl, vargs);
new_temp = make_ssa_name (vec_dest, call);
gimple_call_set_lhs (call, new_temp);
gimple_call_set_nothrow (call, true);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, call, gsi);
}
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
}
for (i = 0; i < nargs; i++)
{
vec<tree> vec_oprndsi = vec_defs[i];
vec_oprndsi.release ();
}
continue;
}
for (i = 0; i < nargs; i++)
{
op = gimple_call_arg (stmt, i);
if (j == 0)
vec_oprnd0
= vect_get_vec_def_for_operand (op, stmt_info, vectypes[i]);
else
vec_oprnd0
= vect_get_vec_def_for_stmt_copy (vinfo, orig_vargs[i]);
orig_vargs[i] = vargs[i] = vec_oprnd0;
}
if (mask_opno >= 0 && masked_loop_p)
{
tree mask = vect_get_loop_mask (gsi, masks, ncopies,
vectype_out, j);
vargs[mask_opno]
= prepare_load_store_mask (TREE_TYPE (mask), mask,
vargs[mask_opno], gsi);
}
if (cfn == CFN_GOMP_SIMD_LANE)
{
tree cst = build_index_vector (vectype_out, j * nunits_out, 1);
tree new_var
= vect_get_new_ssa_name (vectype_out, vect_simple_var, "cst_");
gimple *init_stmt = gimple_build_assign (new_var, cst);
vect_init_vector_1 (stmt_info, init_stmt, NULL);
new_temp = make_ssa_name (vec_dest);
gimple *new_stmt = gimple_build_assign (new_temp, new_var);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
else if (modifier == NARROW)
{
/* We don't define any narrowing conditional functions at
present. */
gcc_assert (mask_opno < 0);
tree half_res = make_ssa_name (vectype_in);
gcall *call = gimple_build_call_internal_vec (ifn, vargs);
gimple_call_set_lhs (call, half_res);
gimple_call_set_nothrow (call, true);
vect_finish_stmt_generation (stmt_info, call, gsi);
if ((j & 1) == 0)
{
prev_res = half_res;
continue;
}
new_temp = make_ssa_name (vec_dest);
gassign *new_stmt = gimple_build_assign (new_temp, convert_code,
prev_res, half_res);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
else
{
gcall *call;
if (ifn != IFN_LAST)
call = gimple_build_call_internal_vec (ifn, vargs);
else
call = gimple_build_call_vec (fndecl, vargs);
new_temp = make_ssa_name (vec_dest, call);
gimple_call_set_lhs (call, new_temp);
gimple_call_set_nothrow (call, true);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, call, gsi);
}
if (j == (modifier == NARROW ? 1 : 0))
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
}
else if (modifier == NARROW)
{
/* We don't define any narrowing conditional functions at present. */
gcc_assert (mask_opno < 0);
for (j = 0; j < ncopies; ++j)
{
/* Build argument list for the vectorized call. */
if (j == 0)
vargs.create (nargs * 2);
else
vargs.truncate (0);
if (slp_node)
{
auto_vec<vec<tree> > vec_defs (nargs);
vec<tree> vec_oprnds0;
vect_get_slp_defs (slp_node, &vec_defs);
vec_oprnds0 = vec_defs[0];
/* Arguments are ready. Create the new vector stmt. */
for (i = 0; vec_oprnds0.iterate (i, &vec_oprnd0); i += 2)
{
size_t k;
vargs.truncate (0);
for (k = 0; k < nargs; k++)
{
vec<tree> vec_oprndsk = vec_defs[k];
vargs.quick_push (vec_oprndsk[i]);
vargs.quick_push (vec_oprndsk[i + 1]);
}
gcall *call;
if (ifn != IFN_LAST)
call = gimple_build_call_internal_vec (ifn, vargs);
else
call = gimple_build_call_vec (fndecl, vargs);
new_temp = make_ssa_name (vec_dest, call);
gimple_call_set_lhs (call, new_temp);
gimple_call_set_nothrow (call, true);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, call, gsi);
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
}
for (i = 0; i < nargs; i++)
{
vec<tree> vec_oprndsi = vec_defs[i];
vec_oprndsi.release ();
}
continue;
}
for (i = 0; i < nargs; i++)
{
op = gimple_call_arg (stmt, i);
if (j == 0)
{
vec_oprnd0
= vect_get_vec_def_for_operand (op, stmt_info,
vectypes[i]);
vec_oprnd1
= vect_get_vec_def_for_stmt_copy (vinfo, vec_oprnd0);
}
else
{
vec_oprnd1 = gimple_call_arg (new_stmt_info->stmt,
2 * i + 1);
vec_oprnd0
= vect_get_vec_def_for_stmt_copy (vinfo, vec_oprnd1);
vec_oprnd1
= vect_get_vec_def_for_stmt_copy (vinfo, vec_oprnd0);
}
vargs.quick_push (vec_oprnd0);
vargs.quick_push (vec_oprnd1);
}
gcall *new_stmt = gimple_build_call_vec (fndecl, vargs);
new_temp = make_ssa_name (vec_dest, new_stmt);
gimple_call_set_lhs (new_stmt, new_temp);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (j == 0)
STMT_VINFO_VEC_STMT (stmt_info) = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
*vec_stmt = STMT_VINFO_VEC_STMT (stmt_info);
}
else
/* No current target implements this case. */
return false;
vargs.release ();
/* The call in STMT might prevent it from being removed in dce.
We however cannot remove it here, due to the way the ssa name
it defines is mapped to the new definition. So just replace
rhs of the statement with something harmless. */
if (slp_node)
return true;
stmt_info = vect_orig_stmt (stmt_info);
lhs = gimple_get_lhs (stmt_info->stmt);
gassign *new_stmt
= gimple_build_assign (lhs, build_zero_cst (TREE_TYPE (lhs)));
vinfo->replace_stmt (gsi, stmt_info, new_stmt);
return true;
}
struct simd_call_arg_info
{
tree vectype;
tree op;
HOST_WIDE_INT linear_step;
enum vect_def_type dt;
unsigned int align;
bool simd_lane_linear;
};
/* Helper function of vectorizable_simd_clone_call. If OP, an SSA_NAME,
is linear within simd lane (but not within whole loop), note it in
*ARGINFO. */
static void
vect_simd_lane_linear (tree op, class loop *loop,
struct simd_call_arg_info *arginfo)
{
gimple *def_stmt = SSA_NAME_DEF_STMT (op);
if (!is_gimple_assign (def_stmt)
|| gimple_assign_rhs_code (def_stmt) != POINTER_PLUS_EXPR
|| !is_gimple_min_invariant (gimple_assign_rhs1 (def_stmt)))
return;
tree base = gimple_assign_rhs1 (def_stmt);
HOST_WIDE_INT linear_step = 0;
tree v = gimple_assign_rhs2 (def_stmt);
while (TREE_CODE (v) == SSA_NAME)
{
tree t;
def_stmt = SSA_NAME_DEF_STMT (v);
if (is_gimple_assign (def_stmt))
switch (gimple_assign_rhs_code (def_stmt))
{
case PLUS_EXPR:
t = gimple_assign_rhs2 (def_stmt);
if (linear_step || TREE_CODE (t) != INTEGER_CST)
return;
base = fold_build2 (POINTER_PLUS_EXPR, TREE_TYPE (base), base, t);
v = gimple_assign_rhs1 (def_stmt);
continue;
case MULT_EXPR:
t = gimple_assign_rhs2 (def_stmt);
if (linear_step || !tree_fits_shwi_p (t) || integer_zerop (t))
return;
linear_step = tree_to_shwi (t);
v = gimple_assign_rhs1 (def_stmt);
continue;
CASE_CONVERT:
t = gimple_assign_rhs1 (def_stmt);
if (TREE_CODE (TREE_TYPE (t)) != INTEGER_TYPE
|| (TYPE_PRECISION (TREE_TYPE (v))
< TYPE_PRECISION (TREE_TYPE (t))))
return;
if (!linear_step)
linear_step = 1;
v = t;
continue;
default:
return;
}
else if (gimple_call_internal_p (def_stmt, IFN_GOMP_SIMD_LANE)
&& loop->simduid
&& TREE_CODE (gimple_call_arg (def_stmt, 0)) == SSA_NAME
&& (SSA_NAME_VAR (gimple_call_arg (def_stmt, 0))
== loop->simduid))
{
if (!linear_step)
linear_step = 1;
arginfo->linear_step = linear_step;
arginfo->op = base;
arginfo->simd_lane_linear = true;
return;
}
}
}
/* Return the number of elements in vector type VECTYPE, which is associated
with a SIMD clone. At present these vectors always have a constant
length. */
static unsigned HOST_WIDE_INT
simd_clone_subparts (tree vectype)
{
return TYPE_VECTOR_SUBPARTS (vectype).to_constant ();
}
/* Function vectorizable_simd_clone_call.
Check if STMT_INFO performs a function call that can be vectorized
by calling a simd clone of the function.
If VEC_STMT is also passed, vectorize STMT_INFO: create a vectorized
stmt to replace it, put it in VEC_STMT, and insert it at GSI.
Return true if STMT_INFO is vectorizable in this way. */
static bool
vectorizable_simd_clone_call (stmt_vec_info stmt_info,
gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt, slp_tree slp_node,
stmt_vector_for_cost *)
{
tree vec_dest;
tree scalar_dest;
tree op, type;
tree vec_oprnd0 = NULL_TREE;
stmt_vec_info prev_stmt_info;
tree vectype;
unsigned int nunits;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
vec_info *vinfo = stmt_info->vinfo;
class loop *loop = loop_vinfo ? LOOP_VINFO_LOOP (loop_vinfo) : NULL;
tree fndecl, new_temp;
int ncopies, j;
auto_vec<simd_call_arg_info> arginfo;
vec<tree> vargs = vNULL;
size_t i, nargs;
tree lhs, rtype, ratype;
vec<constructor_elt, va_gc> *ret_ctor_elts = NULL;
/* Is STMT a vectorizable call? */
gcall *stmt = dyn_cast <gcall *> (stmt_info->stmt);
if (!stmt)
return false;
fndecl = gimple_call_fndecl (stmt);
if (fndecl == NULL_TREE)
return false;
struct cgraph_node *node = cgraph_node::get (fndecl);
if (node == NULL || node->simd_clones == NULL)
return false;
if (!STMT_VINFO_RELEVANT_P (stmt_info) && !bb_vinfo)
return false;
if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def
&& ! vec_stmt)
return false;
if (gimple_call_lhs (stmt)
&& TREE_CODE (gimple_call_lhs (stmt)) != SSA_NAME)
return false;
gcc_checking_assert (!stmt_can_throw_internal (cfun, stmt));
vectype = STMT_VINFO_VECTYPE (stmt_info);
if (loop_vinfo && nested_in_vect_loop_p (loop, stmt_info))
return false;
/* FORNOW */
if (slp_node)
return false;
/* Process function arguments. */
nargs = gimple_call_num_args (stmt);
/* Bail out if the function has zero arguments. */
if (nargs == 0)
return false;
arginfo.reserve (nargs, true);
for (i = 0; i < nargs; i++)
{
simd_call_arg_info thisarginfo;
affine_iv iv;
thisarginfo.linear_step = 0;
thisarginfo.align = 0;
thisarginfo.op = NULL_TREE;
thisarginfo.simd_lane_linear = false;
op = gimple_call_arg (stmt, i);
if (!vect_is_simple_use (op, vinfo, &thisarginfo.dt,
&thisarginfo.vectype)
|| thisarginfo.dt == vect_uninitialized_def)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
if (thisarginfo.dt == vect_constant_def
|| thisarginfo.dt == vect_external_def)
gcc_assert (thisarginfo.vectype == NULL_TREE);
else
{
gcc_assert (thisarginfo.vectype != NULL_TREE);
if (VECTOR_BOOLEAN_TYPE_P (thisarginfo.vectype))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"vector mask arguments are not supported\n");
return false;
}
}
/* For linear arguments, the analyze phase should have saved
the base and step in STMT_VINFO_SIMD_CLONE_INFO. */
if (i * 3 + 4 <= STMT_VINFO_SIMD_CLONE_INFO (stmt_info).length ()
&& STMT_VINFO_SIMD_CLONE_INFO (stmt_info)[i * 3 + 2])
{
gcc_assert (vec_stmt);
thisarginfo.linear_step
= tree_to_shwi (STMT_VINFO_SIMD_CLONE_INFO (stmt_info)[i * 3 + 2]);
thisarginfo.op
= STMT_VINFO_SIMD_CLONE_INFO (stmt_info)[i * 3 + 1];
thisarginfo.simd_lane_linear
= (STMT_VINFO_SIMD_CLONE_INFO (stmt_info)[i * 3 + 3]
== boolean_true_node);
/* If loop has been peeled for alignment, we need to adjust it. */
tree n1 = LOOP_VINFO_NITERS_UNCHANGED (loop_vinfo);
tree n2 = LOOP_VINFO_NITERS (loop_vinfo);
if (n1 != n2 && !thisarginfo.simd_lane_linear)
{
tree bias = fold_build2 (MINUS_EXPR, TREE_TYPE (n1), n1, n2);
tree step = STMT_VINFO_SIMD_CLONE_INFO (stmt_info)[i * 3 + 2];
tree opt = TREE_TYPE (thisarginfo.op);
bias = fold_convert (TREE_TYPE (step), bias);
bias = fold_build2 (MULT_EXPR, TREE_TYPE (step), bias, step);
thisarginfo.op
= fold_build2 (POINTER_TYPE_P (opt)
? POINTER_PLUS_EXPR : PLUS_EXPR, opt,
thisarginfo.op, bias);
}
}
else if (!vec_stmt
&& thisarginfo.dt != vect_constant_def
&& thisarginfo.dt != vect_external_def
&& loop_vinfo
&& TREE_CODE (op) == SSA_NAME
&& simple_iv (loop, loop_containing_stmt (stmt), op,
&iv, false)
&& tree_fits_shwi_p (iv.step))
{
thisarginfo.linear_step = tree_to_shwi (iv.step);
thisarginfo.op = iv.base;
}
else if ((thisarginfo.dt == vect_constant_def
|| thisarginfo.dt == vect_external_def)
&& POINTER_TYPE_P (TREE_TYPE (op)))
thisarginfo.align = get_pointer_alignment (op) / BITS_PER_UNIT;
/* Addresses of array elements indexed by GOMP_SIMD_LANE are
linear too. */
if (POINTER_TYPE_P (TREE_TYPE (op))
&& !thisarginfo.linear_step
&& !vec_stmt
&& thisarginfo.dt != vect_constant_def
&& thisarginfo.dt != vect_external_def
&& loop_vinfo
&& !slp_node
&& TREE_CODE (op) == SSA_NAME)
vect_simd_lane_linear (op, loop, &thisarginfo);
arginfo.quick_push (thisarginfo);
}
unsigned HOST_WIDE_INT vf;
if (!LOOP_VINFO_VECT_FACTOR (loop_vinfo).is_constant (&vf))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not considering SIMD clones; not yet supported"
" for variable-width vectors.\n");
return false;
}
unsigned int badness = 0;
struct cgraph_node *bestn = NULL;
if (STMT_VINFO_SIMD_CLONE_INFO (stmt_info).exists ())
bestn = cgraph_node::get (STMT_VINFO_SIMD_CLONE_INFO (stmt_info)[0]);
else
for (struct cgraph_node *n = node->simd_clones; n != NULL;
n = n->simdclone->next_clone)
{
unsigned int this_badness = 0;
if (n->simdclone->simdlen > vf
|| n->simdclone->nargs != nargs)
continue;
if (n->simdclone->simdlen < vf)
this_badness += (exact_log2 (vf)
- exact_log2 (n->simdclone->simdlen)) * 1024;
if (n->simdclone->inbranch)
this_badness += 2048;
int target_badness = targetm.simd_clone.usable (n);
if (target_badness < 0)
continue;
this_badness += target_badness * 512;
/* FORNOW: Have to add code to add the mask argument. */
if (n->simdclone->inbranch)
continue;
for (i = 0; i < nargs; i++)
{
switch (n->simdclone->args[i].arg_type)
{
case SIMD_CLONE_ARG_TYPE_VECTOR:
if (!useless_type_conversion_p
(n->simdclone->args[i].orig_type,
TREE_TYPE (gimple_call_arg (stmt, i))))
i = -1;
else if (arginfo[i].dt == vect_constant_def
|| arginfo[i].dt == vect_external_def
|| arginfo[i].linear_step)
this_badness += 64;
break;
case SIMD_CLONE_ARG_TYPE_UNIFORM:
if (arginfo[i].dt != vect_constant_def
&& arginfo[i].dt != vect_external_def)
i = -1;
break;
case SIMD_CLONE_ARG_TYPE_LINEAR_CONSTANT_STEP:
case SIMD_CLONE_ARG_TYPE_LINEAR_REF_CONSTANT_STEP:
if (arginfo[i].dt == vect_constant_def
|| arginfo[i].dt == vect_external_def
|| (arginfo[i].linear_step
!= n->simdclone->args[i].linear_step))
i = -1;
break;
case SIMD_CLONE_ARG_TYPE_LINEAR_VARIABLE_STEP:
case SIMD_CLONE_ARG_TYPE_LINEAR_VAL_CONSTANT_STEP:
case SIMD_CLONE_ARG_TYPE_LINEAR_UVAL_CONSTANT_STEP:
case SIMD_CLONE_ARG_TYPE_LINEAR_REF_VARIABLE_STEP:
case SIMD_CLONE_ARG_TYPE_LINEAR_VAL_VARIABLE_STEP:
case SIMD_CLONE_ARG_TYPE_LINEAR_UVAL_VARIABLE_STEP:
/* FORNOW */
i = -1;
break;
case SIMD_CLONE_ARG_TYPE_MASK:
gcc_unreachable ();
}
if (i == (size_t) -1)
break;
if (n->simdclone->args[i].alignment > arginfo[i].align)
{
i = -1;
break;
}
if (arginfo[i].align)
this_badness += (exact_log2 (arginfo[i].align)
- exact_log2 (n->simdclone->args[i].alignment));
}
if (i == (size_t) -1)
continue;
if (bestn == NULL || this_badness < badness)
{
bestn = n;
badness = this_badness;
}
}
if (bestn == NULL)
return false;
for (i = 0; i < nargs; i++)
if ((arginfo[i].dt == vect_constant_def
|| arginfo[i].dt == vect_external_def)
&& bestn->simdclone->args[i].arg_type == SIMD_CLONE_ARG_TYPE_VECTOR)
{
tree arg_type = TREE_TYPE (gimple_call_arg (stmt, i));
arginfo[i].vectype = get_vectype_for_scalar_type (vinfo, arg_type,
slp_node);
if (arginfo[i].vectype == NULL
|| (simd_clone_subparts (arginfo[i].vectype)
> bestn->simdclone->simdlen))
return false;
}
fndecl = bestn->decl;
nunits = bestn->simdclone->simdlen;
ncopies = vf / nunits;
/* If the function isn't const, only allow it in simd loops where user
has asserted that at least nunits consecutive iterations can be
performed using SIMD instructions. */
if ((loop == NULL || (unsigned) loop->safelen < nunits)
&& gimple_vuse (stmt))
return false;
/* Sanity check: make sure that at least one copy of the vectorized stmt
needs to be generated. */
gcc_assert (ncopies >= 1);
if (!vec_stmt) /* transformation not required. */
{
STMT_VINFO_SIMD_CLONE_INFO (stmt_info).safe_push (bestn->decl);
for (i = 0; i < nargs; i++)
if ((bestn->simdclone->args[i].arg_type
== SIMD_CLONE_ARG_TYPE_LINEAR_CONSTANT_STEP)
|| (bestn->simdclone->args[i].arg_type
== SIMD_CLONE_ARG_TYPE_LINEAR_REF_CONSTANT_STEP))
{
STMT_VINFO_SIMD_CLONE_INFO (stmt_info).safe_grow_cleared (i * 3
+ 1);
STMT_VINFO_SIMD_CLONE_INFO (stmt_info).safe_push (arginfo[i].op);
tree lst = POINTER_TYPE_P (TREE_TYPE (arginfo[i].op))
? size_type_node : TREE_TYPE (arginfo[i].op);
tree ls = build_int_cst (lst, arginfo[i].linear_step);
STMT_VINFO_SIMD_CLONE_INFO (stmt_info).safe_push (ls);
tree sll = arginfo[i].simd_lane_linear
? boolean_true_node : boolean_false_node;
STMT_VINFO_SIMD_CLONE_INFO (stmt_info).safe_push (sll);
}
STMT_VINFO_TYPE (stmt_info) = call_simd_clone_vec_info_type;
DUMP_VECT_SCOPE ("vectorizable_simd_clone_call");
/* vect_model_simple_cost (stmt_info, ncopies, dt, slp_node, cost_vec); */
return true;
}
/* Transform. */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location, "transform call.\n");
/* Handle def. */
scalar_dest = gimple_call_lhs (stmt);
vec_dest = NULL_TREE;
rtype = NULL_TREE;
ratype = NULL_TREE;
if (scalar_dest)
{
vec_dest = vect_create_destination_var (scalar_dest, vectype);
rtype = TREE_TYPE (TREE_TYPE (fndecl));
if (TREE_CODE (rtype) == ARRAY_TYPE)
{
ratype = rtype;
rtype = TREE_TYPE (ratype);
}
}
prev_stmt_info = NULL;
for (j = 0; j < ncopies; ++j)
{
/* Build argument list for the vectorized call. */
if (j == 0)
vargs.create (nargs);
else
vargs.truncate (0);
for (i = 0; i < nargs; i++)
{
unsigned int k, l, m, o;
tree atype;
op = gimple_call_arg (stmt, i);
switch (bestn->simdclone->args[i].arg_type)
{
case SIMD_CLONE_ARG_TYPE_VECTOR:
atype = bestn->simdclone->args[i].vector_type;
o = nunits / simd_clone_subparts (atype);
for (m = j * o; m < (j + 1) * o; m++)
{
if (simd_clone_subparts (atype)
< simd_clone_subparts (arginfo[i].vectype))
{
poly_uint64 prec = GET_MODE_BITSIZE (TYPE_MODE (atype));
k = (simd_clone_subparts (arginfo[i].vectype)
/ simd_clone_subparts (atype));
gcc_assert ((k & (k - 1)) == 0);
if (m == 0)
vec_oprnd0
= vect_get_vec_def_for_operand (op, stmt_info);
else
{
vec_oprnd0 = arginfo[i].op;
if ((m & (k - 1)) == 0)
vec_oprnd0
= vect_get_vec_def_for_stmt_copy (vinfo,
vec_oprnd0);
}
arginfo[i].op = vec_oprnd0;
vec_oprnd0
= build3 (BIT_FIELD_REF, atype, vec_oprnd0,
bitsize_int (prec),
bitsize_int ((m & (k - 1)) * prec));
gassign *new_stmt
= gimple_build_assign (make_ssa_name (atype),
vec_oprnd0);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
vargs.safe_push (gimple_assign_lhs (new_stmt));
}
else
{
k = (simd_clone_subparts (atype)
/ simd_clone_subparts (arginfo[i].vectype));
gcc_assert ((k & (k - 1)) == 0);
vec<constructor_elt, va_gc> *ctor_elts;
if (k != 1)
vec_alloc (ctor_elts, k);
else
ctor_elts = NULL;
for (l = 0; l < k; l++)
{
if (m == 0 && l == 0)
vec_oprnd0
= vect_get_vec_def_for_operand (op, stmt_info);
else
vec_oprnd0
= vect_get_vec_def_for_stmt_copy (vinfo,
arginfo[i].op);
arginfo[i].op = vec_oprnd0;
if (k == 1)
break;
CONSTRUCTOR_APPEND_ELT (ctor_elts, NULL_TREE,
vec_oprnd0);
}
if (k == 1)
vargs.safe_push (vec_oprnd0);
else
{
vec_oprnd0 = build_constructor (atype, ctor_elts);
gassign *new_stmt
= gimple_build_assign (make_ssa_name (atype),
vec_oprnd0);
vect_finish_stmt_generation (stmt_info, new_stmt,
gsi);
vargs.safe_push (gimple_assign_lhs (new_stmt));
}
}
}
break;
case SIMD_CLONE_ARG_TYPE_UNIFORM:
vargs.safe_push (op);
break;
case SIMD_CLONE_ARG_TYPE_LINEAR_CONSTANT_STEP:
case SIMD_CLONE_ARG_TYPE_LINEAR_REF_CONSTANT_STEP:
if (j == 0)
{
gimple_seq stmts;
arginfo[i].op
= force_gimple_operand (unshare_expr (arginfo[i].op),
&stmts, true, NULL_TREE);
if (stmts != NULL)
{
basic_block new_bb;
edge pe = loop_preheader_edge (loop);
new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
gcc_assert (!new_bb);
}
if (arginfo[i].simd_lane_linear)
{
vargs.safe_push (arginfo[i].op);
break;
}
tree phi_res = copy_ssa_name (op);
gphi *new_phi = create_phi_node (phi_res, loop->header);
loop_vinfo->add_stmt (new_phi);
add_phi_arg (new_phi, arginfo[i].op,
loop_preheader_edge (loop), UNKNOWN_LOCATION);
enum tree_code code
= POINTER_TYPE_P (TREE_TYPE (op))
? POINTER_PLUS_EXPR : PLUS_EXPR;
tree type = POINTER_TYPE_P (TREE_TYPE (op))
? sizetype : TREE_TYPE (op);
widest_int cst
= wi::mul (bestn->simdclone->args[i].linear_step,
ncopies * nunits);
tree tcst = wide_int_to_tree (type, cst);
tree phi_arg = copy_ssa_name (op);
gassign *new_stmt
= gimple_build_assign (phi_arg, code, phi_res, tcst);
gimple_stmt_iterator si = gsi_after_labels (loop->header);
gsi_insert_after (&si, new_stmt, GSI_NEW_STMT);
loop_vinfo->add_stmt (new_stmt);
add_phi_arg (new_phi, phi_arg, loop_latch_edge (loop),
UNKNOWN_LOCATION);
arginfo[i].op = phi_res;
vargs.safe_push (phi_res);
}
else
{
enum tree_code code
= POINTER_TYPE_P (TREE_TYPE (op))
? POINTER_PLUS_EXPR : PLUS_EXPR;
tree type = POINTER_TYPE_P (TREE_TYPE (op))
? sizetype : TREE_TYPE (op);
widest_int cst
= wi::mul (bestn->simdclone->args[i].linear_step,
j * nunits);
tree tcst = wide_int_to_tree (type, cst);
new_temp = make_ssa_name (TREE_TYPE (op));
gassign *new_stmt
= gimple_build_assign (new_temp, code,
arginfo[i].op, tcst);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
vargs.safe_push (new_temp);
}
break;
case SIMD_CLONE_ARG_TYPE_LINEAR_VAL_CONSTANT_STEP:
case SIMD_CLONE_ARG_TYPE_LINEAR_UVAL_CONSTANT_STEP:
case SIMD_CLONE_ARG_TYPE_LINEAR_VARIABLE_STEP:
case SIMD_CLONE_ARG_TYPE_LINEAR_REF_VARIABLE_STEP:
case SIMD_CLONE_ARG_TYPE_LINEAR_VAL_VARIABLE_STEP:
case SIMD_CLONE_ARG_TYPE_LINEAR_UVAL_VARIABLE_STEP:
default:
gcc_unreachable ();
}
}
gcall *new_call = gimple_build_call_vec (fndecl, vargs);
if (vec_dest)
{
gcc_assert (ratype || simd_clone_subparts (rtype) == nunits);
if (ratype)
new_temp = create_tmp_var (ratype);
else if (simd_clone_subparts (vectype)
== simd_clone_subparts (rtype))
new_temp = make_ssa_name (vec_dest, new_call);
else
new_temp = make_ssa_name (rtype, new_call);
gimple_call_set_lhs (new_call, new_temp);
}
stmt_vec_info new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_call, gsi);
if (vec_dest)
{
if (simd_clone_subparts (vectype) < nunits)
{
unsigned int k, l;
poly_uint64 prec = GET_MODE_BITSIZE (TYPE_MODE (vectype));
poly_uint64 bytes = GET_MODE_SIZE (TYPE_MODE (vectype));
k = nunits / simd_clone_subparts (vectype);
gcc_assert ((k & (k - 1)) == 0);
for (l = 0; l < k; l++)
{
tree t;
if (ratype)
{
t = build_fold_addr_expr (new_temp);
t = build2 (MEM_REF, vectype, t,
build_int_cst (TREE_TYPE (t), l * bytes));
}
else
t = build3 (BIT_FIELD_REF, vectype, new_temp,
bitsize_int (prec), bitsize_int (l * prec));
gimple *new_stmt
= gimple_build_assign (make_ssa_name (vectype), t);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (j == 0 && l == 0)
STMT_VINFO_VEC_STMT (stmt_info)
= *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
if (ratype)
vect_clobber_variable (stmt_info, gsi, new_temp);
continue;
}
else if (simd_clone_subparts (vectype) > nunits)
{
unsigned int k = (simd_clone_subparts (vectype)
/ simd_clone_subparts (rtype));
gcc_assert ((k & (k - 1)) == 0);
if ((j & (k - 1)) == 0)
vec_alloc (ret_ctor_elts, k);
if (ratype)
{
unsigned int m, o = nunits / simd_clone_subparts (rtype);
for (m = 0; m < o; m++)
{
tree tem = build4 (ARRAY_REF, rtype, new_temp,
size_int (m), NULL_TREE, NULL_TREE);
gimple *new_stmt
= gimple_build_assign (make_ssa_name (rtype), tem);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt,
gsi);
CONSTRUCTOR_APPEND_ELT (ret_ctor_elts, NULL_TREE,
gimple_assign_lhs (new_stmt));
}
vect_clobber_variable (stmt_info, gsi, new_temp);
}
else
CONSTRUCTOR_APPEND_ELT (ret_ctor_elts, NULL_TREE, new_temp);
if ((j & (k - 1)) != k - 1)
continue;
vec_oprnd0 = build_constructor (vectype, ret_ctor_elts);
gimple *new_stmt
= gimple_build_assign (make_ssa_name (vec_dest), vec_oprnd0);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if ((unsigned) j == k - 1)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
continue;
}
else if (ratype)
{
tree t = build_fold_addr_expr (new_temp);
t = build2 (MEM_REF, vectype, t,
build_int_cst (TREE_TYPE (t), 0));
gimple *new_stmt
= gimple_build_assign (make_ssa_name (vec_dest), t);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
vect_clobber_variable (stmt_info, gsi, new_temp);
}
}
if (j == 0)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
vargs.release ();
/* The call in STMT might prevent it from being removed in dce.
We however cannot remove it here, due to the way the ssa name
it defines is mapped to the new definition. So just replace
rhs of the statement with something harmless. */
if (slp_node)
return true;
gimple *new_stmt;
if (scalar_dest)
{
type = TREE_TYPE (scalar_dest);
lhs = gimple_call_lhs (vect_orig_stmt (stmt_info)->stmt);
new_stmt = gimple_build_assign (lhs, build_zero_cst (type));
}
else
new_stmt = gimple_build_nop ();
vinfo->replace_stmt (gsi, vect_orig_stmt (stmt_info), new_stmt);
unlink_stmt_vdef (stmt);
return true;
}
/* Function vect_gen_widened_results_half
Create a vector stmt whose code, type, number of arguments, and result
variable are CODE, OP_TYPE, and VEC_DEST, and its arguments are
VEC_OPRND0 and VEC_OPRND1. The new vector stmt is to be inserted at GSI.
In the case that CODE is a CALL_EXPR, this means that a call to DECL
needs to be created (DECL is a function-decl of a target-builtin).
STMT_INFO is the original scalar stmt that we are vectorizing. */
static gimple *
vect_gen_widened_results_half (enum tree_code code,
tree vec_oprnd0, tree vec_oprnd1, int op_type,
tree vec_dest, gimple_stmt_iterator *gsi,
stmt_vec_info stmt_info)
{
gimple *new_stmt;
tree new_temp;
/* Generate half of the widened result: */
gcc_assert (op_type == TREE_CODE_LENGTH (code));
if (op_type != binary_op)
vec_oprnd1 = NULL;
new_stmt = gimple_build_assign (vec_dest, code, vec_oprnd0, vec_oprnd1);
new_temp = make_ssa_name (vec_dest, new_stmt);
gimple_assign_set_lhs (new_stmt, new_temp);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
return new_stmt;
}
/* Get vectorized definitions for loop-based vectorization of STMT_INFO.
For the first operand we call vect_get_vec_def_for_operand (with OPRND
containing scalar operand), and for the rest we get a copy with
vect_get_vec_def_for_stmt_copy() using the previous vector definition
(stored in OPRND). See vect_get_vec_def_for_stmt_copy() for details.
The vectors are collected into VEC_OPRNDS. */
static void
vect_get_loop_based_defs (tree *oprnd, stmt_vec_info stmt_info,
vec<tree> *vec_oprnds, int multi_step_cvt)
{
vec_info *vinfo = stmt_info->vinfo;
tree vec_oprnd;
/* Get first vector operand. */
/* All the vector operands except the very first one (that is scalar oprnd)
are stmt copies. */
if (TREE_CODE (TREE_TYPE (*oprnd)) != VECTOR_TYPE)
vec_oprnd = vect_get_vec_def_for_operand (*oprnd, stmt_info);
else
vec_oprnd = vect_get_vec_def_for_stmt_copy (vinfo, *oprnd);
vec_oprnds->quick_push (vec_oprnd);
/* Get second vector operand. */
vec_oprnd = vect_get_vec_def_for_stmt_copy (vinfo, vec_oprnd);
vec_oprnds->quick_push (vec_oprnd);
*oprnd = vec_oprnd;
/* For conversion in multiple steps, continue to get operands
recursively. */
if (multi_step_cvt)
vect_get_loop_based_defs (oprnd, stmt_info, vec_oprnds,
multi_step_cvt - 1);
}
/* Create vectorized demotion statements for vector operands from VEC_OPRNDS.
For multi-step conversions store the resulting vectors and call the function
recursively. */
static void
vect_create_vectorized_demotion_stmts (vec<tree> *vec_oprnds,
int multi_step_cvt,
stmt_vec_info stmt_info,
vec<tree> vec_dsts,
gimple_stmt_iterator *gsi,
slp_tree slp_node, enum tree_code code,
stmt_vec_info *prev_stmt_info)
{
unsigned int i;
tree vop0, vop1, new_tmp, vec_dest;
vec_dest = vec_dsts.pop ();
for (i = 0; i < vec_oprnds->length (); i += 2)
{
/* Create demotion operation. */
vop0 = (*vec_oprnds)[i];
vop1 = (*vec_oprnds)[i + 1];
gassign *new_stmt = gimple_build_assign (vec_dest, code, vop0, vop1);
new_tmp = make_ssa_name (vec_dest, new_stmt);
gimple_assign_set_lhs (new_stmt, new_tmp);
stmt_vec_info new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (multi_step_cvt)
/* Store the resulting vector for next recursive call. */
(*vec_oprnds)[i/2] = new_tmp;
else
{
/* This is the last step of the conversion sequence. Store the
vectors in SLP_NODE or in vector info of the scalar statement
(or in STMT_VINFO_RELATED_STMT chain). */
if (slp_node)
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
else
{
if (!*prev_stmt_info)
STMT_VINFO_VEC_STMT (stmt_info) = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (*prev_stmt_info) = new_stmt_info;
*prev_stmt_info = new_stmt_info;
}
}
}
/* For multi-step demotion operations we first generate demotion operations
from the source type to the intermediate types, and then combine the
results (stored in VEC_OPRNDS) in demotion operation to the destination
type. */
if (multi_step_cvt)
{
/* At each level of recursion we have half of the operands we had at the
previous level. */
vec_oprnds->truncate ((i+1)/2);
vect_create_vectorized_demotion_stmts (vec_oprnds, multi_step_cvt - 1,
stmt_info, vec_dsts, gsi,
slp_node, VEC_PACK_TRUNC_EXPR,
prev_stmt_info);
}
vec_dsts.quick_push (vec_dest);
}
/* Create vectorized promotion statements for vector operands from VEC_OPRNDS0
and VEC_OPRNDS1, for a binary operation associated with scalar statement
STMT_INFO. For multi-step conversions store the resulting vectors and
call the function recursively. */
static void
vect_create_vectorized_promotion_stmts (vec<tree> *vec_oprnds0,
vec<tree> *vec_oprnds1,
stmt_vec_info stmt_info, tree vec_dest,
gimple_stmt_iterator *gsi,
enum tree_code code1,
enum tree_code code2, int op_type)
{
int i;
tree vop0, vop1, new_tmp1, new_tmp2;
gimple *new_stmt1, *new_stmt2;
vec<tree> vec_tmp = vNULL;
vec_tmp.create (vec_oprnds0->length () * 2);
FOR_EACH_VEC_ELT (*vec_oprnds0, i, vop0)
{
if (op_type == binary_op)
vop1 = (*vec_oprnds1)[i];
else
vop1 = NULL_TREE;
/* Generate the two halves of promotion operation. */
new_stmt1 = vect_gen_widened_results_half (code1, vop0, vop1,
op_type, vec_dest, gsi,
stmt_info);
new_stmt2 = vect_gen_widened_results_half (code2, vop0, vop1,
op_type, vec_dest, gsi,
stmt_info);
if (is_gimple_call (new_stmt1))
{
new_tmp1 = gimple_call_lhs (new_stmt1);
new_tmp2 = gimple_call_lhs (new_stmt2);
}
else
{
new_tmp1 = gimple_assign_lhs (new_stmt1);
new_tmp2 = gimple_assign_lhs (new_stmt2);
}
/* Store the results for the next step. */
vec_tmp.quick_push (new_tmp1);
vec_tmp.quick_push (new_tmp2);
}
vec_oprnds0->release ();
*vec_oprnds0 = vec_tmp;
}
/* Check if STMT_INFO performs a conversion operation that can be vectorized.
If VEC_STMT is also passed, vectorize STMT_INFO: create a vectorized
stmt to replace it, put it in VEC_STMT, and insert it at GSI.
Return true if STMT_INFO is vectorizable in this way. */
static bool
vectorizable_conversion (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt, slp_tree slp_node,
stmt_vector_for_cost *cost_vec)
{
tree vec_dest;
tree scalar_dest;
tree op0, op1 = NULL_TREE;
tree vec_oprnd0 = NULL_TREE, vec_oprnd1 = NULL_TREE;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
enum tree_code code, code1 = ERROR_MARK, code2 = ERROR_MARK;
enum tree_code codecvt1 = ERROR_MARK, codecvt2 = ERROR_MARK;
tree new_temp;
enum vect_def_type dt[2] = {vect_unknown_def_type, vect_unknown_def_type};
int ndts = 2;
stmt_vec_info prev_stmt_info;
poly_uint64 nunits_in;
poly_uint64 nunits_out;
tree vectype_out, vectype_in;
int ncopies, i, j;
tree lhs_type, rhs_type;
enum { NARROW, NONE, WIDEN } modifier;
vec<tree> vec_oprnds0 = vNULL;
vec<tree> vec_oprnds1 = vNULL;
tree vop0;
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
vec_info *vinfo = stmt_info->vinfo;
int multi_step_cvt = 0;
vec<tree> interm_types = vNULL;
tree last_oprnd, intermediate_type, cvt_type = NULL_TREE;
int op_type;
unsigned short fltsz;
/* Is STMT a vectorizable conversion? */
if (!STMT_VINFO_RELEVANT_P (stmt_info) && !bb_vinfo)
return false;
if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def
&& ! vec_stmt)
return false;
gassign *stmt = dyn_cast <gassign *> (stmt_info->stmt);
if (!stmt)
return false;
if (TREE_CODE (gimple_assign_lhs (stmt)) != SSA_NAME)
return false;
code = gimple_assign_rhs_code (stmt);
if (!CONVERT_EXPR_CODE_P (code)
&& code != FIX_TRUNC_EXPR
&& code != FLOAT_EXPR
&& code != WIDEN_MULT_EXPR
&& code != WIDEN_LSHIFT_EXPR)
return false;
op_type = TREE_CODE_LENGTH (code);
/* Check types of lhs and rhs. */
scalar_dest = gimple_assign_lhs (stmt);
lhs_type = TREE_TYPE (scalar_dest);
vectype_out = STMT_VINFO_VECTYPE (stmt_info);
op0 = gimple_assign_rhs1 (stmt);
rhs_type = TREE_TYPE (op0);
if ((code != FIX_TRUNC_EXPR && code != FLOAT_EXPR)
&& !((INTEGRAL_TYPE_P (lhs_type)
&& INTEGRAL_TYPE_P (rhs_type))
|| (SCALAR_FLOAT_TYPE_P (lhs_type)
&& SCALAR_FLOAT_TYPE_P (rhs_type))))
return false;
if (!VECTOR_BOOLEAN_TYPE_P (vectype_out)
&& ((INTEGRAL_TYPE_P (lhs_type)
&& !type_has_mode_precision_p (lhs_type))
|| (INTEGRAL_TYPE_P (rhs_type)
&& !type_has_mode_precision_p (rhs_type))))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"type conversion to/from bit-precision unsupported."
"\n");
return false;
}
/* Check the operands of the operation. */
if (!vect_is_simple_use (op0, vinfo, &dt[0], &vectype_in))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
if (op_type == binary_op)
{
bool ok;
op1 = gimple_assign_rhs2 (stmt);
gcc_assert (code == WIDEN_MULT_EXPR || code == WIDEN_LSHIFT_EXPR);
/* For WIDEN_MULT_EXPR, if OP0 is a constant, use the type of
OP1. */
if (CONSTANT_CLASS_P (op0))
ok = vect_is_simple_use (op1, vinfo, &dt[1], &vectype_in);
else
ok = vect_is_simple_use (op1, vinfo, &dt[1]);
if (!ok)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
}
/* If op0 is an external or constant def, infer the vector type
from the scalar type. */
if (!vectype_in)
vectype_in = get_vectype_for_scalar_type (vinfo, rhs_type, slp_node);
if (vec_stmt)
gcc_assert (vectype_in);
if (!vectype_in)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"no vectype for scalar type %T\n", rhs_type);
return false;
}
if (VECTOR_BOOLEAN_TYPE_P (vectype_out)
&& !VECTOR_BOOLEAN_TYPE_P (vectype_in))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"can't convert between boolean and non "
"boolean vectors %T\n", rhs_type);
return false;
}
nunits_in = TYPE_VECTOR_SUBPARTS (vectype_in);
nunits_out = TYPE_VECTOR_SUBPARTS (vectype_out);
if (known_eq (nunits_out, nunits_in))
modifier = NONE;
else if (multiple_p (nunits_out, nunits_in))
modifier = NARROW;
else
{
gcc_checking_assert (multiple_p (nunits_in, nunits_out));
modifier = WIDEN;
}
/* Multiple types in SLP are handled by creating the appropriate number of
vectorized stmts for each SLP node. Hence, NCOPIES is always 1 in
case of SLP. */
if (slp_node)
ncopies = 1;
else if (modifier == NARROW)
ncopies = vect_get_num_copies (loop_vinfo, vectype_out);
else
ncopies = vect_get_num_copies (loop_vinfo, vectype_in);
/* Sanity check: make sure that at least one copy of the vectorized stmt
needs to be generated. */
gcc_assert (ncopies >= 1);
bool found_mode = false;
scalar_mode lhs_mode = SCALAR_TYPE_MODE (lhs_type);
scalar_mode rhs_mode = SCALAR_TYPE_MODE (rhs_type);
opt_scalar_mode rhs_mode_iter;
/* Supportable by target? */
switch (modifier)
{
case NONE:
if (code != FIX_TRUNC_EXPR
&& code != FLOAT_EXPR
&& !CONVERT_EXPR_CODE_P (code))
return false;
if (supportable_convert_operation (code, vectype_out, vectype_in, &code1))
break;
/* FALLTHRU */
unsupported:
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"conversion not supported by target.\n");
return false;
case WIDEN:
if (supportable_widening_operation (code, stmt_info, vectype_out,
vectype_in, &code1, &code2,
&multi_step_cvt, &interm_types))
{
/* Binary widening operation can only be supported directly by the
architecture. */
gcc_assert (!(multi_step_cvt && op_type == binary_op));
break;
}
if (code != FLOAT_EXPR
|| GET_MODE_SIZE (lhs_mode) <= GET_MODE_SIZE (rhs_mode))
goto unsupported;
fltsz = GET_MODE_SIZE (lhs_mode);
FOR_EACH_2XWIDER_MODE (rhs_mode_iter, rhs_mode)
{
rhs_mode = rhs_mode_iter.require ();
if (GET_MODE_SIZE (rhs_mode) > fltsz)
break;
cvt_type
= build_nonstandard_integer_type (GET_MODE_BITSIZE (rhs_mode), 0);
cvt_type = get_same_sized_vectype (cvt_type, vectype_in);
if (cvt_type == NULL_TREE)
goto unsupported;
if (GET_MODE_SIZE (rhs_mode) == fltsz)
{
if (!supportable_convert_operation (code, vectype_out,
cvt_type, &codecvt1))
goto unsupported;
}
else if (!supportable_widening_operation (code, stmt_info,
vectype_out, cvt_type,
&codecvt1, &codecvt2,
&multi_step_cvt,
&interm_types))
continue;
else
gcc_assert (multi_step_cvt == 0);
if (supportable_widening_operation (NOP_EXPR, stmt_info, cvt_type,
vectype_in, &code1, &code2,
&multi_step_cvt, &interm_types))
{
found_mode = true;
break;
}
}
if (!found_mode)
goto unsupported;
if (GET_MODE_SIZE (rhs_mode) == fltsz)
codecvt2 = ERROR_MARK;
else
{
multi_step_cvt++;
interm_types.safe_push (cvt_type);
cvt_type = NULL_TREE;
}
break;
case NARROW:
gcc_assert (op_type == unary_op);
if (supportable_narrowing_operation (code, vectype_out, vectype_in,
&code1, &multi_step_cvt,
&interm_types))
break;
if (code != FIX_TRUNC_EXPR
|| GET_MODE_SIZE (lhs_mode) >= GET_MODE_SIZE (rhs_mode))
goto unsupported;
cvt_type
= build_nonstandard_integer_type (GET_MODE_BITSIZE (rhs_mode), 0);
cvt_type = get_same_sized_vectype (cvt_type, vectype_in);
if (cvt_type == NULL_TREE)
goto unsupported;
if (!supportable_convert_operation (code, cvt_type, vectype_in,
&codecvt1))
goto unsupported;
if (supportable_narrowing_operation (NOP_EXPR, vectype_out, cvt_type,
&code1, &multi_step_cvt,
&interm_types))
break;
goto unsupported;
default:
gcc_unreachable ();
}
if (!vec_stmt) /* transformation not required. */
{
DUMP_VECT_SCOPE ("vectorizable_conversion");
if (modifier == NONE)
{
STMT_VINFO_TYPE (stmt_info) = type_conversion_vec_info_type;
vect_model_simple_cost (stmt_info, ncopies, dt, ndts, slp_node,
cost_vec);
}
else if (modifier == NARROW)
{
STMT_VINFO_TYPE (stmt_info) = type_demotion_vec_info_type;
/* The final packing step produces one vector result per copy. */
unsigned int nvectors
= (slp_node ? SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node) : ncopies);
vect_model_promotion_demotion_cost (stmt_info, dt, nvectors,
multi_step_cvt, cost_vec);
}
else
{
STMT_VINFO_TYPE (stmt_info) = type_promotion_vec_info_type;
/* The initial unpacking step produces two vector results
per copy. MULTI_STEP_CVT is 0 for a single conversion,
so >> MULTI_STEP_CVT divides by 2^(number of steps - 1). */
unsigned int nvectors
= (slp_node
? SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node) >> multi_step_cvt
: ncopies * 2);
vect_model_promotion_demotion_cost (stmt_info, dt, nvectors,
multi_step_cvt, cost_vec);
}
interm_types.release ();
return true;
}
/* Transform. */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"transform conversion. ncopies = %d.\n", ncopies);
if (op_type == binary_op)
{
if (CONSTANT_CLASS_P (op0))
op0 = fold_convert (TREE_TYPE (op1), op0);
else if (CONSTANT_CLASS_P (op1))
op1 = fold_convert (TREE_TYPE (op0), op1);
}
/* In case of multi-step conversion, we first generate conversion operations
to the intermediate types, and then from that types to the final one.
We create vector destinations for the intermediate type (TYPES) received
from supportable_*_operation, and store them in the correct order
for future use in vect_create_vectorized_*_stmts (). */
auto_vec<tree> vec_dsts (multi_step_cvt + 1);
vec_dest = vect_create_destination_var (scalar_dest,
(cvt_type && modifier == WIDEN)
? cvt_type : vectype_out);
vec_dsts.quick_push (vec_dest);
if (multi_step_cvt)
{
for (i = interm_types.length () - 1;
interm_types.iterate (i, &intermediate_type); i--)
{
vec_dest = vect_create_destination_var (scalar_dest,
intermediate_type);
vec_dsts.quick_push (vec_dest);
}
}
if (cvt_type)
vec_dest = vect_create_destination_var (scalar_dest,
modifier == WIDEN
? vectype_out : cvt_type);
if (!slp_node)
{
if (modifier == WIDEN)
{
vec_oprnds0.create (multi_step_cvt ? vect_pow2 (multi_step_cvt) : 1);
if (op_type == binary_op)
vec_oprnds1.create (1);
}
else if (modifier == NARROW)
vec_oprnds0.create (
2 * (multi_step_cvt ? vect_pow2 (multi_step_cvt) : 1));
}
else if (code == WIDEN_LSHIFT_EXPR)
vec_oprnds1.create (slp_node->vec_stmts_size);
last_oprnd = op0;
prev_stmt_info = NULL;
switch (modifier)
{
case NONE:
for (j = 0; j < ncopies; j++)
{
if (j == 0)
vect_get_vec_defs (op0, NULL, stmt_info, &vec_oprnds0,
NULL, slp_node);
else
vect_get_vec_defs_for_stmt_copy (vinfo, &vec_oprnds0, NULL);
FOR_EACH_VEC_ELT (vec_oprnds0, i, vop0)
{
stmt_vec_info new_stmt_info;
/* Arguments are ready, create the new vector stmt. */
gcc_assert (TREE_CODE_LENGTH (code1) == unary_op);
gassign *new_stmt = gimple_build_assign (vec_dest, code1, vop0);
new_temp = make_ssa_name (vec_dest, new_stmt);
gimple_assign_set_lhs (new_stmt, new_temp);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (slp_node)
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
else
{
if (!prev_stmt_info)
STMT_VINFO_VEC_STMT (stmt_info)
= *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
}
}
break;
case WIDEN:
/* In case the vectorization factor (VF) is bigger than the number
of elements that we can fit in a vectype (nunits), we have to
generate more than one vector stmt - i.e - we need to "unroll"
the vector stmt by a factor VF/nunits. */
for (j = 0; j < ncopies; j++)
{
/* Handle uses. */
if (j == 0)
{
if (slp_node)
{
if (code == WIDEN_LSHIFT_EXPR)
{
unsigned int k;
vec_oprnd1 = op1;
/* Store vec_oprnd1 for every vector stmt to be created
for SLP_NODE. We check during the analysis that all
the shift arguments are the same. */
for (k = 0; k < slp_node->vec_stmts_size - 1; k++)
vec_oprnds1.quick_push (vec_oprnd1);
vect_get_vec_defs (op0, NULL_TREE, stmt_info,
&vec_oprnds0, NULL, slp_node);
}
else
vect_get_vec_defs (op0, op1, stmt_info, &vec_oprnds0,
&vec_oprnds1, slp_node);
}
else
{
vec_oprnd0 = vect_get_vec_def_for_operand (op0, stmt_info);
vec_oprnds0.quick_push (vec_oprnd0);
if (op_type == binary_op)
{
if (code == WIDEN_LSHIFT_EXPR)
vec_oprnd1 = op1;
else
vec_oprnd1
= vect_get_vec_def_for_operand (op1, stmt_info);
vec_oprnds1.quick_push (vec_oprnd1);
}
}
}
else
{
vec_oprnd0 = vect_get_vec_def_for_stmt_copy (vinfo, vec_oprnd0);
vec_oprnds0.truncate (0);
vec_oprnds0.quick_push (vec_oprnd0);
if (op_type == binary_op)
{
if (code == WIDEN_LSHIFT_EXPR)
vec_oprnd1 = op1;
else
vec_oprnd1 = vect_get_vec_def_for_stmt_copy (vinfo,
vec_oprnd1);
vec_oprnds1.truncate (0);
vec_oprnds1.quick_push (vec_oprnd1);
}
}
/* Arguments are ready. Create the new vector stmts. */
for (i = multi_step_cvt; i >= 0; i--)
{
tree this_dest = vec_dsts[i];
enum tree_code c1 = code1, c2 = code2;
if (i == 0 && codecvt2 != ERROR_MARK)
{
c1 = codecvt1;
c2 = codecvt2;
}
vect_create_vectorized_promotion_stmts (&vec_oprnds0,
&vec_oprnds1, stmt_info,
this_dest, gsi,
c1, c2, op_type);
}
FOR_EACH_VEC_ELT (vec_oprnds0, i, vop0)
{
stmt_vec_info new_stmt_info;
if (cvt_type)
{
gcc_assert (TREE_CODE_LENGTH (codecvt1) == unary_op);
new_temp = make_ssa_name (vec_dest);
gassign *new_stmt
= gimple_build_assign (new_temp, codecvt1, vop0);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
else
new_stmt_info = vinfo->lookup_def (vop0);
if (slp_node)
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
else
{
if (!prev_stmt_info)
STMT_VINFO_VEC_STMT (stmt_info) = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
}
}
*vec_stmt = STMT_VINFO_VEC_STMT (stmt_info);
break;
case NARROW:
/* In case the vectorization factor (VF) is bigger than the number
of elements that we can fit in a vectype (nunits), we have to
generate more than one vector stmt - i.e - we need to "unroll"
the vector stmt by a factor VF/nunits. */
for (j = 0; j < ncopies; j++)
{
/* Handle uses. */
if (slp_node)
vect_get_vec_defs (op0, NULL_TREE, stmt_info, &vec_oprnds0, NULL,
slp_node);
else
{
vec_oprnds0.truncate (0);
vect_get_loop_based_defs (&last_oprnd, stmt_info, &vec_oprnds0,
vect_pow2 (multi_step_cvt) - 1);
}
/* Arguments are ready. Create the new vector stmts. */
if (cvt_type)
FOR_EACH_VEC_ELT (vec_oprnds0, i, vop0)
{
gcc_assert (TREE_CODE_LENGTH (codecvt1) == unary_op);
new_temp = make_ssa_name (vec_dest);
gassign *new_stmt
= gimple_build_assign (new_temp, codecvt1, vop0);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
vec_oprnds0[i] = new_temp;
}
vect_create_vectorized_demotion_stmts (&vec_oprnds0, multi_step_cvt,
stmt_info, vec_dsts, gsi,
slp_node, code1,
&prev_stmt_info);
}
*vec_stmt = STMT_VINFO_VEC_STMT (stmt_info);
break;
}
vec_oprnds0.release ();
vec_oprnds1.release ();
interm_types.release ();
return true;
}
/* Return true if we can assume from the scalar form of STMT_INFO that
neither the scalar nor the vector forms will generate code. STMT_INFO
is known not to involve a data reference. */
bool
vect_nop_conversion_p (stmt_vec_info stmt_info)
{
gassign *stmt = dyn_cast <gassign *> (stmt_info->stmt);
if (!stmt)
return false;
tree lhs = gimple_assign_lhs (stmt);
tree_code code = gimple_assign_rhs_code (stmt);
tree rhs = gimple_assign_rhs1 (stmt);
if (code == SSA_NAME || code == VIEW_CONVERT_EXPR)
return true;
if (CONVERT_EXPR_CODE_P (code))
return tree_nop_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs));
return false;
}
/* Function vectorizable_assignment.
Check if STMT_INFO performs an assignment (copy) that can be vectorized.
If VEC_STMT is also passed, vectorize the STMT_INFO: create a vectorized
stmt to replace it, put it in VEC_STMT, and insert it at GSI.
Return true if STMT_INFO is vectorizable in this way. */
static bool
vectorizable_assignment (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt, slp_tree slp_node,
stmt_vector_for_cost *cost_vec)
{
tree vec_dest;
tree scalar_dest;
tree op;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
tree new_temp;
enum vect_def_type dt[1] = {vect_unknown_def_type};
int ndts = 1;
int ncopies;
int i, j;
vec<tree> vec_oprnds = vNULL;
tree vop;
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
vec_info *vinfo = stmt_info->vinfo;
stmt_vec_info prev_stmt_info = NULL;
enum tree_code code;
tree vectype_in;
if (!STMT_VINFO_RELEVANT_P (stmt_info) && !bb_vinfo)
return false;
if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def
&& ! vec_stmt)
return false;
/* Is vectorizable assignment? */
gassign *stmt = dyn_cast <gassign *> (stmt_info->stmt);
if (!stmt)
return false;
scalar_dest = gimple_assign_lhs (stmt);
if (TREE_CODE (scalar_dest) != SSA_NAME)
return false;
code = gimple_assign_rhs_code (stmt);
if (gimple_assign_single_p (stmt)
|| code == PAREN_EXPR
|| CONVERT_EXPR_CODE_P (code))
op = gimple_assign_rhs1 (stmt);
else
return false;
if (code == VIEW_CONVERT_EXPR)
op = TREE_OPERAND (op, 0);
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
/* Multiple types in SLP are handled by creating the appropriate number of
vectorized stmts for each SLP node. Hence, NCOPIES is always 1 in
case of SLP. */
if (slp_node)
ncopies = 1;
else
ncopies = vect_get_num_copies (loop_vinfo, vectype);
gcc_assert (ncopies >= 1);
if (!vect_is_simple_use (op, vinfo, &dt[0], &vectype_in))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
/* We can handle NOP_EXPR conversions that do not change the number
of elements or the vector size. */
if ((CONVERT_EXPR_CODE_P (code)
|| code == VIEW_CONVERT_EXPR)
&& (!vectype_in
|| maybe_ne (TYPE_VECTOR_SUBPARTS (vectype_in), nunits)
|| maybe_ne (GET_MODE_SIZE (TYPE_MODE (vectype)),
GET_MODE_SIZE (TYPE_MODE (vectype_in)))))
return false;
/* We do not handle bit-precision changes. */
if ((CONVERT_EXPR_CODE_P (code)
|| code == VIEW_CONVERT_EXPR)
&& INTEGRAL_TYPE_P (TREE_TYPE (scalar_dest))
&& (!type_has_mode_precision_p (TREE_TYPE (scalar_dest))
|| !type_has_mode_precision_p (TREE_TYPE (op)))
/* But a conversion that does not change the bit-pattern is ok. */
&& !((TYPE_PRECISION (TREE_TYPE (scalar_dest))
> TYPE_PRECISION (TREE_TYPE (op)))
&& TYPE_UNSIGNED (TREE_TYPE (op)))
/* Conversion between boolean types of different sizes is
a simple assignment in case their vectypes are same
boolean vectors. */
&& (!VECTOR_BOOLEAN_TYPE_P (vectype)
|| !VECTOR_BOOLEAN_TYPE_P (vectype_in)))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"type conversion to/from bit-precision "
"unsupported.\n");
return false;
}
if (!vec_stmt) /* transformation not required. */
{
STMT_VINFO_TYPE (stmt_info) = assignment_vec_info_type;
DUMP_VECT_SCOPE ("vectorizable_assignment");
if (!vect_nop_conversion_p (stmt_info))
vect_model_simple_cost (stmt_info, ncopies, dt, ndts, slp_node,
cost_vec);
return true;
}
/* Transform. */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location, "transform assignment.\n");
/* Handle def. */
vec_dest = vect_create_destination_var (scalar_dest, vectype);
/* Handle use. */
for (j = 0; j < ncopies; j++)
{
/* Handle uses. */
if (j == 0)
vect_get_vec_defs (op, NULL, stmt_info, &vec_oprnds, NULL, slp_node);
else
vect_get_vec_defs_for_stmt_copy (vinfo, &vec_oprnds, NULL);
/* Arguments are ready. create the new vector stmt. */
stmt_vec_info new_stmt_info = NULL;
FOR_EACH_VEC_ELT (vec_oprnds, i, vop)
{
if (CONVERT_EXPR_CODE_P (code)
|| code == VIEW_CONVERT_EXPR)
vop = build1 (VIEW_CONVERT_EXPR, vectype, vop);
gassign *new_stmt = gimple_build_assign (vec_dest, vop);
new_temp = make_ssa_name (vec_dest, new_stmt);
gimple_assign_set_lhs (new_stmt, new_temp);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (slp_node)
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
}
if (slp_node)
continue;
if (j == 0)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
vec_oprnds.release ();
return true;
}
/* Return TRUE if CODE (a shift operation) is supported for SCALAR_TYPE
either as shift by a scalar or by a vector. */
bool
vect_supportable_shift (vec_info *vinfo, enum tree_code code, tree scalar_type)
{
machine_mode vec_mode;
optab optab;
int icode;
tree vectype;
vectype = get_vectype_for_scalar_type (vinfo, scalar_type);
if (!vectype)
return false;
optab = optab_for_tree_code (code, vectype, optab_scalar);
if (!optab
|| optab_handler (optab, TYPE_MODE (vectype)) == CODE_FOR_nothing)
{
optab = optab_for_tree_code (code, vectype, optab_vector);
if (!optab
|| (optab_handler (optab, TYPE_MODE (vectype))
== CODE_FOR_nothing))
return false;
}
vec_mode = TYPE_MODE (vectype);
icode = (int) optab_handler (optab, vec_mode);
if (icode == CODE_FOR_nothing)
return false;
return true;
}
/* Function vectorizable_shift.
Check if STMT_INFO performs a shift operation that can be vectorized.
If VEC_STMT is also passed, vectorize the STMT_INFO: create a vectorized
stmt to replace it, put it in VEC_STMT, and insert it at GSI.
Return true if STMT_INFO is vectorizable in this way. */
static bool
vectorizable_shift (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt, slp_tree slp_node,
stmt_vector_for_cost *cost_vec)
{
tree vec_dest;
tree scalar_dest;
tree op0, op1 = NULL;
tree vec_oprnd1 = NULL_TREE;
tree vectype;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
enum tree_code code;
machine_mode vec_mode;
tree new_temp;
optab optab;
int icode;
machine_mode optab_op2_mode;
enum vect_def_type dt[2] = {vect_unknown_def_type, vect_unknown_def_type};
int ndts = 2;
stmt_vec_info prev_stmt_info;
poly_uint64 nunits_in;
poly_uint64 nunits_out;
tree vectype_out;
tree op1_vectype;
int ncopies;
int j, i;
vec<tree> vec_oprnds0 = vNULL;
vec<tree> vec_oprnds1 = vNULL;
tree vop0, vop1;
unsigned int k;
bool scalar_shift_arg = true;
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
vec_info *vinfo = stmt_info->vinfo;
bool incompatible_op1_vectype_p = false;
if (!STMT_VINFO_RELEVANT_P (stmt_info) && !bb_vinfo)
return false;
if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def
&& STMT_VINFO_DEF_TYPE (stmt_info) != vect_nested_cycle
&& ! vec_stmt)
return false;
/* Is STMT a vectorizable binary/unary operation? */
gassign *stmt = dyn_cast <gassign *> (stmt_info->stmt);
if (!stmt)
return false;
if (TREE_CODE (gimple_assign_lhs (stmt)) != SSA_NAME)
return false;
code = gimple_assign_rhs_code (stmt);
if (!(code == LSHIFT_EXPR || code == RSHIFT_EXPR || code == LROTATE_EXPR
|| code == RROTATE_EXPR))
return false;
scalar_dest = gimple_assign_lhs (stmt);
vectype_out = STMT_VINFO_VECTYPE (stmt_info);
if (!type_has_mode_precision_p (TREE_TYPE (scalar_dest)))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"bit-precision shifts not supported.\n");
return false;
}
op0 = gimple_assign_rhs1 (stmt);
if (!vect_is_simple_use (op0, vinfo, &dt[0], &vectype))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
/* If op0 is an external or constant def, infer the vector type
from the scalar type. */
if (!vectype)
vectype = get_vectype_for_scalar_type (vinfo, TREE_TYPE (op0), slp_node);
if (vec_stmt)
gcc_assert (vectype);
if (!vectype)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"no vectype for scalar type\n");
return false;
}
nunits_out = TYPE_VECTOR_SUBPARTS (vectype_out);
nunits_in = TYPE_VECTOR_SUBPARTS (vectype);
if (maybe_ne (nunits_out, nunits_in))
return false;
op1 = gimple_assign_rhs2 (stmt);
stmt_vec_info op1_def_stmt_info;
if (!vect_is_simple_use (op1, vinfo, &dt[1], &op1_vectype,
&op1_def_stmt_info))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
/* Multiple types in SLP are handled by creating the appropriate number of
vectorized stmts for each SLP node. Hence, NCOPIES is always 1 in
case of SLP. */
if (slp_node)
ncopies = 1;
else
ncopies = vect_get_num_copies (loop_vinfo, vectype);
gcc_assert (ncopies >= 1);
/* Determine whether the shift amount is a vector, or scalar. If the
shift/rotate amount is a vector, use the vector/vector shift optabs. */
if ((dt[1] == vect_internal_def
|| dt[1] == vect_induction_def
|| dt[1] == vect_nested_cycle)
&& !slp_node)
scalar_shift_arg = false;
else if (dt[1] == vect_constant_def
|| dt[1] == vect_external_def
|| dt[1] == vect_internal_def)
{
/* In SLP, need to check whether the shift count is the same,
in loops if it is a constant or invariant, it is always
a scalar shift. */
if (slp_node)
{
vec<stmt_vec_info> stmts = SLP_TREE_SCALAR_STMTS (slp_node);
stmt_vec_info slpstmt_info;
FOR_EACH_VEC_ELT (stmts, k, slpstmt_info)
{
gassign *slpstmt = as_a <gassign *> (slpstmt_info->stmt);
if (!operand_equal_p (gimple_assign_rhs2 (slpstmt), op1, 0))
scalar_shift_arg = false;
}
/* For internal SLP defs we have to make sure we see scalar stmts
for all vector elements.
??? For different vectors we could resort to a different
scalar shift operand but code-generation below simply always
takes the first. */
if (dt[1] == vect_internal_def
&& maybe_ne (nunits_out * SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node),
stmts.length ()))
scalar_shift_arg = false;
}
/* If the shift amount is computed by a pattern stmt we cannot
use the scalar amount directly thus give up and use a vector
shift. */
if (op1_def_stmt_info && is_pattern_stmt_p (op1_def_stmt_info))
scalar_shift_arg = false;
}
else
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"operand mode requires invariant argument.\n");
return false;
}
/* Vector shifted by vector. */
bool was_scalar_shift_arg = scalar_shift_arg;
if (!scalar_shift_arg)
{
optab = optab_for_tree_code (code, vectype, optab_vector);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vector/vector shift/rotate found.\n");
if (!op1_vectype)
op1_vectype = get_vectype_for_scalar_type (vinfo, TREE_TYPE (op1),
slp_node);
incompatible_op1_vectype_p
= (op1_vectype == NULL_TREE
|| maybe_ne (TYPE_VECTOR_SUBPARTS (op1_vectype),
TYPE_VECTOR_SUBPARTS (vectype))
|| TYPE_MODE (op1_vectype) != TYPE_MODE (vectype));
if (incompatible_op1_vectype_p
&& (!slp_node
|| SLP_TREE_DEF_TYPE
(SLP_TREE_CHILDREN (slp_node)[1]) != vect_constant_def))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"unusable type for last operand in"
" vector/vector shift/rotate.\n");
return false;
}
}
/* See if the machine has a vector shifted by scalar insn and if not
then see if it has a vector shifted by vector insn. */
else
{
optab = optab_for_tree_code (code, vectype, optab_scalar);
if (optab
&& optab_handler (optab, TYPE_MODE (vectype)) != CODE_FOR_nothing)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vector/scalar shift/rotate found.\n");
}
else
{
optab = optab_for_tree_code (code, vectype, optab_vector);
if (optab
&& (optab_handler (optab, TYPE_MODE (vectype))
!= CODE_FOR_nothing))
{
scalar_shift_arg = false;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vector/vector shift/rotate found.\n");
/* Unlike the other binary operators, shifts/rotates have
the rhs being int, instead of the same type as the lhs,
so make sure the scalar is the right type if we are
dealing with vectors of long long/long/short/char. */
incompatible_op1_vectype_p
= !tree_nop_conversion_p (TREE_TYPE (vectype),
TREE_TYPE (op1));
}
}
}
/* Supportable by target? */
if (!optab)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"no optab.\n");
return false;
}
vec_mode = TYPE_MODE (vectype);
icode = (int) optab_handler (optab, vec_mode);
if (icode == CODE_FOR_nothing)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"op not supported by target.\n");
/* Check only during analysis. */
if (maybe_ne (GET_MODE_SIZE (vec_mode), UNITS_PER_WORD)
|| (!vec_stmt
&& !vect_worthwhile_without_simd_p (vinfo, code)))
return false;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"proceeding using word mode.\n");
}
/* Worthwhile without SIMD support? Check only during analysis. */
if (!vec_stmt
&& !VECTOR_MODE_P (TYPE_MODE (vectype))
&& !vect_worthwhile_without_simd_p (vinfo, code))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not worthwhile without SIMD support.\n");
return false;
}
if (!vec_stmt) /* transformation not required. */
{
STMT_VINFO_TYPE (stmt_info) = shift_vec_info_type;
DUMP_VECT_SCOPE ("vectorizable_shift");
vect_model_simple_cost (stmt_info, ncopies, dt,
scalar_shift_arg ? 1 : ndts, slp_node, cost_vec);
return true;
}
/* Transform. */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"transform binary/unary operation.\n");
if (incompatible_op1_vectype_p && !slp_node)
{
op1 = fold_convert (TREE_TYPE (vectype), op1);
if (dt[1] != vect_constant_def)
op1 = vect_init_vector (stmt_info, op1,
TREE_TYPE (vectype), NULL);
}
/* Handle def. */
vec_dest = vect_create_destination_var (scalar_dest, vectype);
prev_stmt_info = NULL;
for (j = 0; j < ncopies; j++)
{
/* Handle uses. */
if (j == 0)
{
if (scalar_shift_arg)
{
/* Vector shl and shr insn patterns can be defined with scalar
operand 2 (shift operand). In this case, use constant or loop
invariant op1 directly, without extending it to vector mode
first. */
optab_op2_mode = insn_data[icode].operand[2].mode;
if (!VECTOR_MODE_P (optab_op2_mode))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"operand 1 using scalar mode.\n");
vec_oprnd1 = op1;
vec_oprnds1.create (slp_node ? slp_node->vec_stmts_size : 1);
vec_oprnds1.quick_push (vec_oprnd1);
if (slp_node)
{
/* Store vec_oprnd1 for every vector stmt to be created
for SLP_NODE. We check during the analysis that all
the shift arguments are the same.
TODO: Allow different constants for different vector
stmts generated for an SLP instance. */
for (k = 0; k < slp_node->vec_stmts_size - 1; k++)
vec_oprnds1.quick_push (vec_oprnd1);
}
}
}
else if (slp_node && incompatible_op1_vectype_p)
{
if (was_scalar_shift_arg)
{
/* If the argument was the same in all lanes create
the correctly typed vector shift amount directly. */
op1 = fold_convert (TREE_TYPE (vectype), op1);
op1 = vect_init_vector (stmt_info, op1, TREE_TYPE (vectype),
!loop_vinfo ? gsi : NULL);
vec_oprnd1 = vect_init_vector (stmt_info, op1, vectype,
!loop_vinfo ? gsi : NULL);
vec_oprnds1.create (slp_node->vec_stmts_size);
for (k = 0; k < slp_node->vec_stmts_size; k++)
vec_oprnds1.quick_push (vec_oprnd1);
}
else if (dt[1] == vect_constant_def)
{
/* Convert the scalar constant shift amounts in-place. */
slp_tree shift = SLP_TREE_CHILDREN (slp_node)[1];
gcc_assert (SLP_TREE_DEF_TYPE (shift) == vect_constant_def);
for (unsigned i = 0;
i < SLP_TREE_SCALAR_OPS (shift).length (); ++i)
{
SLP_TREE_SCALAR_OPS (shift)[i]
= fold_convert (TREE_TYPE (vectype),
SLP_TREE_SCALAR_OPS (shift)[i]);
gcc_assert ((TREE_CODE (SLP_TREE_SCALAR_OPS (shift)[i])
== INTEGER_CST));
}
}
else
gcc_assert (TYPE_MODE (op1_vectype) == TYPE_MODE (vectype));
}
/* vec_oprnd1 is available if operand 1 should be of a scalar-type
(a special case for certain kind of vector shifts); otherwise,
operand 1 should be of a vector type (the usual case). */
if (vec_oprnd1)
vect_get_vec_defs (op0, NULL_TREE, stmt_info, &vec_oprnds0, NULL,
slp_node);
else
vect_get_vec_defs (op0, op1, stmt_info, &vec_oprnds0, &vec_oprnds1,
slp_node);
}
else
vect_get_vec_defs_for_stmt_copy (vinfo, &vec_oprnds0, &vec_oprnds1);
/* Arguments are ready. Create the new vector stmt. */
stmt_vec_info new_stmt_info = NULL;
FOR_EACH_VEC_ELT (vec_oprnds0, i, vop0)
{
vop1 = vec_oprnds1[i];
gassign *new_stmt = gimple_build_assign (vec_dest, code, vop0, vop1);
new_temp = make_ssa_name (vec_dest, new_stmt);
gimple_assign_set_lhs (new_stmt, new_temp);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (slp_node)
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
}
if (slp_node)
continue;
if (j == 0)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
vec_oprnds0.release ();
vec_oprnds1.release ();
return true;
}
/* Function vectorizable_operation.
Check if STMT_INFO performs a binary, unary or ternary operation that can
be vectorized.
If VEC_STMT is also passed, vectorize STMT_INFO: create a vectorized
stmt to replace it, put it in VEC_STMT, and insert it at GSI.
Return true if STMT_INFO is vectorizable in this way. */
static bool
vectorizable_operation (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt, slp_tree slp_node,
stmt_vector_for_cost *cost_vec)
{
tree vec_dest;
tree scalar_dest;
tree op0, op1 = NULL_TREE, op2 = NULL_TREE;
tree vectype;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
enum tree_code code, orig_code;
machine_mode vec_mode;
tree new_temp;
int op_type;
optab optab;
bool target_support_p;
enum vect_def_type dt[3]
= {vect_unknown_def_type, vect_unknown_def_type, vect_unknown_def_type};
int ndts = 3;
stmt_vec_info prev_stmt_info;
poly_uint64 nunits_in;
poly_uint64 nunits_out;
tree vectype_out;
int ncopies, vec_num;
int j, i;
vec<tree> vec_oprnds0 = vNULL;
vec<tree> vec_oprnds1 = vNULL;
vec<tree> vec_oprnds2 = vNULL;
tree vop0, vop1, vop2;
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
vec_info *vinfo = stmt_info->vinfo;
if (!STMT_VINFO_RELEVANT_P (stmt_info) && !bb_vinfo)
return false;
if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def
&& ! vec_stmt)
return false;
/* Is STMT a vectorizable binary/unary operation? */
gassign *stmt = dyn_cast <gassign *> (stmt_info->stmt);
if (!stmt)
return false;
if (TREE_CODE (gimple_assign_lhs (stmt)) != SSA_NAME)
return false;
orig_code = code = gimple_assign_rhs_code (stmt);
/* Shifts are handled in vectorizable_shift. */
if (code == LSHIFT_EXPR
|| code == RSHIFT_EXPR
|| code == LROTATE_EXPR
|| code == RROTATE_EXPR)
return false;
/* Comparisons are handled in vectorizable_comparison. */
if (TREE_CODE_CLASS (code) == tcc_comparison)
return false;
/* Conditions are handled in vectorizable_condition. */
if (code == COND_EXPR)
return false;
/* For pointer addition and subtraction, we should use the normal
plus and minus for the vector operation. */
if (code == POINTER_PLUS_EXPR)
code = PLUS_EXPR;
if (code == POINTER_DIFF_EXPR)
code = MINUS_EXPR;
/* Support only unary or binary operations. */
op_type = TREE_CODE_LENGTH (code);
if (op_type != unary_op && op_type != binary_op && op_type != ternary_op)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"num. args = %d (not unary/binary/ternary op).\n",
op_type);
return false;
}
scalar_dest = gimple_assign_lhs (stmt);
vectype_out = STMT_VINFO_VECTYPE (stmt_info);
/* Most operations cannot handle bit-precision types without extra
truncations. */
bool mask_op_p = VECTOR_BOOLEAN_TYPE_P (vectype_out);
if (!mask_op_p
&& !type_has_mode_precision_p (TREE_TYPE (scalar_dest))
/* Exception are bitwise binary operations. */
&& code != BIT_IOR_EXPR
&& code != BIT_XOR_EXPR
&& code != BIT_AND_EXPR)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"bit-precision arithmetic not supported.\n");
return false;
}
op0 = gimple_assign_rhs1 (stmt);
if (!vect_is_simple_use (op0, vinfo, &dt[0], &vectype))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
/* If op0 is an external or constant def, infer the vector type
from the scalar type. */
if (!vectype)
{
/* For boolean type we cannot determine vectype by
invariant value (don't know whether it is a vector
of booleans or vector of integers). We use output
vectype because operations on boolean don't change
type. */
if (VECT_SCALAR_BOOLEAN_TYPE_P (TREE_TYPE (op0)))
{
if (!VECT_SCALAR_BOOLEAN_TYPE_P (TREE_TYPE (scalar_dest)))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not supported operation on bool value.\n");
return false;
}
vectype = vectype_out;
}
else
vectype = get_vectype_for_scalar_type (vinfo, TREE_TYPE (op0),
slp_node);
}
if (vec_stmt)
gcc_assert (vectype);
if (!vectype)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"no vectype for scalar type %T\n",
TREE_TYPE (op0));
return false;
}
nunits_out = TYPE_VECTOR_SUBPARTS (vectype_out);
nunits_in = TYPE_VECTOR_SUBPARTS (vectype);
if (maybe_ne (nunits_out, nunits_in))
return false;
tree vectype2 = NULL_TREE, vectype3 = NULL_TREE;
if (op_type == binary_op || op_type == ternary_op)
{
op1 = gimple_assign_rhs2 (stmt);
if (!vect_is_simple_use (op1, vinfo, &dt[1], &vectype2))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
}
if (op_type == ternary_op)
{
op2 = gimple_assign_rhs3 (stmt);
if (!vect_is_simple_use (op2, vinfo, &dt[2], &vectype3))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"use not simple.\n");
return false;
}
}
/* Multiple types in SLP are handled by creating the appropriate number of
vectorized stmts for each SLP node. Hence, NCOPIES is always 1 in
case of SLP. */
if (slp_node)
{
ncopies = 1;
vec_num = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
}
else
{
ncopies = vect_get_num_copies (loop_vinfo, vectype);
vec_num = 1;
}
gcc_assert (ncopies >= 1);
/* Reject attempts to combine mask types with nonmask types, e.g. if
we have an AND between a (nonmask) boolean loaded from memory and
a (mask) boolean result of a comparison.
TODO: We could easily fix these cases up using pattern statements. */
if (VECTOR_BOOLEAN_TYPE_P (vectype) != mask_op_p
|| (vectype2 && VECTOR_BOOLEAN_TYPE_P (vectype2) != mask_op_p)
|| (vectype3 && VECTOR_BOOLEAN_TYPE_P (vectype3) != mask_op_p))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"mixed mask and nonmask vector types\n");
return false;
}
/* Supportable by target? */
vec_mode = TYPE_MODE (vectype);
if (code == MULT_HIGHPART_EXPR)
target_support_p = can_mult_highpart_p (vec_mode, TYPE_UNSIGNED (vectype));
else
{
optab = optab_for_tree_code (code, vectype, optab_default);
if (!optab)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"no optab.\n");
return false;
}
target_support_p = (optab_handler (optab, vec_mode)
!= CODE_FOR_nothing);
}
if (!target_support_p)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"op not supported by target.\n");
/* Check only during analysis. */
if (maybe_ne (GET_MODE_SIZE (vec_mode), UNITS_PER_WORD)
|| (!vec_stmt && !vect_worthwhile_without_simd_p (vinfo, code)))
return false;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"proceeding using word mode.\n");
}
/* Worthwhile without SIMD support? Check only during analysis. */
if (!VECTOR_MODE_P (vec_mode)
&& !vec_stmt
&& !vect_worthwhile_without_simd_p (vinfo, code))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not worthwhile without SIMD support.\n");
return false;
}
int reduc_idx = STMT_VINFO_REDUC_IDX (stmt_info);
vec_loop_masks *masks = (loop_vinfo ? &LOOP_VINFO_MASKS (loop_vinfo) : NULL);
internal_fn cond_fn = get_conditional_internal_fn (code);
if (!vec_stmt) /* transformation not required. */
{
/* If this operation is part of a reduction, a fully-masked loop
should only change the active lanes of the reduction chain,
keeping the inactive lanes as-is. */
if (loop_vinfo
&& LOOP_VINFO_CAN_FULLY_MASK_P (loop_vinfo)
&& reduc_idx >= 0)
{
if (cond_fn == IFN_LAST
|| !direct_internal_fn_supported_p (cond_fn, vectype,
OPTIMIZE_FOR_SPEED))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"can't use a fully-masked loop because no"
" conditional operation is available.\n");
LOOP_VINFO_CAN_FULLY_MASK_P (loop_vinfo) = false;
}
else
vect_record_loop_mask (loop_vinfo, masks, ncopies * vec_num,
vectype, NULL);
}
STMT_VINFO_TYPE (stmt_info) = op_vec_info_type;
DUMP_VECT_SCOPE ("vectorizable_operation");
vect_model_simple_cost (stmt_info, ncopies, dt, ndts, slp_node, cost_vec);
return true;
}
/* Transform. */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"transform binary/unary operation.\n");
bool masked_loop_p = loop_vinfo && LOOP_VINFO_FULLY_MASKED_P (loop_vinfo);
/* POINTER_DIFF_EXPR has pointer arguments which are vectorized as
vectors with unsigned elements, but the result is signed. So, we
need to compute the MINUS_EXPR into vectype temporary and
VIEW_CONVERT_EXPR it into the final vectype_out result. */
tree vec_cvt_dest = NULL_TREE;
if (orig_code == POINTER_DIFF_EXPR)
{
vec_dest = vect_create_destination_var (scalar_dest, vectype);
vec_cvt_dest = vect_create_destination_var (scalar_dest, vectype_out);
}
/* Handle def. */
else
vec_dest = vect_create_destination_var (scalar_dest, vectype_out);
/* In case the vectorization factor (VF) is bigger than the number
of elements that we can fit in a vectype (nunits), we have to generate
more than one vector stmt - i.e - we need to "unroll" the
vector stmt by a factor VF/nunits. In doing so, we record a pointer
from one copy of the vector stmt to the next, in the field
STMT_VINFO_RELATED_STMT. This is necessary in order to allow following
stages to find the correct vector defs to be used when vectorizing
stmts that use the defs of the current stmt. The example below
illustrates the vectorization process when VF=16 and nunits=4 (i.e.,
we need to create 4 vectorized stmts):
before vectorization:
RELATED_STMT VEC_STMT
S1: x = memref - -
S2: z = x + 1 - -
step 1: vectorize stmt S1 (done in vectorizable_load. See more details
there):
RELATED_STMT VEC_STMT
VS1_0: vx0 = memref0 VS1_1 -
VS1_1: vx1 = memref1 VS1_2 -
VS1_2: vx2 = memref2 VS1_3 -
VS1_3: vx3 = memref3 - -
S1: x = load - VS1_0
S2: z = x + 1 - -
step2: vectorize stmt S2 (done here):
To vectorize stmt S2 we first need to find the relevant vector
def for the first operand 'x'. This is, as usual, obtained from
the vector stmt recorded in the STMT_VINFO_VEC_STMT of the stmt
that defines 'x' (S1). This way we find the stmt VS1_0, and the
relevant vector def 'vx0'. Having found 'vx0' we can generate
the vector stmt VS2_0, and as usual, record it in the
STMT_VINFO_VEC_STMT of stmt S2.
When creating the second copy (VS2_1), we obtain the relevant vector
def from the vector stmt recorded in the STMT_VINFO_RELATED_STMT of
stmt VS1_0. This way we find the stmt VS1_1 and the relevant
vector def 'vx1'. Using 'vx1' we create stmt VS2_1 and record a
pointer to it in the STMT_VINFO_RELATED_STMT of the vector stmt VS2_0.
Similarly when creating stmts VS2_2 and VS2_3. This is the resulting
chain of stmts and pointers:
RELATED_STMT VEC_STMT
VS1_0: vx0 = memref0 VS1_1 -
VS1_1: vx1 = memref1 VS1_2 -
VS1_2: vx2 = memref2 VS1_3 -
VS1_3: vx3 = memref3 - -
S1: x = load - VS1_0
VS2_0: vz0 = vx0 + v1 VS2_1 -
VS2_1: vz1 = vx1 + v1 VS2_2 -
VS2_2: vz2 = vx2 + v1 VS2_3 -
VS2_3: vz3 = vx3 + v1 - -
S2: z = x + 1 - VS2_0 */
prev_stmt_info = NULL;
for (j = 0; j < ncopies; j++)
{
/* Handle uses. */
if (j == 0)
{
if (op_type == binary_op)
vect_get_vec_defs (op0, op1, stmt_info, &vec_oprnds0, &vec_oprnds1,
slp_node);
else if (op_type == ternary_op)
{
if (slp_node)
{
auto_vec<vec<tree> > vec_defs(3);
vect_get_slp_defs (slp_node, &vec_defs);
vec_oprnds0 = vec_defs[0];
vec_oprnds1 = vec_defs[1];
vec_oprnds2 = vec_defs[2];
}
else
{
vect_get_vec_defs (op0, op1, stmt_info, &vec_oprnds0,
&vec_oprnds1, NULL);
vect_get_vec_defs (op2, NULL_TREE, stmt_info, &vec_oprnds2,
NULL, NULL);
}
}
else
vect_get_vec_defs (op0, NULL_TREE, stmt_info, &vec_oprnds0, NULL,
slp_node);
}
else
{
vect_get_vec_defs_for_stmt_copy (vinfo, &vec_oprnds0, &vec_oprnds1);
if (op_type == ternary_op)
{
tree vec_oprnd = vec_oprnds2.pop ();
vec_oprnds2.quick_push (vect_get_vec_def_for_stmt_copy (vinfo,
vec_oprnd));
}
}
/* Arguments are ready. Create the new vector stmt. */
stmt_vec_info new_stmt_info = NULL;
FOR_EACH_VEC_ELT (vec_oprnds0, i, vop0)
{
vop1 = ((op_type == binary_op || op_type == ternary_op)
? vec_oprnds1[i] : NULL_TREE);
vop2 = ((op_type == ternary_op)
? vec_oprnds2[i] : NULL_TREE);
if (masked_loop_p && reduc_idx >= 0)
{
/* Perform the operation on active elements only and take
inactive elements from the reduction chain input. */
gcc_assert (!vop2);
vop2 = reduc_idx == 1 ? vop1 : vop0;
tree mask = vect_get_loop_mask (gsi, masks, vec_num * ncopies,
vectype, i * ncopies + j);
gcall *call = gimple_build_call_internal (cond_fn, 4, mask,
vop0, vop1, vop2);
new_temp = make_ssa_name (vec_dest, call);
gimple_call_set_lhs (call, new_temp);
gimple_call_set_nothrow (call, true);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, call, gsi);
}
else
{
gassign *new_stmt = gimple_build_assign (vec_dest, code,
vop0, vop1, vop2);
new_temp = make_ssa_name (vec_dest, new_stmt);
gimple_assign_set_lhs (new_stmt, new_temp);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (vec_cvt_dest)
{
new_temp = build1 (VIEW_CONVERT_EXPR, vectype_out, new_temp);
gassign *new_stmt
= gimple_build_assign (vec_cvt_dest, VIEW_CONVERT_EXPR,
new_temp);
new_temp = make_ssa_name (vec_cvt_dest, new_stmt);
gimple_assign_set_lhs (new_stmt, new_temp);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
}
if (slp_node)
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
}
if (slp_node)
continue;
if (j == 0)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
vec_oprnds0.release ();
vec_oprnds1.release ();
vec_oprnds2.release ();
return true;
}
/* A helper function to ensure data reference DR_INFO's base alignment. */
static void
ensure_base_align (dr_vec_info *dr_info)
{
if (dr_info->misalignment == DR_MISALIGNMENT_UNINITIALIZED)
return;
if (dr_info->base_misaligned)
{
tree base_decl = dr_info->base_decl;
// We should only be able to increase the alignment of a base object if
// we know what its new alignment should be at compile time.
unsigned HOST_WIDE_INT align_base_to =
DR_TARGET_ALIGNMENT (dr_info).to_constant () * BITS_PER_UNIT;
if (decl_in_symtab_p (base_decl))
symtab_node::get (base_decl)->increase_alignment (align_base_to);
else if (DECL_ALIGN (base_decl) < align_base_to)
{
SET_DECL_ALIGN (base_decl, align_base_to);
DECL_USER_ALIGN (base_decl) = 1;
}
dr_info->base_misaligned = false;
}
}
/* Function get_group_alias_ptr_type.
Return the alias type for the group starting at FIRST_STMT_INFO. */
static tree
get_group_alias_ptr_type (stmt_vec_info first_stmt_info)
{
struct data_reference *first_dr, *next_dr;
first_dr = STMT_VINFO_DATA_REF (first_stmt_info);
stmt_vec_info next_stmt_info = DR_GROUP_NEXT_ELEMENT (first_stmt_info);
while (next_stmt_info)
{
next_dr = STMT_VINFO_DATA_REF (next_stmt_info);
if (get_alias_set (DR_REF (first_dr))
!= get_alias_set (DR_REF (next_dr)))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"conflicting alias set types.\n");
return ptr_type_node;
}
next_stmt_info = DR_GROUP_NEXT_ELEMENT (next_stmt_info);
}
return reference_alias_ptr_type (DR_REF (first_dr));
}
/* Function scan_operand_equal_p.
Helper function for check_scan_store. Compare two references
with .GOMP_SIMD_LANE bases. */
static bool
scan_operand_equal_p (tree ref1, tree ref2)
{
tree ref[2] = { ref1, ref2 };
poly_int64 bitsize[2], bitpos[2];
tree offset[2], base[2];
for (int i = 0; i < 2; ++i)
{
machine_mode mode;
int unsignedp, reversep, volatilep = 0;
base[i] = get_inner_reference (ref[i], &bitsize[i], &bitpos[i],
&offset[i], &mode, &unsignedp,
&reversep, &volatilep);
if (reversep || volatilep || maybe_ne (bitpos[i], 0))
return false;
if (TREE_CODE (base[i]) == MEM_REF
&& offset[i] == NULL_TREE
&& TREE_CODE (TREE_OPERAND (base[i], 0)) == SSA_NAME)
{
gimple *def_stmt = SSA_NAME_DEF_STMT (TREE_OPERAND (base[i], 0));
if (is_gimple_assign (def_stmt)
&& gimple_assign_rhs_code (def_stmt) == POINTER_PLUS_EXPR
&& TREE_CODE (gimple_assign_rhs1 (def_stmt)) == ADDR_EXPR
&& TREE_CODE (gimple_assign_rhs2 (def_stmt)) == SSA_NAME)
{
if (maybe_ne (mem_ref_offset (base[i]), 0))
return false;
base[i] = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), 0);
offset[i] = gimple_assign_rhs2 (def_stmt);
}
}
}
if (!operand_equal_p (base[0], base[1], 0))
return false;
if (maybe_ne (bitsize[0], bitsize[1]))
return false;
if (offset[0] != offset[1])
{
if (!offset[0] || !offset[1])
return false;
if (!operand_equal_p (offset[0], offset[1], 0))
{
tree step[2];
for (int i = 0; i < 2; ++i)
{
step[i] = integer_one_node;
if (TREE_CODE (offset[i]) == SSA_NAME)
{
gimple *def_stmt = SSA_NAME_DEF_STMT (offset[i]);
if (is_gimple_assign (def_stmt)
&& gimple_assign_rhs_code (def_stmt) == MULT_EXPR
&& (TREE_CODE (gimple_assign_rhs2 (def_stmt))
== INTEGER_CST))
{
step[i] = gimple_assign_rhs2 (def_stmt);
offset[i] = gimple_assign_rhs1 (def_stmt);
}
}
else if (TREE_CODE (offset[i]) == MULT_EXPR)
{
step[i] = TREE_OPERAND (offset[i], 1);
offset[i] = TREE_OPERAND (offset[i], 0);
}
tree rhs1 = NULL_TREE;
if (TREE_CODE (offset[i]) == SSA_NAME)
{
gimple *def_stmt = SSA_NAME_DEF_STMT (offset[i]);
if (gimple_assign_cast_p (def_stmt))
rhs1 = gimple_assign_rhs1 (def_stmt);
}
else if (CONVERT_EXPR_P (offset[i]))
rhs1 = TREE_OPERAND (offset[i], 0);
if (rhs1
&& INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
&& INTEGRAL_TYPE_P (TREE_TYPE (offset[i]))
&& (TYPE_PRECISION (TREE_TYPE (offset[i]))
>= TYPE_PRECISION (TREE_TYPE (rhs1))))
offset[i] = rhs1;
}
if (!operand_equal_p (offset[0], offset[1], 0)
|| !operand_equal_p (step[0], step[1], 0))
return false;
}
}
return true;
}
enum scan_store_kind {
/* Normal permutation. */
scan_store_kind_perm,
/* Whole vector left shift permutation with zero init. */
scan_store_kind_lshift_zero,
/* Whole vector left shift permutation and VEC_COND_EXPR. */
scan_store_kind_lshift_cond
};
/* Function check_scan_store.
Verify if we can perform the needed permutations or whole vector shifts.
Return -1 on failure, otherwise exact log2 of vectype's nunits.
USE_WHOLE_VECTOR is a vector of enum scan_store_kind which operation
to do at each step. */
static int
scan_store_can_perm_p (tree vectype, tree init,
vec<enum scan_store_kind> *use_whole_vector = NULL)
{
enum machine_mode vec_mode = TYPE_MODE (vectype);
unsigned HOST_WIDE_INT nunits;
if (!TYPE_VECTOR_SUBPARTS (vectype).is_constant (&nunits))
return -1;
int units_log2 = exact_log2 (nunits);
if (units_log2 <= 0)
return -1;
int i;
enum scan_store_kind whole_vector_shift_kind = scan_store_kind_perm;
for (i = 0; i <= units_log2; ++i)
{
unsigned HOST_WIDE_INT j, k;
enum scan_store_kind kind = scan_store_kind_perm;
vec_perm_builder sel (nunits, nunits, 1);
sel.quick_grow (nunits);
if (i == units_log2)
{
for (j = 0; j < nunits; ++j)
sel[j] = nunits - 1;
}
else
{
for (j = 0; j < (HOST_WIDE_INT_1U << i); ++j)
sel[j] = j;
for (k = 0; j < nunits; ++j, ++k)
sel[j] = nunits + k;
}
vec_perm_indices indices (sel, i == units_log2 ? 1 : 2, nunits);
if (!can_vec_perm_const_p (vec_mode, indices))
{
if (i == units_log2)
return -1;
if (whole_vector_shift_kind == scan_store_kind_perm)
{
if (optab_handler (vec_shl_optab, vec_mode) == CODE_FOR_nothing)
return -1;
whole_vector_shift_kind = scan_store_kind_lshift_zero;
/* Whole vector shifts shift in zeros, so if init is all zero
constant, there is no need to do anything further. */
if ((TREE_CODE (init) != INTEGER_CST
&& TREE_CODE (init) != REAL_CST)
|| !initializer_zerop (init))
{
tree masktype = truth_type_for (vectype);
if (!expand_vec_cond_expr_p (vectype, masktype, VECTOR_CST))
return -1;
whole_vector_shift_kind = scan_store_kind_lshift_cond;
}
}
kind = whole_vector_shift_kind;
}
if (use_whole_vector)
{
if (kind != scan_store_kind_perm && use_whole_vector->is_empty ())
use_whole_vector->safe_grow_cleared (i);
if (kind != scan_store_kind_perm || !use_whole_vector->is_empty ())
use_whole_vector->safe_push (kind);
}
}
return units_log2;
}
/* Function check_scan_store.
Check magic stores for #pragma omp scan {in,ex}clusive reductions. */
static bool
check_scan_store (stmt_vec_info stmt_info, tree vectype,
enum vect_def_type rhs_dt, bool slp, tree mask,
vect_memory_access_type memory_access_type)
{
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info);
tree ref_type;
gcc_assert (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) > 1);
if (slp
|| mask
|| memory_access_type != VMAT_CONTIGUOUS
|| TREE_CODE (DR_BASE_ADDRESS (dr_info->dr)) != ADDR_EXPR
|| !VAR_P (TREE_OPERAND (DR_BASE_ADDRESS (dr_info->dr), 0))
|| loop_vinfo == NULL
|| LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
|| STMT_VINFO_GROUPED_ACCESS (stmt_info)
|| !integer_zerop (get_dr_vinfo_offset (dr_info))
|| !integer_zerop (DR_INIT (dr_info->dr))
|| !(ref_type = reference_alias_ptr_type (DR_REF (dr_info->dr)))
|| !alias_sets_conflict_p (get_alias_set (vectype),
get_alias_set (TREE_TYPE (ref_type))))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"unsupported OpenMP scan store.\n");
return false;
}
/* We need to pattern match code built by OpenMP lowering and simplified
by following optimizations into something we can handle.
#pragma omp simd reduction(inscan,+:r)
for (...)
{
r += something ();
#pragma omp scan inclusive (r)
use (r);
}
shall have body with:
// Initialization for input phase, store the reduction initializer:
_20 = .GOMP_SIMD_LANE (simduid.3_14(D), 0);
_21 = .GOMP_SIMD_LANE (simduid.3_14(D), 1);
D.2042[_21] = 0;
// Actual input phase:
...
r.0_5 = D.2042[_20];
_6 = _4 + r.0_5;
D.2042[_20] = _6;
// Initialization for scan phase:
_25 = .GOMP_SIMD_LANE (simduid.3_14(D), 2);
_26 = D.2043[_25];
_27 = D.2042[_25];
_28 = _26 + _27;
D.2043[_25] = _28;
D.2042[_25] = _28;
// Actual scan phase:
...
r.1_8 = D.2042[_20];
...
The "omp simd array" variable D.2042 holds the privatized copy used
inside of the loop and D.2043 is another one that holds copies of
the current original list item. The separate GOMP_SIMD_LANE ifn
kinds are there in order to allow optimizing the initializer store
and combiner sequence, e.g. if it is originally some C++ish user
defined reduction, but allow the vectorizer to pattern recognize it
and turn into the appropriate vectorized scan.
For exclusive scan, this is slightly different:
#pragma omp simd reduction(inscan,+:r)
for (...)
{
use (r);
#pragma omp scan exclusive (r)
r += something ();
}
shall have body with:
// Initialization for input phase, store the reduction initializer:
_20 = .GOMP_SIMD_LANE (simduid.3_14(D), 0);
_21 = .GOMP_SIMD_LANE (simduid.3_14(D), 1);
D.2042[_21] = 0;
// Actual input phase:
...
r.0_5 = D.2042[_20];
_6 = _4 + r.0_5;
D.2042[_20] = _6;
// Initialization for scan phase:
_25 = .GOMP_SIMD_LANE (simduid.3_14(D), 3);
_26 = D.2043[_25];
D.2044[_25] = _26;
_27 = D.2042[_25];
_28 = _26 + _27;
D.2043[_25] = _28;
// Actual scan phase:
...
r.1_8 = D.2044[_20];
... */
if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) == 2)
{
/* Match the D.2042[_21] = 0; store above. Just require that
it is a constant or external definition store. */
if (rhs_dt != vect_constant_def && rhs_dt != vect_external_def)
{
fail_init:
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"unsupported OpenMP scan initializer store.\n");
return false;
}
if (! loop_vinfo->scan_map)
loop_vinfo->scan_map = new hash_map<tree, tree>;
tree var = TREE_OPERAND (DR_BASE_ADDRESS (dr_info->dr), 0);
tree &cached = loop_vinfo->scan_map->get_or_insert (var);
if (cached)
goto fail_init;
cached = gimple_assign_rhs1 (STMT_VINFO_STMT (stmt_info));
/* These stores can be vectorized normally. */
return true;
}
if (rhs_dt != vect_internal_def)
{
fail:
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"unsupported OpenMP scan combiner pattern.\n");
return false;
}
gimple *stmt = STMT_VINFO_STMT (stmt_info);
tree rhs = gimple_assign_rhs1 (stmt);
if (TREE_CODE (rhs) != SSA_NAME)
goto fail;
gimple *other_store_stmt = NULL;
tree var = TREE_OPERAND (DR_BASE_ADDRESS (dr_info->dr), 0);
bool inscan_var_store
= lookup_attribute ("omp simd inscan", DECL_ATTRIBUTES (var)) != NULL;
if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) == 4)
{
if (!inscan_var_store)
{
use_operand_p use_p;
imm_use_iterator iter;
FOR_EACH_IMM_USE_FAST (use_p, iter, rhs)
{
gimple *use_stmt = USE_STMT (use_p);
if (use_stmt == stmt || is_gimple_debug (use_stmt))
continue;
if (gimple_bb (use_stmt) != gimple_bb (stmt)
|| !is_gimple_assign (use_stmt)
|| gimple_assign_rhs_class (use_stmt) != GIMPLE_BINARY_RHS
|| other_store_stmt
|| TREE_CODE (gimple_assign_lhs (use_stmt)) != SSA_NAME)
goto fail;
other_store_stmt = use_stmt;
}
if (other_store_stmt == NULL)
goto fail;
rhs = gimple_assign_lhs (other_store_stmt);
if (!single_imm_use (rhs, &use_p, &other_store_stmt))
goto fail;
}
}
else if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) == 3)
{
use_operand_p use_p;
imm_use_iterator iter;
FOR_EACH_IMM_USE_FAST (use_p, iter, rhs)
{
gimple *use_stmt = USE_STMT (use_p);
if (use_stmt == stmt || is_gimple_debug (use_stmt))
continue;
if (other_store_stmt)
goto fail;
other_store_stmt = use_stmt;
}
}
else
goto fail;
gimple *def_stmt = SSA_NAME_DEF_STMT (rhs);
if (gimple_bb (def_stmt) != gimple_bb (stmt)
|| !is_gimple_assign (def_stmt)
|| gimple_assign_rhs_class (def_stmt) != GIMPLE_BINARY_RHS)
goto fail;
enum tree_code code = gimple_assign_rhs_code (def_stmt);
/* For pointer addition, we should use the normal plus for the vector
operation. */
switch (code)
{
case POINTER_PLUS_EXPR:
code = PLUS_EXPR;
break;
case MULT_HIGHPART_EXPR:
goto fail;
default:
break;
}
if (TREE_CODE_LENGTH (code) != binary_op || !commutative_tree_code (code))
goto fail;
tree rhs1 = gimple_assign_rhs1 (def_stmt);
tree rhs2 = gimple_assign_rhs2 (def_stmt);
if (TREE_CODE (rhs1) != SSA_NAME || TREE_CODE (rhs2) != SSA_NAME)
goto fail;
gimple *load1_stmt = SSA_NAME_DEF_STMT (rhs1);
gimple *load2_stmt = SSA_NAME_DEF_STMT (rhs2);
if (gimple_bb (load1_stmt) != gimple_bb (stmt)
|| !gimple_assign_load_p (load1_stmt)
|| gimple_bb (load2_stmt) != gimple_bb (stmt)
|| !gimple_assign_load_p (load2_stmt))
goto fail;
stmt_vec_info load1_stmt_info = loop_vinfo->lookup_stmt (load1_stmt);
stmt_vec_info load2_stmt_info = loop_vinfo->lookup_stmt (load2_stmt);
if (load1_stmt_info == NULL
|| load2_stmt_info == NULL
|| (STMT_VINFO_SIMD_LANE_ACCESS_P (load1_stmt_info)
!= STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info))
|| (STMT_VINFO_SIMD_LANE_ACCESS_P (load2_stmt_info)
!= STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info)))
goto fail;
if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) == 4 && inscan_var_store)
{
dr_vec_info *load1_dr_info = STMT_VINFO_DR_INFO (load1_stmt_info);
if (TREE_CODE (DR_BASE_ADDRESS (load1_dr_info->dr)) != ADDR_EXPR
|| !VAR_P (TREE_OPERAND (DR_BASE_ADDRESS (load1_dr_info->dr), 0)))
goto fail;
tree var1 = TREE_OPERAND (DR_BASE_ADDRESS (load1_dr_info->dr), 0);
tree lrhs;
if (lookup_attribute ("omp simd inscan", DECL_ATTRIBUTES (var1)))
lrhs = rhs1;
else
lrhs = rhs2;
use_operand_p use_p;
imm_use_iterator iter;
FOR_EACH_IMM_USE_FAST (use_p, iter, lrhs)
{
gimple *use_stmt = USE_STMT (use_p);
if (use_stmt == def_stmt || is_gimple_debug (use_stmt))
continue;
if (other_store_stmt)
goto fail;
other_store_stmt = use_stmt;
}
}
if (other_store_stmt == NULL)
goto fail;
if (gimple_bb (other_store_stmt) != gimple_bb (stmt)
|| !gimple_store_p (other_store_stmt))
goto fail;
stmt_vec_info other_store_stmt_info
= loop_vinfo->lookup_stmt (other_store_stmt);
if (other_store_stmt_info == NULL
|| (STMT_VINFO_SIMD_LANE_ACCESS_P (other_store_stmt_info)
!= STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info)))
goto fail;
gimple *stmt1 = stmt;
gimple *stmt2 = other_store_stmt;
if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) == 4 && !inscan_var_store)
std::swap (stmt1, stmt2);
if (scan_operand_equal_p (gimple_assign_lhs (stmt1),
gimple_assign_rhs1 (load2_stmt)))
{
std::swap (rhs1, rhs2);
std::swap (load1_stmt, load2_stmt);
std::swap (load1_stmt_info, load2_stmt_info);
}
if (!scan_operand_equal_p (gimple_assign_lhs (stmt1),
gimple_assign_rhs1 (load1_stmt)))
goto fail;
tree var3 = NULL_TREE;
if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) == 3
&& !scan_operand_equal_p (gimple_assign_lhs (stmt2),
gimple_assign_rhs1 (load2_stmt)))
goto fail;
else if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) == 4)
{
dr_vec_info *load2_dr_info = STMT_VINFO_DR_INFO (load2_stmt_info);
if (TREE_CODE (DR_BASE_ADDRESS (load2_dr_info->dr)) != ADDR_EXPR
|| !VAR_P (TREE_OPERAND (DR_BASE_ADDRESS (load2_dr_info->dr), 0)))
goto fail;
var3 = TREE_OPERAND (DR_BASE_ADDRESS (load2_dr_info->dr), 0);
if (!lookup_attribute ("omp simd array", DECL_ATTRIBUTES (var3))
|| lookup_attribute ("omp simd inscan", DECL_ATTRIBUTES (var3))
|| lookup_attribute ("omp simd inscan exclusive",
DECL_ATTRIBUTES (var3)))
goto fail;
}
dr_vec_info *other_dr_info = STMT_VINFO_DR_INFO (other_store_stmt_info);
if (TREE_CODE (DR_BASE_ADDRESS (other_dr_info->dr)) != ADDR_EXPR
|| !VAR_P (TREE_OPERAND (DR_BASE_ADDRESS (other_dr_info->dr), 0)))
goto fail;
tree var1 = TREE_OPERAND (DR_BASE_ADDRESS (dr_info->dr), 0);
tree var2 = TREE_OPERAND (DR_BASE_ADDRESS (other_dr_info->dr), 0);
if (!lookup_attribute ("omp simd array", DECL_ATTRIBUTES (var1))
|| !lookup_attribute ("omp simd array", DECL_ATTRIBUTES (var2))
|| (!lookup_attribute ("omp simd inscan", DECL_ATTRIBUTES (var1)))
== (!lookup_attribute ("omp simd inscan", DECL_ATTRIBUTES (var2))))
goto fail;
if (lookup_attribute ("omp simd inscan", DECL_ATTRIBUTES (var1)))
std::swap (var1, var2);
if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) == 4)
{
if (!lookup_attribute ("omp simd inscan exclusive",
DECL_ATTRIBUTES (var1)))
goto fail;
var1 = var3;
}
if (loop_vinfo->scan_map == NULL)
goto fail;
tree *init = loop_vinfo->scan_map->get (var1);
if (init == NULL)
goto fail;
/* The IL is as expected, now check if we can actually vectorize it.
Inclusive scan:
_26 = D.2043[_25];
_27 = D.2042[_25];
_28 = _26 + _27;
D.2043[_25] = _28;
D.2042[_25] = _28;
should be vectorized as (where _40 is the vectorized rhs
from the D.2042[_21] = 0; store):
_30 = MEM <vector(8) int> [(int *)&D.2043];
_31 = MEM <vector(8) int> [(int *)&D.2042];
_32 = VEC_PERM_EXPR <_40, _31, { 0, 8, 9, 10, 11, 12, 13, 14 }>;
_33 = _31 + _32;
// _33 = { _31[0], _31[0]+_31[1], _31[1]+_31[2], ..., _31[6]+_31[7] };
_34 = VEC_PERM_EXPR <_40, _33, { 0, 1, 8, 9, 10, 11, 12, 13 }>;
_35 = _33 + _34;
// _35 = { _31[0], _31[0]+_31[1], _31[0]+.._31[2], _31[0]+.._31[3],
// _31[1]+.._31[4], ... _31[4]+.._31[7] };
_36 = VEC_PERM_EXPR <_40, _35, { 0, 1, 2, 3, 8, 9, 10, 11 }>;
_37 = _35 + _36;
// _37 = { _31[0], _31[0]+_31[1], _31[0]+.._31[2], _31[0]+.._31[3],
// _31[0]+.._31[4], ... _31[0]+.._31[7] };
_38 = _30 + _37;
_39 = VEC_PERM_EXPR <_38, _38, { 7, 7, 7, 7, 7, 7, 7, 7 }>;
MEM <vector(8) int> [(int *)&D.2043] = _39;
MEM <vector(8) int> [(int *)&D.2042] = _38;
Exclusive scan:
_26 = D.2043[_25];
D.2044[_25] = _26;
_27 = D.2042[_25];
_28 = _26 + _27;
D.2043[_25] = _28;
should be vectorized as (where _40 is the vectorized rhs
from the D.2042[_21] = 0; store):
_30 = MEM <vector(8) int> [(int *)&D.2043];
_31 = MEM <vector(8) int> [(int *)&D.2042];
_32 = VEC_PERM_EXPR <_40, _31, { 0, 8, 9, 10, 11, 12, 13, 14 }>;
_33 = VEC_PERM_EXPR <_40, _32, { 0, 8, 9, 10, 11, 12, 13, 14 }>;
_34 = _32 + _33;
// _34 = { 0, _31[0], _31[0]+_31[1], _31[1]+_31[2], _31[2]+_31[3],
// _31[3]+_31[4], ... _31[5]+.._31[6] };
_35 = VEC_PERM_EXPR <_40, _34, { 0, 1, 8, 9, 10, 11, 12, 13 }>;
_36 = _34 + _35;
// _36 = { 0, _31[0], _31[0]+_31[1], _31[0]+.._31[2], _31[0]+.._31[3],
// _31[1]+.._31[4], ... _31[3]+.._31[6] };
_37 = VEC_PERM_EXPR <_40, _36, { 0, 1, 2, 3, 8, 9, 10, 11 }>;
_38 = _36 + _37;
// _38 = { 0, _31[0], _31[0]+_31[1], _31[0]+.._31[2], _31[0]+.._31[3],
// _31[0]+.._31[4], ... _31[0]+.._31[6] };
_39 = _30 + _38;
_50 = _31 + _39;
_51 = VEC_PERM_EXPR <_50, _50, { 7, 7, 7, 7, 7, 7, 7, 7 }>;
MEM <vector(8) int> [(int *)&D.2044] = _39;
MEM <vector(8) int> [(int *)&D.2042] = _51; */
enum machine_mode vec_mode = TYPE_MODE (vectype);
optab optab = optab_for_tree_code (code, vectype, optab_default);
if (!optab || optab_handler (optab, vec_mode) == CODE_FOR_nothing)
goto fail;
int units_log2 = scan_store_can_perm_p (vectype, *init);
if (units_log2 == -1)
goto fail;
return true;
}
/* Function vectorizable_scan_store.
Helper of vectorizable_score, arguments like on vectorizable_store.
Handle only the transformation, checking is done in check_scan_store. */
static bool
vectorizable_scan_store (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt, int ncopies)
{
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info);
tree ref_type = reference_alias_ptr_type (DR_REF (dr_info->dr));
vec_info *vinfo = stmt_info->vinfo;
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"transform scan store. ncopies = %d\n", ncopies);
gimple *stmt = STMT_VINFO_STMT (stmt_info);
tree rhs = gimple_assign_rhs1 (stmt);
gcc_assert (TREE_CODE (rhs) == SSA_NAME);
tree var = TREE_OPERAND (DR_BASE_ADDRESS (dr_info->dr), 0);
bool inscan_var_store
= lookup_attribute ("omp simd inscan", DECL_ATTRIBUTES (var)) != NULL;
if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) == 4 && !inscan_var_store)
{
use_operand_p use_p;
imm_use_iterator iter;
FOR_EACH_IMM_USE_FAST (use_p, iter, rhs)
{
gimple *use_stmt = USE_STMT (use_p);
if (use_stmt == stmt || is_gimple_debug (use_stmt))
continue;
rhs = gimple_assign_lhs (use_stmt);
break;
}
}
gimple *def_stmt = SSA_NAME_DEF_STMT (rhs);
enum tree_code code = gimple_assign_rhs_code (def_stmt);
if (code == POINTER_PLUS_EXPR)
code = PLUS_EXPR;
gcc_assert (TREE_CODE_LENGTH (code) == binary_op
&& commutative_tree_code (code));
tree rhs1 = gimple_assign_rhs1 (def_stmt);
tree rhs2 = gimple_assign_rhs2 (def_stmt);
gcc_assert (TREE_CODE (rhs1) == SSA_NAME && TREE_CODE (rhs2) == SSA_NAME);
gimple *load1_stmt = SSA_NAME_DEF_STMT (rhs1);
gimple *load2_stmt = SSA_NAME_DEF_STMT (rhs2);
stmt_vec_info load1_stmt_info = loop_vinfo->lookup_stmt (load1_stmt);
stmt_vec_info load2_stmt_info = loop_vinfo->lookup_stmt (load2_stmt);
dr_vec_info *load1_dr_info = STMT_VINFO_DR_INFO (load1_stmt_info);
dr_vec_info *load2_dr_info = STMT_VINFO_DR_INFO (load2_stmt_info);
tree var1 = TREE_OPERAND (DR_BASE_ADDRESS (load1_dr_info->dr), 0);
tree var2 = TREE_OPERAND (DR_BASE_ADDRESS (load2_dr_info->dr), 0);
if (lookup_attribute ("omp simd inscan", DECL_ATTRIBUTES (var1)))
{
std::swap (rhs1, rhs2);
std::swap (var1, var2);
std::swap (load1_dr_info, load2_dr_info);
}
tree *init = loop_vinfo->scan_map->get (var1);
gcc_assert (init);
unsigned HOST_WIDE_INT nunits;
if (!TYPE_VECTOR_SUBPARTS (vectype).is_constant (&nunits))
gcc_unreachable ();
auto_vec<enum scan_store_kind, 16> use_whole_vector;
int units_log2 = scan_store_can_perm_p (vectype, *init, &use_whole_vector);
gcc_assert (units_log2 > 0);
auto_vec<tree, 16> perms;
perms.quick_grow (units_log2 + 1);
tree zero_vec = NULL_TREE, masktype = NULL_TREE;
for (int i = 0; i <= units_log2; ++i)
{
unsigned HOST_WIDE_INT j, k;
vec_perm_builder sel (nunits, nunits, 1);
sel.quick_grow (nunits);
if (i == units_log2)
for (j = 0; j < nunits; ++j)
sel[j] = nunits - 1;
else
{
for (j = 0; j < (HOST_WIDE_INT_1U << i); ++j)
sel[j] = j;
for (k = 0; j < nunits; ++j, ++k)
sel[j] = nunits + k;
}
vec_perm_indices indices (sel, i == units_log2 ? 1 : 2, nunits);
if (!use_whole_vector.is_empty ()
&& use_whole_vector[i] != scan_store_kind_perm)
{
if (zero_vec == NULL_TREE)
zero_vec = build_zero_cst (vectype);
if (masktype == NULL_TREE
&& use_whole_vector[i] == scan_store_kind_lshift_cond)
masktype = truth_type_for (vectype);
perms[i] = vect_gen_perm_mask_any (vectype, indices);
}
else
perms[i] = vect_gen_perm_mask_checked (vectype, indices);
}
stmt_vec_info prev_stmt_info = NULL;
tree vec_oprnd1 = NULL_TREE;
tree vec_oprnd2 = NULL_TREE;
tree vec_oprnd3 = NULL_TREE;
tree dataref_ptr = DR_BASE_ADDRESS (dr_info->dr);
tree dataref_offset = build_int_cst (ref_type, 0);
tree bump = vect_get_data_ptr_increment (dr_info, vectype, VMAT_CONTIGUOUS);
tree ldataref_ptr = NULL_TREE;
tree orig = NULL_TREE;
if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) == 4 && !inscan_var_store)
ldataref_ptr = DR_BASE_ADDRESS (load1_dr_info->dr);
for (int j = 0; j < ncopies; j++)
{
stmt_vec_info new_stmt_info;
if (j == 0)
{
vec_oprnd1 = vect_get_vec_def_for_operand (*init, stmt_info);
if (ldataref_ptr == NULL)
vec_oprnd2 = vect_get_vec_def_for_operand (rhs1, stmt_info);
vec_oprnd3 = vect_get_vec_def_for_operand (rhs2, stmt_info);
orig = vec_oprnd3;
}
else
{
vec_oprnd1 = vect_get_vec_def_for_stmt_copy (vinfo, vec_oprnd1);
if (ldataref_ptr == NULL)
vec_oprnd2 = vect_get_vec_def_for_stmt_copy (vinfo, vec_oprnd2);
vec_oprnd3 = vect_get_vec_def_for_stmt_copy (vinfo, vec_oprnd3);
if (!inscan_var_store)
dataref_offset = int_const_binop (PLUS_EXPR, dataref_offset, bump);
}
if (ldataref_ptr)
{
vec_oprnd2 = make_ssa_name (vectype);
tree data_ref = fold_build2 (MEM_REF, vectype,
unshare_expr (ldataref_ptr),
dataref_offset);
vect_copy_ref_info (data_ref, DR_REF (load1_dr_info->dr));
gimple *g = gimple_build_assign (vec_oprnd2, data_ref);
new_stmt_info = vect_finish_stmt_generation (stmt_info, g, gsi);
if (prev_stmt_info == NULL)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
tree v = vec_oprnd2;
for (int i = 0; i < units_log2; ++i)
{
tree new_temp = make_ssa_name (vectype);
gimple *g = gimple_build_assign (new_temp, VEC_PERM_EXPR,
(zero_vec
&& (use_whole_vector[i]
!= scan_store_kind_perm))
? zero_vec : vec_oprnd1, v,
perms[i]);
new_stmt_info = vect_finish_stmt_generation (stmt_info, g, gsi);
if (prev_stmt_info == NULL)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
if (zero_vec && use_whole_vector[i] == scan_store_kind_lshift_cond)
{
/* Whole vector shift shifted in zero bits, but if *init
is not initializer_zerop, we need to replace those elements
with elements from vec_oprnd1. */
tree_vector_builder vb (masktype, nunits, 1);
for (unsigned HOST_WIDE_INT k = 0; k < nunits; ++k)
vb.quick_push (k < (HOST_WIDE_INT_1U << i)
? boolean_false_node : boolean_true_node);
tree new_temp2 = make_ssa_name (vectype);
g = gimple_build_assign (new_temp2, VEC_COND_EXPR, vb.build (),
new_temp, vec_oprnd1);
new_stmt_info = vect_finish_stmt_generation (stmt_info, g, gsi);
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
new_temp = new_temp2;
}
/* For exclusive scan, perform the perms[i] permutation once
more. */
if (i == 0
&& STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) == 4
&& v == vec_oprnd2)
{
v = new_temp;
--i;
continue;
}
tree new_temp2 = make_ssa_name (vectype);
g = gimple_build_assign (new_temp2, code, v, new_temp);
new_stmt_info = vect_finish_stmt_generation (stmt_info, g, gsi);
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
v = new_temp2;
}
tree new_temp = make_ssa_name (vectype);
gimple *g = gimple_build_assign (new_temp, code, orig, v);
new_stmt_info = vect_finish_stmt_generation (stmt_info, g, gsi);
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
tree last_perm_arg = new_temp;
/* For exclusive scan, new_temp computed above is the exclusive scan
prefix sum. Turn it into inclusive prefix sum for the broadcast
of the last element into orig. */
if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) == 4)
{
last_perm_arg = make_ssa_name (vectype);
g = gimple_build_assign (last_perm_arg, code, new_temp, vec_oprnd2);
new_stmt_info = vect_finish_stmt_generation (stmt_info, g, gsi);
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
orig = make_ssa_name (vectype);
g = gimple_build_assign (orig, VEC_PERM_EXPR, last_perm_arg,
last_perm_arg, perms[units_log2]);
new_stmt_info = vect_finish_stmt_generation (stmt_info, g, gsi);
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
if (!inscan_var_store)
{
tree data_ref = fold_build2 (MEM_REF, vectype,
unshare_expr (dataref_ptr),
dataref_offset);
vect_copy_ref_info (data_ref, DR_REF (dr_info->dr));
g = gimple_build_assign (data_ref, new_temp);
new_stmt_info = vect_finish_stmt_generation (stmt_info, g, gsi);
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
}
if (inscan_var_store)
for (int j = 0; j < ncopies; j++)
{
if (j != 0)
dataref_offset = int_const_binop (PLUS_EXPR, dataref_offset, bump);
tree data_ref = fold_build2 (MEM_REF, vectype,
unshare_expr (dataref_ptr),
dataref_offset);
vect_copy_ref_info (data_ref, DR_REF (dr_info->dr));
gimple *g = gimple_build_assign (data_ref, orig);
stmt_vec_info new_stmt_info
= vect_finish_stmt_generation (stmt_info, g, gsi);
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
return true;
}
/* Function vectorizable_store.
Check if STMT_INFO defines a non scalar data-ref (array/pointer/structure)
that can be vectorized.
If VEC_STMT is also passed, vectorize STMT_INFO: create a vectorized
stmt to replace it, put it in VEC_STMT, and insert it at GSI.
Return true if STMT_INFO is vectorizable in this way. */
static bool
vectorizable_store (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt, slp_tree slp_node,
stmt_vector_for_cost *cost_vec)
{
tree data_ref;
tree op;
tree vec_oprnd = NULL_TREE;
tree elem_type;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
class loop *loop = NULL;
machine_mode vec_mode;
tree dummy;
enum dr_alignment_support alignment_support_scheme;
enum vect_def_type rhs_dt = vect_unknown_def_type;
enum vect_def_type mask_dt = vect_unknown_def_type;
stmt_vec_info prev_stmt_info = NULL;
tree dataref_ptr = NULL_TREE;
tree dataref_offset = NULL_TREE;
gimple *ptr_incr = NULL;
int ncopies;
int j;
stmt_vec_info first_stmt_info;
bool grouped_store;
unsigned int group_size, i;
vec<tree> oprnds = vNULL;
vec<tree> result_chain = vNULL;
tree offset = NULL_TREE;
vec<tree> vec_oprnds = vNULL;
bool slp = (slp_node != NULL);
unsigned int vec_num;
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
vec_info *vinfo = stmt_info->vinfo;
tree aggr_type;
gather_scatter_info gs_info;
poly_uint64 vf;
vec_load_store_type vls_type;
tree ref_type;
if (!STMT_VINFO_RELEVANT_P (stmt_info) && !bb_vinfo)
return false;
if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def
&& ! vec_stmt)
return false;
/* Is vectorizable store? */
tree mask = NULL_TREE, mask_vectype = NULL_TREE;
if (gassign *assign = dyn_cast <gassign *> (stmt_info->stmt))
{
tree scalar_dest = gimple_assign_lhs (assign);
if (TREE_CODE (scalar_dest) == VIEW_CONVERT_EXPR
&& is_pattern_stmt_p (stmt_info))
scalar_dest = TREE_OPERAND (scalar_dest, 0);
if (TREE_CODE (scalar_dest) != ARRAY_REF
&& TREE_CODE (scalar_dest) != BIT_FIELD_REF
&& TREE_CODE (scalar_dest) != INDIRECT_REF
&& TREE_CODE (scalar_dest) != COMPONENT_REF
&& TREE_CODE (scalar_dest) != IMAGPART_EXPR
&& TREE_CODE (scalar_dest) != REALPART_EXPR
&& TREE_CODE (scalar_dest) != MEM_REF)
return false;
}
else
{
gcall *call = dyn_cast <gcall *> (stmt_info->stmt);
if (!call || !gimple_call_internal_p (call))
return false;
internal_fn ifn = gimple_call_internal_fn (call);
if (!internal_store_fn_p (ifn))
return false;
if (slp_node != NULL)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"SLP of masked stores not supported.\n");
return false;
}
int mask_index = internal_fn_mask_index (ifn);
if (mask_index >= 0)
{
mask = gimple_call_arg (call, mask_index);
if (!vect_check_scalar_mask (stmt_info, mask, &mask_dt,
&mask_vectype))
return false;
}
}
op = vect_get_store_rhs (stmt_info);
/* Cannot have hybrid store SLP -- that would mean storing to the
same location twice. */
gcc_assert (slp == PURE_SLP_STMT (stmt_info));
tree vectype = STMT_VINFO_VECTYPE (stmt_info), rhs_vectype = NULL_TREE;
poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
if (loop_vinfo)
{
loop = LOOP_VINFO_LOOP (loop_vinfo);
vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
}
else
vf = 1;
/* Multiple types in SLP are handled by creating the appropriate number of
vectorized stmts for each SLP node. Hence, NCOPIES is always 1 in
case of SLP. */
if (slp)
ncopies = 1;
else
ncopies = vect_get_num_copies (loop_vinfo, vectype);
gcc_assert (ncopies >= 1);
/* FORNOW. This restriction should be relaxed. */
if (loop && nested_in_vect_loop_p (loop, stmt_info) && ncopies > 1)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"multiple types in nested loop.\n");
return false;
}
if (!vect_check_store_rhs (stmt_info, op, &rhs_dt, &rhs_vectype, &vls_type))
return false;
elem_type = TREE_TYPE (vectype);
vec_mode = TYPE_MODE (vectype);
if (!STMT_VINFO_DATA_REF (stmt_info))
return false;
vect_memory_access_type memory_access_type;
if (!get_load_store_type (stmt_info, vectype, slp, mask, vls_type, ncopies,
&memory_access_type, &gs_info))
return false;
if (mask)
{
if (memory_access_type == VMAT_CONTIGUOUS)
{
if (!VECTOR_MODE_P (vec_mode)
|| !can_vec_mask_load_store_p (vec_mode,
TYPE_MODE (mask_vectype), false))
return false;
}
else if (memory_access_type != VMAT_LOAD_STORE_LANES
&& (memory_access_type != VMAT_GATHER_SCATTER
|| (gs_info.decl && !VECTOR_BOOLEAN_TYPE_P (mask_vectype))))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"unsupported access type for masked store.\n");
return false;
}
}
else
{
/* FORNOW. In some cases can vectorize even if data-type not supported
(e.g. - array initialization with 0). */
if (optab_handler (mov_optab, vec_mode) == CODE_FOR_nothing)
return false;
}
dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info), *first_dr_info = NULL;
grouped_store = (STMT_VINFO_GROUPED_ACCESS (stmt_info)
&& memory_access_type != VMAT_GATHER_SCATTER
&& (slp || memory_access_type != VMAT_CONTIGUOUS));
if (grouped_store)
{
first_stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
first_dr_info = STMT_VINFO_DR_INFO (first_stmt_info);
group_size = DR_GROUP_SIZE (first_stmt_info);
}
else
{
first_stmt_info = stmt_info;
first_dr_info = dr_info;
group_size = vec_num = 1;
}
if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) > 1 && !vec_stmt)
{
if (!check_scan_store (stmt_info, vectype, rhs_dt, slp, mask,
memory_access_type))
return false;
}
if (!vec_stmt) /* transformation not required. */
{
STMT_VINFO_MEMORY_ACCESS_TYPE (stmt_info) = memory_access_type;
if (loop_vinfo
&& LOOP_VINFO_CAN_FULLY_MASK_P (loop_vinfo))
check_load_store_masking (loop_vinfo, vectype, vls_type, group_size,
memory_access_type, &gs_info, mask);
STMT_VINFO_TYPE (stmt_info) = store_vec_info_type;
vect_model_store_cost (stmt_info, ncopies, rhs_dt, memory_access_type,
vls_type, slp_node, cost_vec);
return true;
}
gcc_assert (memory_access_type == STMT_VINFO_MEMORY_ACCESS_TYPE (stmt_info));
/* Transform. */
ensure_base_align (dr_info);
if (memory_access_type == VMAT_GATHER_SCATTER && gs_info.decl)
{
tree vec_oprnd0 = NULL_TREE, vec_oprnd1 = NULL_TREE, src;
tree arglist = TYPE_ARG_TYPES (TREE_TYPE (gs_info.decl));
tree rettype, srctype, ptrtype, idxtype, masktype, scaletype;
tree ptr, var, scale, vec_mask;
tree mask_arg = NULL_TREE, mask_op = NULL_TREE, perm_mask = NULL_TREE;
tree mask_halfvectype = mask_vectype;
edge pe = loop_preheader_edge (loop);
gimple_seq seq;
basic_block new_bb;
enum { NARROW, NONE, WIDEN } modifier;
poly_uint64 scatter_off_nunits
= TYPE_VECTOR_SUBPARTS (gs_info.offset_vectype);
if (known_eq (nunits, scatter_off_nunits))
modifier = NONE;
else if (known_eq (nunits * 2, scatter_off_nunits))
{
modifier = WIDEN;
/* Currently gathers and scatters are only supported for
fixed-length vectors. */
unsigned int count = scatter_off_nunits.to_constant ();
vec_perm_builder sel (count, count, 1);
for (i = 0; i < (unsigned int) count; ++i)
sel.quick_push (i | (count / 2));
vec_perm_indices indices (sel, 1, count);
perm_mask = vect_gen_perm_mask_checked (gs_info.offset_vectype,
indices);
gcc_assert (perm_mask != NULL_TREE);
}
else if (known_eq (nunits, scatter_off_nunits * 2))
{
modifier = NARROW;
/* Currently gathers and scatters are only supported for
fixed-length vectors. */
unsigned int count = nunits.to_constant ();
vec_perm_builder sel (count, count, 1);
for (i = 0; i < (unsigned int) count; ++i)
sel.quick_push (i | (count / 2));
vec_perm_indices indices (sel, 2, count);
perm_mask = vect_gen_perm_mask_checked (vectype, indices);
gcc_assert (perm_mask != NULL_TREE);
ncopies *= 2;
if (mask)
mask_halfvectype = truth_type_for (gs_info.offset_vectype);
}
else
gcc_unreachable ();
rettype = TREE_TYPE (TREE_TYPE (gs_info.decl));
ptrtype = TREE_VALUE (arglist); arglist = TREE_CHAIN (arglist);
masktype = TREE_VALUE (arglist); arglist = TREE_CHAIN (arglist);
idxtype = TREE_VALUE (arglist); arglist = TREE_CHAIN (arglist);
srctype = TREE_VALUE (arglist); arglist = TREE_CHAIN (arglist);
scaletype = TREE_VALUE (arglist);
gcc_checking_assert (TREE_CODE (masktype) == INTEGER_TYPE
&& TREE_CODE (rettype) == VOID_TYPE);
ptr = fold_convert (ptrtype, gs_info.base);
if (!is_gimple_min_invariant (ptr))
{
ptr = force_gimple_operand (ptr, &seq, true, NULL_TREE);
new_bb = gsi_insert_seq_on_edge_immediate (pe, seq);
gcc_assert (!new_bb);
}
if (mask == NULL_TREE)
{
mask_arg = build_int_cst (masktype, -1);
mask_arg = vect_init_vector (stmt_info, mask_arg, masktype, NULL);
}
scale = build_int_cst (scaletype, gs_info.scale);
prev_stmt_info = NULL;
for (j = 0; j < ncopies; ++j)
{
if (j == 0)
{
src = vec_oprnd1 = vect_get_vec_def_for_operand (op, stmt_info);
op = vec_oprnd0 = vect_get_vec_def_for_operand (gs_info.offset,
stmt_info);
if (mask)
{
tree mask_vectype = truth_type_for (vectype);
mask_op = vec_mask
= vect_get_vec_def_for_operand (mask,
stmt_info, mask_vectype);
}
}
else if (modifier != NONE && (j & 1))
{
if (modifier == WIDEN)
{
src
= vec_oprnd1 = vect_get_vec_def_for_stmt_copy (vinfo,
vec_oprnd1);
op = permute_vec_elements (vec_oprnd0, vec_oprnd0, perm_mask,
stmt_info, gsi);
if (mask)
mask_op
= vec_mask = vect_get_vec_def_for_stmt_copy (vinfo,
vec_mask);
}
else if (modifier == NARROW)
{
src = permute_vec_elements (vec_oprnd1, vec_oprnd1, perm_mask,
stmt_info, gsi);
op = vec_oprnd0 = vect_get_vec_def_for_stmt_copy (vinfo,
vec_oprnd0);
}
else
gcc_unreachable ();
}
else
{
src = vec_oprnd1 = vect_get_vec_def_for_stmt_copy (vinfo,
vec_oprnd1);
op = vec_oprnd0 = vect_get_vec_def_for_stmt_copy (vinfo,
vec_oprnd0);
if (mask)
mask_op = vec_mask = vect_get_vec_def_for_stmt_copy (vinfo,
vec_mask);
}
if (!useless_type_conversion_p (srctype, TREE_TYPE (src)))
{
gcc_assert (known_eq (TYPE_VECTOR_SUBPARTS (TREE_TYPE (src)),
TYPE_VECTOR_SUBPARTS (srctype)));
var = vect_get_new_ssa_name (srctype, vect_simple_var);
src = build1 (VIEW_CONVERT_EXPR, srctype, src);
gassign *new_stmt
= gimple_build_assign (var, VIEW_CONVERT_EXPR, src);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
src = var;
}
if (!useless_type_conversion_p (idxtype, TREE_TYPE (op)))
{
gcc_assert (known_eq (TYPE_VECTOR_SUBPARTS (TREE_TYPE (op)),
TYPE_VECTOR_SUBPARTS (idxtype)));
var = vect_get_new_ssa_name (idxtype, vect_simple_var);
op = build1 (VIEW_CONVERT_EXPR, idxtype, op);
gassign *new_stmt
= gimple_build_assign (var, VIEW_CONVERT_EXPR, op);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
op = var;
}
if (mask)
{
tree utype;
mask_arg = mask_op;
if (modifier == NARROW)
{
var = vect_get_new_ssa_name (mask_halfvectype,
vect_simple_var);
gassign *new_stmt
= gimple_build_assign (var, (j & 1) ? VEC_UNPACK_HI_EXPR
: VEC_UNPACK_LO_EXPR,
mask_op);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
mask_arg = var;
}
tree optype = TREE_TYPE (mask_arg);
if (TYPE_MODE (masktype) == TYPE_MODE (optype))
utype = masktype;
else
utype = lang_hooks.types.type_for_mode (TYPE_MODE (optype), 1);
var = vect_get_new_ssa_name (utype, vect_scalar_var);
mask_arg = build1 (VIEW_CONVERT_EXPR, utype, mask_arg);
gassign *new_stmt
= gimple_build_assign (var, VIEW_CONVERT_EXPR, mask_arg);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
mask_arg = var;
if (!useless_type_conversion_p (masktype, utype))
{
gcc_assert (TYPE_PRECISION (utype)
<= TYPE_PRECISION (masktype));
var = vect_get_new_ssa_name (masktype, vect_scalar_var);
new_stmt = gimple_build_assign (var, NOP_EXPR, mask_arg);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
mask_arg = var;
}
}
gcall *new_stmt
= gimple_build_call (gs_info.decl, 5, ptr, mask_arg, op, src, scale);
stmt_vec_info new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (prev_stmt_info == NULL)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
return true;
}
else if (STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) >= 3)
return vectorizable_scan_store (stmt_info, gsi, vec_stmt, ncopies);
if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
DR_GROUP_STORE_COUNT (DR_GROUP_FIRST_ELEMENT (stmt_info))++;
if (grouped_store)
{
/* FORNOW */
gcc_assert (!loop || !nested_in_vect_loop_p (loop, stmt_info));
/* We vectorize all the stmts of the interleaving group when we
reach the last stmt in the group. */
if (DR_GROUP_STORE_COUNT (first_stmt_info)
< DR_GROUP_SIZE (first_stmt_info)
&& !slp)
{
*vec_stmt = NULL;
return true;
}
if (slp)
{
grouped_store = false;
/* VEC_NUM is the number of vect stmts to be created for this
group. */
vec_num = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
first_stmt_info = SLP_TREE_SCALAR_STMTS (slp_node)[0];
gcc_assert (DR_GROUP_FIRST_ELEMENT (first_stmt_info)
== first_stmt_info);
first_dr_info = STMT_VINFO_DR_INFO (first_stmt_info);
op = vect_get_store_rhs (first_stmt_info);
}
else
/* VEC_NUM is the number of vect stmts to be created for this
group. */
vec_num = group_size;
ref_type = get_group_alias_ptr_type (first_stmt_info);
}
else
ref_type = reference_alias_ptr_type (DR_REF (first_dr_info->dr));
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"transform store. ncopies = %d\n", ncopies);
if (memory_access_type == VMAT_ELEMENTWISE
|| memory_access_type == VMAT_STRIDED_SLP)
{
gimple_stmt_iterator incr_gsi;
bool insert_after;
gimple *incr;
tree offvar;
tree ivstep;
tree running_off;
tree stride_base, stride_step, alias_off;
tree vec_oprnd;
tree dr_offset;
unsigned int g;
/* Checked by get_load_store_type. */
unsigned int const_nunits = nunits.to_constant ();
gcc_assert (!LOOP_VINFO_FULLY_MASKED_P (loop_vinfo));
gcc_assert (!nested_in_vect_loop_p (loop, stmt_info));
dr_offset = get_dr_vinfo_offset (first_dr_info);
stride_base
= fold_build_pointer_plus
(DR_BASE_ADDRESS (first_dr_info->dr),
size_binop (PLUS_EXPR,
convert_to_ptrofftype (dr_offset),
convert_to_ptrofftype (DR_INIT (first_dr_info->dr))));
stride_step = fold_convert (sizetype, DR_STEP (first_dr_info->dr));
/* For a store with loop-invariant (but other than power-of-2)
stride (i.e. not a grouped access) like so:
for (i = 0; i < n; i += stride)
array[i] = ...;
we generate a new induction variable and new stores from
the components of the (vectorized) rhs:
for (j = 0; ; j += VF*stride)
vectemp = ...;
tmp1 = vectemp[0];
array[j] = tmp1;
tmp2 = vectemp[1];
array[j + stride] = tmp2;
...
*/
unsigned nstores = const_nunits;
unsigned lnel = 1;
tree ltype = elem_type;
tree lvectype = vectype;
if (slp)
{
if (group_size < const_nunits
&& const_nunits % group_size == 0)
{
nstores = const_nunits / group_size;
lnel = group_size;
ltype = build_vector_type (elem_type, group_size);
lvectype = vectype;
/* First check if vec_extract optab doesn't support extraction
of vector elts directly. */
scalar_mode elmode = SCALAR_TYPE_MODE (elem_type);
machine_mode vmode;
if (!VECTOR_MODE_P (TYPE_MODE (vectype))
|| !related_vector_mode (TYPE_MODE (vectype), elmode,
group_size).exists (&vmode)
|| (convert_optab_handler (vec_extract_optab,
TYPE_MODE (vectype), vmode)
== CODE_FOR_nothing))
{
/* Try to avoid emitting an extract of vector elements
by performing the extracts using an integer type of the
same size, extracting from a vector of those and then
re-interpreting it as the original vector type if
supported. */
unsigned lsize
= group_size * GET_MODE_BITSIZE (elmode);
unsigned int lnunits = const_nunits / group_size;
/* If we can't construct such a vector fall back to
element extracts from the original vector type and
element size stores. */
if (int_mode_for_size (lsize, 0).exists (&elmode)
&& VECTOR_MODE_P (TYPE_MODE (vectype))
&& related_vector_mode (TYPE_MODE (vectype), elmode,
lnunits).exists (&vmode)
&& (convert_optab_handler (vec_extract_optab,
vmode, elmode)
!= CODE_FOR_nothing))
{
nstores = lnunits;
lnel = group_size;
ltype = build_nonstandard_integer_type (lsize, 1);
lvectype = build_vector_type (ltype, nstores);
}
/* Else fall back to vector extraction anyway.
Fewer stores are more important than avoiding spilling
of the vector we extract from. Compared to the
construction case in vectorizable_load no store-forwarding
issue exists here for reasonable archs. */
}
}
else if (group_size >= const_nunits
&& group_size % const_nunits == 0)
{
nstores = 1;
lnel = const_nunits;
ltype = vectype;
lvectype = vectype;
}
ltype = build_aligned_type (ltype, TYPE_ALIGN (elem_type));
ncopies = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
}
ivstep = stride_step;
ivstep = fold_build2 (MULT_EXPR, TREE_TYPE (ivstep), ivstep,
build_int_cst (TREE_TYPE (ivstep), vf));
standard_iv_increment_position (loop, &incr_gsi, &insert_after);
stride_base = cse_and_gimplify_to_preheader (loop_vinfo, stride_base);
ivstep = cse_and_gimplify_to_preheader (loop_vinfo, ivstep);
create_iv (stride_base, ivstep, NULL,
loop, &incr_gsi, insert_after,
&offvar, NULL);
incr = gsi_stmt (incr_gsi);
loop_vinfo->add_stmt (incr);
stride_step = cse_and_gimplify_to_preheader (loop_vinfo, stride_step);
prev_stmt_info = NULL;
alias_off = build_int_cst (ref_type, 0);
stmt_vec_info next_stmt_info = first_stmt_info;
for (g = 0; g < group_size; g++)
{
running_off = offvar;
if (g)
{
tree size = TYPE_SIZE_UNIT (ltype);
tree pos = fold_build2 (MULT_EXPR, sizetype, size_int (g),
size);
tree newoff = copy_ssa_name (running_off, NULL);
incr = gimple_build_assign (newoff, POINTER_PLUS_EXPR,
running_off, pos);
vect_finish_stmt_generation (stmt_info, incr, gsi);
running_off = newoff;
}
unsigned int group_el = 0;
unsigned HOST_WIDE_INT
elsz = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (vectype)));
for (j = 0; j < ncopies; j++)
{
/* We've set op and dt above, from vect_get_store_rhs,
and first_stmt_info == stmt_info. */
if (j == 0)
{
if (slp)
{
vect_get_vec_defs (op, NULL_TREE, stmt_info,
&vec_oprnds, NULL, slp_node);
vec_oprnd = vec_oprnds[0];
}
else
{
op = vect_get_store_rhs (next_stmt_info);
vec_oprnd = vect_get_vec_def_for_operand
(op, next_stmt_info);
}
}
else
{
if (slp)
vec_oprnd = vec_oprnds[j];
else
vec_oprnd = vect_get_vec_def_for_stmt_copy (vinfo,
vec_oprnd);
}
/* Pun the vector to extract from if necessary. */
if (lvectype != vectype)
{
tree tem = make_ssa_name (lvectype);
gimple *pun
= gimple_build_assign (tem, build1 (VIEW_CONVERT_EXPR,
lvectype, vec_oprnd));
vect_finish_stmt_generation (stmt_info, pun, gsi);
vec_oprnd = tem;
}
for (i = 0; i < nstores; i++)
{
tree newref, newoff;
gimple *incr, *assign;
tree size = TYPE_SIZE (ltype);
/* Extract the i'th component. */
tree pos = fold_build2 (MULT_EXPR, bitsizetype,
bitsize_int (i), size);
tree elem = fold_build3 (BIT_FIELD_REF, ltype, vec_oprnd,
size, pos);
elem = force_gimple_operand_gsi (gsi, elem, true,
NULL_TREE, true,
GSI_SAME_STMT);
tree this_off = build_int_cst (TREE_TYPE (alias_off),
group_el * elsz);
newref = build2 (MEM_REF, ltype,
running_off, this_off);
vect_copy_ref_info (newref, DR_REF (first_dr_info->dr));
/* And store it to *running_off. */
assign = gimple_build_assign (newref, elem);
stmt_vec_info assign_info
= vect_finish_stmt_generation (stmt_info, assign, gsi);
group_el += lnel;
if (! slp
|| group_el == group_size)
{
newoff = copy_ssa_name (running_off, NULL);
incr = gimple_build_assign (newoff, POINTER_PLUS_EXPR,
running_off, stride_step);
vect_finish_stmt_generation (stmt_info, incr, gsi);
running_off = newoff;
group_el = 0;
}
if (g == group_size - 1
&& !slp)
{
if (j == 0 && i == 0)
STMT_VINFO_VEC_STMT (stmt_info)
= *vec_stmt = assign_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = assign_info;
prev_stmt_info = assign_info;
}
}
}
next_stmt_info = DR_GROUP_NEXT_ELEMENT (next_stmt_info);
if (slp)
break;
}
vec_oprnds.release ();
return true;
}
auto_vec<tree> dr_chain (group_size);
oprnds.create (group_size);
/* Gather-scatter accesses perform only component accesses, alignment
is irrelevant for them. */
if (memory_access_type == VMAT_GATHER_SCATTER)
alignment_support_scheme = dr_unaligned_supported;
else
alignment_support_scheme
= vect_supportable_dr_alignment (first_dr_info, false);
gcc_assert (alignment_support_scheme);
vec_loop_masks *loop_masks
= (loop_vinfo && LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
? &LOOP_VINFO_MASKS (loop_vinfo)
: NULL);
/* Targets with store-lane instructions must not require explicit
realignment. vect_supportable_dr_alignment always returns either
dr_aligned or dr_unaligned_supported for masked operations. */
gcc_assert ((memory_access_type != VMAT_LOAD_STORE_LANES
&& !mask
&& !loop_masks)
|| alignment_support_scheme == dr_aligned
|| alignment_support_scheme == dr_unaligned_supported);
if (memory_access_type == VMAT_CONTIGUOUS_DOWN
|| memory_access_type == VMAT_CONTIGUOUS_REVERSE)
offset = size_int (-TYPE_VECTOR_SUBPARTS (vectype) + 1);
tree bump;
tree vec_offset = NULL_TREE;
if (STMT_VINFO_GATHER_SCATTER_P (stmt_info))
{
aggr_type = NULL_TREE;
bump = NULL_TREE;
}
else if (memory_access_type == VMAT_GATHER_SCATTER)
{
aggr_type = elem_type;
vect_get_strided_load_store_ops (stmt_info, loop_vinfo, &gs_info,
&bump, &vec_offset);
}
else
{
if (memory_access_type == VMAT_LOAD_STORE_LANES)
aggr_type = build_array_type_nelts (elem_type, vec_num * nunits);
else
aggr_type = vectype;
bump = vect_get_data_ptr_increment (dr_info, aggr_type,
memory_access_type);
}
if (mask)
LOOP_VINFO_HAS_MASK_STORE (loop_vinfo) = true;
/* In case the vectorization factor (VF) is bigger than the number
of elements that we can fit in a vectype (nunits), we have to generate
more than one vector stmt - i.e - we need to "unroll" the
vector stmt by a factor VF/nunits. For more details see documentation in
vect_get_vec_def_for_copy_stmt. */
/* In case of interleaving (non-unit grouped access):
S1: &base + 2 = x2
S2: &base = x0
S3: &base + 1 = x1
S4: &base + 3 = x3
We create vectorized stores starting from base address (the access of the
first stmt in the chain (S2 in the above example), when the last store stmt
of the chain (S4) is reached:
VS1: &base = vx2
VS2: &base + vec_size*1 = vx0
VS3: &base + vec_size*2 = vx1
VS4: &base + vec_size*3 = vx3
Then permutation statements are generated:
VS5: vx5 = VEC_PERM_EXPR < vx0, vx3, {0, 8, 1, 9, 2, 10, 3, 11} >
VS6: vx6 = VEC_PERM_EXPR < vx0, vx3, {4, 12, 5, 13, 6, 14, 7, 15} >
...
And they are put in STMT_VINFO_VEC_STMT of the corresponding scalar stmts
(the order of the data-refs in the output of vect_permute_store_chain
corresponds to the order of scalar stmts in the interleaving chain - see
the documentation of vect_permute_store_chain()).
In case of both multiple types and interleaving, above vector stores and
permutation stmts are created for every copy. The result vector stmts are
put in STMT_VINFO_VEC_STMT for the first copy and in the corresponding
STMT_VINFO_RELATED_STMT for the next copies.
*/
prev_stmt_info = NULL;
tree vec_mask = NULL_TREE;
for (j = 0; j < ncopies; j++)
{
stmt_vec_info new_stmt_info;
if (j == 0)
{
if (slp)
{
/* Get vectorized arguments for SLP_NODE. */
vect_get_vec_defs (op, NULL_TREE, stmt_info, &vec_oprnds,
NULL, slp_node);
vec_oprnd = vec_oprnds[0];
}
else
{
/* For interleaved stores we collect vectorized defs for all the
stores in the group in DR_CHAIN and OPRNDS. DR_CHAIN is then
used as an input to vect_permute_store_chain(), and OPRNDS as
an input to vect_get_vec_def_for_stmt_copy() for the next copy.
If the store is not grouped, DR_GROUP_SIZE is 1, and DR_CHAIN and
OPRNDS are of size 1. */
stmt_vec_info next_stmt_info = first_stmt_info;
for (i = 0; i < group_size; i++)
{
/* Since gaps are not supported for interleaved stores,
DR_GROUP_SIZE is the exact number of stmts in the chain.
Therefore, NEXT_STMT_INFO can't be NULL_TREE. In case
that there is no interleaving, DR_GROUP_SIZE is 1,
and only one iteration of the loop will be executed. */
op = vect_get_store_rhs (next_stmt_info);
vec_oprnd = vect_get_vec_def_for_operand
(op, next_stmt_info);
dr_chain.quick_push (vec_oprnd);
oprnds.quick_push (vec_oprnd);
next_stmt_info = DR_GROUP_NEXT_ELEMENT (next_stmt_info);
}
if (mask)
vec_mask = vect_get_vec_def_for_operand (mask, stmt_info,
mask_vectype);
}
/* We should have catched mismatched types earlier. */
gcc_assert (useless_type_conversion_p (vectype,
TREE_TYPE (vec_oprnd)));
bool simd_lane_access_p
= STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) != 0;
if (simd_lane_access_p
&& !loop_masks
&& TREE_CODE (DR_BASE_ADDRESS (first_dr_info->dr)) == ADDR_EXPR
&& VAR_P (TREE_OPERAND (DR_BASE_ADDRESS (first_dr_info->dr), 0))
&& integer_zerop (get_dr_vinfo_offset (first_dr_info))
&& integer_zerop (DR_INIT (first_dr_info->dr))
&& alias_sets_conflict_p (get_alias_set (aggr_type),
get_alias_set (TREE_TYPE (ref_type))))
{
dataref_ptr = unshare_expr (DR_BASE_ADDRESS (first_dr_info->dr));
dataref_offset = build_int_cst (ref_type, 0);
}
else if (STMT_VINFO_GATHER_SCATTER_P (stmt_info))
vect_get_gather_scatter_ops (loop, stmt_info, &gs_info,
&dataref_ptr, &vec_offset);
else
dataref_ptr
= vect_create_data_ref_ptr (first_stmt_info, aggr_type,
simd_lane_access_p ? loop : NULL,
offset, &dummy, gsi, &ptr_incr,
simd_lane_access_p, NULL_TREE, bump);
}
else
{
/* For interleaved stores we created vectorized defs for all the
defs stored in OPRNDS in the previous iteration (previous copy).
DR_CHAIN is then used as an input to vect_permute_store_chain(),
and OPRNDS as an input to vect_get_vec_def_for_stmt_copy() for the
next copy.
If the store is not grouped, DR_GROUP_SIZE is 1, and DR_CHAIN and
OPRNDS are of size 1. */
for (i = 0; i < group_size; i++)
{
op = oprnds[i];
vec_oprnd = vect_get_vec_def_for_stmt_copy (vinfo, op);
dr_chain[i] = vec_oprnd;
oprnds[i] = vec_oprnd;
}
if (mask)
vec_mask = vect_get_vec_def_for_stmt_copy (vinfo, vec_mask);
if (dataref_offset)
dataref_offset
= int_const_binop (PLUS_EXPR, dataref_offset, bump);
else if (STMT_VINFO_GATHER_SCATTER_P (stmt_info))
vec_offset = vect_get_vec_def_for_stmt_copy (vinfo, vec_offset);
else
dataref_ptr = bump_vector_ptr (dataref_ptr, ptr_incr, gsi,
stmt_info, bump);
}
if (memory_access_type == VMAT_LOAD_STORE_LANES)
{
tree vec_array;
/* Get an array into which we can store the individual vectors. */
vec_array = create_vector_array (vectype, vec_num);
/* Invalidate the current contents of VEC_ARRAY. This should
become an RTL clobber too, which prevents the vector registers
from being upward-exposed. */
vect_clobber_variable (stmt_info, gsi, vec_array);
/* Store the individual vectors into the array. */
for (i = 0; i < vec_num; i++)
{
vec_oprnd = dr_chain[i];
write_vector_array (stmt_info, gsi, vec_oprnd, vec_array, i);
}
tree final_mask = NULL;
if (loop_masks)
final_mask = vect_get_loop_mask (gsi, loop_masks, ncopies,
vectype, j);
if (vec_mask)
final_mask = prepare_load_store_mask (mask_vectype, final_mask,
vec_mask, gsi);
gcall *call;
if (final_mask)
{
/* Emit:
MASK_STORE_LANES (DATAREF_PTR, ALIAS_PTR, VEC_MASK,
VEC_ARRAY). */
unsigned int align = TYPE_ALIGN (TREE_TYPE (vectype));
tree alias_ptr = build_int_cst (ref_type, align);
call = gimple_build_call_internal (IFN_MASK_STORE_LANES, 4,
dataref_ptr, alias_ptr,
final_mask, vec_array);
}
else
{
/* Emit:
MEM_REF[...all elements...] = STORE_LANES (VEC_ARRAY). */
data_ref = create_array_ref (aggr_type, dataref_ptr, ref_type);
call = gimple_build_call_internal (IFN_STORE_LANES, 1,
vec_array);
gimple_call_set_lhs (call, data_ref);
}
gimple_call_set_nothrow (call, true);
new_stmt_info = vect_finish_stmt_generation (stmt_info, call, gsi);
/* Record that VEC_ARRAY is now dead. */
vect_clobber_variable (stmt_info, gsi, vec_array);
}
else
{
new_stmt_info = NULL;
if (grouped_store)
{
if (j == 0)
result_chain.create (group_size);
/* Permute. */
vect_permute_store_chain (dr_chain, group_size, stmt_info, gsi,
&result_chain);
}
stmt_vec_info next_stmt_info = first_stmt_info;
for (i = 0; i < vec_num; i++)
{
unsigned misalign;
unsigned HOST_WIDE_INT align;
tree final_mask = NULL_TREE;
if (loop_masks)
final_mask = vect_get_loop_mask (gsi, loop_masks,
vec_num * ncopies,
vectype, vec_num * j + i);
if (vec_mask)
final_mask = prepare_load_store_mask (mask_vectype, final_mask,
vec_mask, gsi);
if (memory_access_type == VMAT_GATHER_SCATTER)
{
tree scale = size_int (gs_info.scale);
gcall *call;
if (loop_masks)
call = gimple_build_call_internal
(IFN_MASK_SCATTER_STORE, 5, dataref_ptr, vec_offset,
scale, vec_oprnd, final_mask);
else
call = gimple_build_call_internal
(IFN_SCATTER_STORE, 4, dataref_ptr, vec_offset,
scale, vec_oprnd);
gimple_call_set_nothrow (call, true);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, call, gsi);
break;
}
if (i > 0)
/* Bump the vector pointer. */
dataref_ptr = bump_vector_ptr (dataref_ptr, ptr_incr, gsi,
stmt_info, bump);
if (slp)
vec_oprnd = vec_oprnds[i];
else if (grouped_store)
/* For grouped stores vectorized defs are interleaved in
vect_permute_store_chain(). */
vec_oprnd = result_chain[i];
align = known_alignment (DR_TARGET_ALIGNMENT (first_dr_info));
if (aligned_access_p (first_dr_info))
misalign = 0;
else if (DR_MISALIGNMENT (first_dr_info) == -1)
{
align = dr_alignment (vect_dr_behavior (first_dr_info));
misalign = 0;
}
else
misalign = DR_MISALIGNMENT (first_dr_info);
if (dataref_offset == NULL_TREE
&& TREE_CODE (dataref_ptr) == SSA_NAME)
set_ptr_info_alignment (get_ptr_info (dataref_ptr), align,
misalign);
if (memory_access_type == VMAT_CONTIGUOUS_REVERSE)
{
tree perm_mask = perm_mask_for_reverse (vectype);
tree perm_dest = vect_create_destination_var
(vect_get_store_rhs (stmt_info), vectype);
tree new_temp = make_ssa_name (perm_dest);
/* Generate the permute statement. */
gimple *perm_stmt
= gimple_build_assign (new_temp, VEC_PERM_EXPR, vec_oprnd,
vec_oprnd, perm_mask);
vect_finish_stmt_generation (stmt_info, perm_stmt, gsi);
perm_stmt = SSA_NAME_DEF_STMT (new_temp);
vec_oprnd = new_temp;
}
/* Arguments are ready. Create the new vector stmt. */
if (final_mask)
{
align = least_bit_hwi (misalign | align);
tree ptr = build_int_cst (ref_type, align * BITS_PER_UNIT);
gcall *call
= gimple_build_call_internal (IFN_MASK_STORE, 4,
dataref_ptr, ptr,
final_mask, vec_oprnd);
gimple_call_set_nothrow (call, true);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, call, gsi);
}
else
{
data_ref = fold_build2 (MEM_REF, vectype,
dataref_ptr,
dataref_offset
? dataref_offset
: build_int_cst (ref_type, 0));
if (aligned_access_p (first_dr_info))
;
else if (DR_MISALIGNMENT (first_dr_info) == -1)
TREE_TYPE (data_ref)
= build_aligned_type (TREE_TYPE (data_ref),
align * BITS_PER_UNIT);
else
TREE_TYPE (data_ref)
= build_aligned_type (TREE_TYPE (data_ref),
TYPE_ALIGN (elem_type));
vect_copy_ref_info (data_ref, DR_REF (first_dr_info->dr));
gassign *new_stmt
= gimple_build_assign (data_ref, vec_oprnd);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
if (slp)
continue;
next_stmt_info = DR_GROUP_NEXT_ELEMENT (next_stmt_info);
if (!next_stmt_info)
break;
}
}
if (!slp)
{
if (j == 0)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
}
oprnds.release ();
result_chain.release ();
vec_oprnds.release ();
return true;
}
/* Given a vector type VECTYPE, turns permutation SEL into the equivalent
VECTOR_CST mask. No checks are made that the target platform supports the
mask, so callers may wish to test can_vec_perm_const_p separately, or use
vect_gen_perm_mask_checked. */
tree
vect_gen_perm_mask_any (tree vectype, const vec_perm_indices &sel)
{
tree mask_type;
poly_uint64 nunits = sel.length ();
gcc_assert (known_eq (nunits, TYPE_VECTOR_SUBPARTS (vectype)));
mask_type = build_vector_type (ssizetype, nunits);
return vec_perm_indices_to_tree (mask_type, sel);
}
/* Checked version of vect_gen_perm_mask_any. Asserts can_vec_perm_const_p,
i.e. that the target supports the pattern _for arbitrary input vectors_. */
tree
vect_gen_perm_mask_checked (tree vectype, const vec_perm_indices &sel)
{
gcc_assert (can_vec_perm_const_p (TYPE_MODE (vectype), sel));
return vect_gen_perm_mask_any (vectype, sel);
}
/* Given a vector variable X and Y, that was generated for the scalar
STMT_INFO, generate instructions to permute the vector elements of X and Y
using permutation mask MASK_VEC, insert them at *GSI and return the
permuted vector variable. */
static tree
permute_vec_elements (tree x, tree y, tree mask_vec, stmt_vec_info stmt_info,
gimple_stmt_iterator *gsi)
{
tree vectype = TREE_TYPE (x);
tree perm_dest, data_ref;
gimple *perm_stmt;
tree scalar_dest = gimple_get_lhs (stmt_info->stmt);
if (scalar_dest && TREE_CODE (scalar_dest) == SSA_NAME)
perm_dest = vect_create_destination_var (scalar_dest, vectype);
else
perm_dest = vect_get_new_vect_var (vectype, vect_simple_var, NULL);
data_ref = make_ssa_name (perm_dest);
/* Generate the permute statement. */
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, x, y, mask_vec);
vect_finish_stmt_generation (stmt_info, perm_stmt, gsi);
return data_ref;
}
/* Hoist the definitions of all SSA uses on STMT_INFO out of the loop LOOP,
inserting them on the loops preheader edge. Returns true if we
were successful in doing so (and thus STMT_INFO can be moved then),
otherwise returns false. */
static bool
hoist_defs_of_uses (stmt_vec_info stmt_info, class loop *loop)
{
ssa_op_iter i;
tree op;
bool any = false;
FOR_EACH_SSA_TREE_OPERAND (op, stmt_info->stmt, i, SSA_OP_USE)
{
gimple *def_stmt = SSA_NAME_DEF_STMT (op);
if (!gimple_nop_p (def_stmt)
&& flow_bb_inside_loop_p (loop, gimple_bb (def_stmt)))
{
/* Make sure we don't need to recurse. While we could do
so in simple cases when there are more complex use webs
we don't have an easy way to preserve stmt order to fulfil
dependencies within them. */
tree op2;
ssa_op_iter i2;
if (gimple_code (def_stmt) == GIMPLE_PHI)
return false;
FOR_EACH_SSA_TREE_OPERAND (op2, def_stmt, i2, SSA_OP_USE)
{
gimple *def_stmt2 = SSA_NAME_DEF_STMT (op2);
if (!gimple_nop_p (def_stmt2)
&& flow_bb_inside_loop_p (loop, gimple_bb (def_stmt2)))
return false;
}
any = true;
}
}
if (!any)
return true;
FOR_EACH_SSA_TREE_OPERAND (op, stmt_info->stmt, i, SSA_OP_USE)
{
gimple *def_stmt = SSA_NAME_DEF_STMT (op);
if (!gimple_nop_p (def_stmt)
&& flow_bb_inside_loop_p (loop, gimple_bb (def_stmt)))
{
gimple_stmt_iterator gsi = gsi_for_stmt (def_stmt);
gsi_remove (&gsi, false);
gsi_insert_on_edge_immediate (loop_preheader_edge (loop), def_stmt);
}
}
return true;
}
/* vectorizable_load.
Check if STMT_INFO reads a non scalar data-ref (array/pointer/structure)
that can be vectorized.
If VEC_STMT is also passed, vectorize STMT_INFO: create a vectorized
stmt to replace it, put it in VEC_STMT, and insert it at GSI.
Return true if STMT_INFO is vectorizable in this way. */
static bool
vectorizable_load (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt, slp_tree slp_node,
slp_instance slp_node_instance,
stmt_vector_for_cost *cost_vec)
{
tree scalar_dest;
tree vec_dest = NULL;
tree data_ref = NULL;
stmt_vec_info prev_stmt_info;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
class loop *loop = NULL;
class loop *containing_loop = gimple_bb (stmt_info->stmt)->loop_father;
bool nested_in_vect_loop = false;
tree elem_type;
tree new_temp;
machine_mode mode;
tree dummy;
enum dr_alignment_support alignment_support_scheme;
tree dataref_ptr = NULL_TREE;
tree dataref_offset = NULL_TREE;
gimple *ptr_incr = NULL;
int ncopies;
int i, j;
unsigned int group_size;
poly_uint64 group_gap_adj;
tree msq = NULL_TREE, lsq;
tree offset = NULL_TREE;
tree byte_offset = NULL_TREE;
tree realignment_token = NULL_TREE;
gphi *phi = NULL;
vec<tree> dr_chain = vNULL;
bool grouped_load = false;
stmt_vec_info first_stmt_info;
stmt_vec_info first_stmt_info_for_drptr = NULL;
bool compute_in_loop = false;
class loop *at_loop;
int vec_num;
bool slp = (slp_node != NULL);
bool slp_perm = false;
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
poly_uint64 vf;
tree aggr_type;
gather_scatter_info gs_info;
vec_info *vinfo = stmt_info->vinfo;
tree ref_type;
enum vect_def_type mask_dt = vect_unknown_def_type;
if (!STMT_VINFO_RELEVANT_P (stmt_info) && !bb_vinfo)
return false;
if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def
&& ! vec_stmt)
return false;
tree mask = NULL_TREE, mask_vectype = NULL_TREE;
if (gassign *assign = dyn_cast <gassign *> (stmt_info->stmt))
{
scalar_dest = gimple_assign_lhs (assign);
if (TREE_CODE (scalar_dest) != SSA_NAME)
return false;
tree_code code = gimple_assign_rhs_code (assign);
if (code != ARRAY_REF
&& code != BIT_FIELD_REF
&& code != INDIRECT_REF
&& code != COMPONENT_REF
&& code != IMAGPART_EXPR
&& code != REALPART_EXPR
&& code != MEM_REF
&& TREE_CODE_CLASS (code) != tcc_declaration)
return false;
}
else
{
gcall *call = dyn_cast <gcall *> (stmt_info->stmt);
if (!call || !gimple_call_internal_p (call))
return false;
internal_fn ifn = gimple_call_internal_fn (call);
if (!internal_load_fn_p (ifn))
return false;
scalar_dest = gimple_call_lhs (call);
if (!scalar_dest)
return false;
int mask_index = internal_fn_mask_index (ifn);
if (mask_index >= 0)
{
mask = gimple_call_arg (call, mask_index);
if (!vect_check_scalar_mask (stmt_info, mask, &mask_dt,
&mask_vectype))
return false;
}
}
if (!STMT_VINFO_DATA_REF (stmt_info))
return false;
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
poly_uint64 nunits = TYPE_VECTOR_SUBPARTS (vectype);
if (loop_vinfo)
{
loop = LOOP_VINFO_LOOP (loop_vinfo);
nested_in_vect_loop = nested_in_vect_loop_p (loop, stmt_info);
vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
}
else
vf = 1;
/* Multiple types in SLP are handled by creating the appropriate number of
vectorized stmts for each SLP node. Hence, NCOPIES is always 1 in
case of SLP. */
if (slp)
ncopies = 1;
else
ncopies = vect_get_num_copies (loop_vinfo, vectype);
gcc_assert (ncopies >= 1);
/* FORNOW. This restriction should be relaxed. */
if (nested_in_vect_loop && ncopies > 1)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"multiple types in nested loop.\n");
return false;
}
/* Invalidate assumptions made by dependence analysis when vectorization
on the unrolled body effectively re-orders stmts. */
if (ncopies > 1
&& STMT_VINFO_MIN_NEG_DIST (stmt_info) != 0
&& maybe_gt (LOOP_VINFO_VECT_FACTOR (loop_vinfo),
STMT_VINFO_MIN_NEG_DIST (stmt_info)))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"cannot perform implicit CSE when unrolling "
"with negative dependence distance\n");
return false;
}
elem_type = TREE_TYPE (vectype);
mode = TYPE_MODE (vectype);
/* FORNOW. In some cases can vectorize even if data-type not supported
(e.g. - data copies). */
if (optab_handler (mov_optab, mode) == CODE_FOR_nothing)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"Aligned load, but unsupported type.\n");
return false;
}
/* Check if the load is a part of an interleaving chain. */
if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
{
grouped_load = true;
/* FORNOW */
gcc_assert (!nested_in_vect_loop);
gcc_assert (!STMT_VINFO_GATHER_SCATTER_P (stmt_info));
first_stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
group_size = DR_GROUP_SIZE (first_stmt_info);
/* Refuse non-SLP vectorization of SLP-only groups. */
if (!slp && STMT_VINFO_SLP_VECT_ONLY (first_stmt_info))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"cannot vectorize load in non-SLP mode.\n");
return false;
}
if (slp && SLP_TREE_LOAD_PERMUTATION (slp_node).exists ())
slp_perm = true;
/* Invalidate assumptions made by dependence analysis when vectorization
on the unrolled body effectively re-orders stmts. */
if (!PURE_SLP_STMT (stmt_info)
&& STMT_VINFO_MIN_NEG_DIST (stmt_info) != 0
&& maybe_gt (LOOP_VINFO_VECT_FACTOR (loop_vinfo),
STMT_VINFO_MIN_NEG_DIST (stmt_info)))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"cannot perform implicit CSE when performing "
"group loads with negative dependence distance\n");
return false;
}
}
else
group_size = 1;
vect_memory_access_type memory_access_type;
if (!get_load_store_type (stmt_info, vectype, slp, mask, VLS_LOAD, ncopies,
&memory_access_type, &gs_info))
return false;
if (mask)
{
if (memory_access_type == VMAT_CONTIGUOUS)
{
machine_mode vec_mode = TYPE_MODE (vectype);
if (!VECTOR_MODE_P (vec_mode)
|| !can_vec_mask_load_store_p (vec_mode,
TYPE_MODE (mask_vectype), true))
return false;
}
else if (memory_access_type != VMAT_LOAD_STORE_LANES
&& memory_access_type != VMAT_GATHER_SCATTER)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"unsupported access type for masked load.\n");
return false;
}
}
if (!vec_stmt) /* transformation not required. */
{
if (!slp)
STMT_VINFO_MEMORY_ACCESS_TYPE (stmt_info) = memory_access_type;
if (loop_vinfo
&& LOOP_VINFO_CAN_FULLY_MASK_P (loop_vinfo))
check_load_store_masking (loop_vinfo, vectype, VLS_LOAD, group_size,
memory_access_type, &gs_info, mask);
STMT_VINFO_TYPE (stmt_info) = load_vec_info_type;
vect_model_load_cost (stmt_info, ncopies, memory_access_type,
slp_node_instance, slp_node, cost_vec);
return true;
}
if (!slp)
gcc_assert (memory_access_type
== STMT_VINFO_MEMORY_ACCESS_TYPE (stmt_info));
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"transform load. ncopies = %d\n", ncopies);
/* Transform. */
dr_vec_info *dr_info = STMT_VINFO_DR_INFO (stmt_info), *first_dr_info = NULL;
ensure_base_align (dr_info);
if (memory_access_type == VMAT_GATHER_SCATTER && gs_info.decl)
{
vect_build_gather_load_calls (stmt_info, gsi, vec_stmt, &gs_info, mask);
return true;
}
if (memory_access_type == VMAT_INVARIANT)
{
gcc_assert (!grouped_load && !mask && !bb_vinfo);
/* If we have versioned for aliasing or the loop doesn't
have any data dependencies that would preclude this,
then we are sure this is a loop invariant load and
thus we can insert it on the preheader edge. */
bool hoist_p = (LOOP_VINFO_NO_DATA_DEPENDENCIES (loop_vinfo)
&& !nested_in_vect_loop
&& hoist_defs_of_uses (stmt_info, loop));
if (hoist_p)
{
gassign *stmt = as_a <gassign *> (stmt_info->stmt);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"hoisting out of the vectorized loop: %G", stmt);
scalar_dest = copy_ssa_name (scalar_dest);
tree rhs = unshare_expr (gimple_assign_rhs1 (stmt));
gsi_insert_on_edge_immediate
(loop_preheader_edge (loop),
gimple_build_assign (scalar_dest, rhs));
}
/* These copies are all equivalent, but currently the representation
requires a separate STMT_VINFO_VEC_STMT for each one. */
prev_stmt_info = NULL;
gimple_stmt_iterator gsi2 = *gsi;
gsi_next (&gsi2);
for (j = 0; j < ncopies; j++)
{
stmt_vec_info new_stmt_info;
if (hoist_p)
{
new_temp = vect_init_vector (stmt_info, scalar_dest,
vectype, NULL);
gimple *new_stmt = SSA_NAME_DEF_STMT (new_temp);
new_stmt_info = vinfo->add_stmt (new_stmt);
}
else
{
new_temp = vect_init_vector (stmt_info, scalar_dest,
vectype, &gsi2);
new_stmt_info = vinfo->lookup_def (new_temp);
}
if (slp)
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
else if (j == 0)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
return true;
}
if (memory_access_type == VMAT_ELEMENTWISE
|| memory_access_type == VMAT_STRIDED_SLP)
{
gimple_stmt_iterator incr_gsi;
bool insert_after;
gimple *incr;
tree offvar;
tree ivstep;
tree running_off;
vec<constructor_elt, va_gc> *v = NULL;
tree stride_base, stride_step, alias_off;
/* Checked by get_load_store_type. */
unsigned int const_nunits = nunits.to_constant ();
unsigned HOST_WIDE_INT cst_offset = 0;
tree dr_offset;
gcc_assert (!LOOP_VINFO_FULLY_MASKED_P (loop_vinfo));
gcc_assert (!nested_in_vect_loop);
if (grouped_load)
{
first_stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
first_dr_info = STMT_VINFO_DR_INFO (first_stmt_info);
}
else
{
first_stmt_info = stmt_info;
first_dr_info = dr_info;
}
if (slp && grouped_load)
{
group_size = DR_GROUP_SIZE (first_stmt_info);
ref_type = get_group_alias_ptr_type (first_stmt_info);
}
else
{
if (grouped_load)
cst_offset
= (tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (vectype)))
* vect_get_place_in_interleaving_chain (stmt_info,
first_stmt_info));
group_size = 1;
ref_type = reference_alias_ptr_type (DR_REF (dr_info->dr));
}
dr_offset = get_dr_vinfo_offset (first_dr_info);
stride_base
= fold_build_pointer_plus
(DR_BASE_ADDRESS (first_dr_info->dr),
size_binop (PLUS_EXPR,
convert_to_ptrofftype (dr_offset),
convert_to_ptrofftype (DR_INIT (first_dr_info->dr))));
stride_step = fold_convert (sizetype, DR_STEP (first_dr_info->dr));
/* For a load with loop-invariant (but other than power-of-2)
stride (i.e. not a grouped access) like so:
for (i = 0; i < n; i += stride)
... = array[i];
we generate a new induction variable and new accesses to
form a new vector (or vectors, depending on ncopies):
for (j = 0; ; j += VF*stride)
tmp1 = array[j];
tmp2 = array[j + stride];
...
vectemp = {tmp1, tmp2, ...}
*/
ivstep = fold_build2 (MULT_EXPR, TREE_TYPE (stride_step), stride_step,
build_int_cst (TREE_TYPE (stride_step), vf));
standard_iv_increment_position (loop, &incr_gsi, &insert_after);
stride_base = cse_and_gimplify_to_preheader (loop_vinfo, stride_base);
ivstep = cse_and_gimplify_to_preheader (loop_vinfo, ivstep);
create_iv (stride_base, ivstep, NULL,
loop, &incr_gsi, insert_after,
&offvar, NULL);
incr = gsi_stmt (incr_gsi);
loop_vinfo->add_stmt (incr);
stride_step = cse_and_gimplify_to_preheader (loop_vinfo, stride_step);
prev_stmt_info = NULL;
running_off = offvar;
alias_off = build_int_cst (ref_type, 0);
int nloads = const_nunits;
int lnel = 1;
tree ltype = TREE_TYPE (vectype);
tree lvectype = vectype;
auto_vec<tree> dr_chain;
if (memory_access_type == VMAT_STRIDED_SLP)
{
if (group_size < const_nunits)
{
/* First check if vec_init optab supports construction from vector
elts directly. Otherwise avoid emitting a constructor of
vector elements by performing the loads using an integer type
of the same size, constructing a vector of those and then
re-interpreting it as the original vector type. This avoids a
huge runtime penalty due to the general inability to perform
store forwarding from smaller stores to a larger load. */
tree ptype;
tree vtype
= vector_vector_composition_type (vectype,
const_nunits / group_size,
&ptype);
if (vtype != NULL_TREE)
{
nloads = const_nunits / group_size;
lnel = group_size;
lvectype = vtype;
ltype = ptype;
}
}
else
{
nloads = 1;
lnel = const_nunits;
ltype = vectype;
}
ltype = build_aligned_type (ltype, TYPE_ALIGN (TREE_TYPE (vectype)));
}
/* Load vector(1) scalar_type if it's 1 element-wise vectype. */
else if (nloads == 1)
ltype = vectype;
if (slp)
{
/* For SLP permutation support we need to load the whole group,
not only the number of vector stmts the permutation result
fits in. */
if (slp_perm)
{
/* We don't yet generate SLP_TREE_LOAD_PERMUTATIONs for
variable VF. */
unsigned int const_vf = vf.to_constant ();
ncopies = CEIL (group_size * const_vf, const_nunits);
dr_chain.create (ncopies);
}
else
ncopies = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
}
unsigned int group_el = 0;
unsigned HOST_WIDE_INT
elsz = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (vectype)));
for (j = 0; j < ncopies; j++)
{
if (nloads > 1)
vec_alloc (v, nloads);
stmt_vec_info new_stmt_info = NULL;
for (i = 0; i < nloads; i++)
{
tree this_off = build_int_cst (TREE_TYPE (alias_off),
group_el * elsz + cst_offset);
tree data_ref = build2 (MEM_REF, ltype, running_off, this_off);
vect_copy_ref_info (data_ref, DR_REF (first_dr_info->dr));
gassign *new_stmt
= gimple_build_assign (make_ssa_name (ltype), data_ref);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (nloads > 1)
CONSTRUCTOR_APPEND_ELT (v, NULL_TREE,
gimple_assign_lhs (new_stmt));
group_el += lnel;
if (! slp
|| group_el == group_size)
{
tree newoff = copy_ssa_name (running_off);
gimple *incr = gimple_build_assign (newoff, POINTER_PLUS_EXPR,
running_off, stride_step);
vect_finish_stmt_generation (stmt_info, incr, gsi);
running_off = newoff;
group_el = 0;
}
}
if (nloads > 1)
{
tree vec_inv = build_constructor (lvectype, v);
new_temp = vect_init_vector (stmt_info, vec_inv, lvectype, gsi);
new_stmt_info = vinfo->lookup_def (new_temp);
if (lvectype != vectype)
{
gassign *new_stmt
= gimple_build_assign (make_ssa_name (vectype),
VIEW_CONVERT_EXPR,
build1 (VIEW_CONVERT_EXPR,
vectype, new_temp));
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
}
if (slp)
{
if (slp_perm)
dr_chain.quick_push (gimple_assign_lhs (new_stmt_info->stmt));
else
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
}
else
{
if (j == 0)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
}
if (slp_perm)
{
unsigned n_perms;
vect_transform_slp_perm_load (slp_node, dr_chain, gsi, vf,
slp_node_instance, false, &n_perms);
}
return true;
}
if (memory_access_type == VMAT_GATHER_SCATTER
|| (!slp && memory_access_type == VMAT_CONTIGUOUS))
grouped_load = false;
if (grouped_load)
{
first_stmt_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
group_size = DR_GROUP_SIZE (first_stmt_info);
/* For SLP vectorization we directly vectorize a subchain
without permutation. */
if (slp && ! SLP_TREE_LOAD_PERMUTATION (slp_node).exists ())
first_stmt_info = SLP_TREE_SCALAR_STMTS (slp_node)[0];
/* For BB vectorization always use the first stmt to base
the data ref pointer on. */
if (bb_vinfo)
first_stmt_info_for_drptr = SLP_TREE_SCALAR_STMTS (slp_node)[0];
/* Check if the chain of loads is already vectorized. */
if (STMT_VINFO_VEC_STMT (first_stmt_info)
/* For SLP we would need to copy over SLP_TREE_VEC_STMTS.
??? But we can only do so if there is exactly one
as we have no way to get at the rest. Leave the CSE
opportunity alone.
??? With the group load eventually participating
in multiple different permutations (having multiple
slp nodes which refer to the same group) the CSE
is even wrong code. See PR56270. */
&& !slp)
{
*vec_stmt = STMT_VINFO_VEC_STMT (stmt_info);
return true;
}
first_dr_info = STMT_VINFO_DR_INFO (first_stmt_info);
group_gap_adj = 0;
/* VEC_NUM is the number of vect stmts to be created for this group. */
if (slp)
{
grouped_load = false;
/* If an SLP permutation is from N elements to N elements,
and if one vector holds a whole number of N, we can load
the inputs to the permutation in the same way as an
unpermuted sequence. In other cases we need to load the
whole group, not only the number of vector stmts the
permutation result fits in. */
if (slp_perm
&& (group_size != SLP_INSTANCE_GROUP_SIZE (slp_node_instance)
|| !multiple_p (nunits, group_size)))
{
/* We don't yet generate such SLP_TREE_LOAD_PERMUTATIONs for
variable VF; see vect_transform_slp_perm_load. */
unsigned int const_vf = vf.to_constant ();
unsigned int const_nunits = nunits.to_constant ();
vec_num = CEIL (group_size * const_vf, const_nunits);
group_gap_adj = vf * group_size - nunits * vec_num;
}
else
{
vec_num = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
group_gap_adj
= group_size - SLP_INSTANCE_GROUP_SIZE (slp_node_instance);
}
}
else
vec_num = group_size;
ref_type = get_group_alias_ptr_type (first_stmt_info);
}
else
{
first_stmt_info = stmt_info;
first_dr_info = dr_info;
group_size = vec_num = 1;
group_gap_adj = 0;
ref_type = reference_alias_ptr_type (DR_REF (first_dr_info->dr));
}
/* Gather-scatter accesses perform only component accesses, alignment
is irrelevant for them. */
if (memory_access_type == VMAT_GATHER_SCATTER)
alignment_support_scheme = dr_unaligned_supported;
else
alignment_support_scheme
= vect_supportable_dr_alignment (first_dr_info, false);
gcc_assert (alignment_support_scheme);
vec_loop_masks *loop_masks
= (loop_vinfo && LOOP_VINFO_FULLY_MASKED_P (loop_vinfo)
? &LOOP_VINFO_MASKS (loop_vinfo)
: NULL);
/* Targets with store-lane instructions must not require explicit
realignment. vect_supportable_dr_alignment always returns either
dr_aligned or dr_unaligned_supported for masked operations. */
gcc_assert ((memory_access_type != VMAT_LOAD_STORE_LANES
&& !mask
&& !loop_masks)
|| alignment_support_scheme == dr_aligned
|| alignment_support_scheme == dr_unaligned_supported);
/* In case the vectorization factor (VF) is bigger than the number
of elements that we can fit in a vectype (nunits), we have to generate
more than one vector stmt - i.e - we need to "unroll" the
vector stmt by a factor VF/nunits. In doing so, we record a pointer
from one copy of the vector stmt to the next, in the field
STMT_VINFO_RELATED_STMT. This is necessary in order to allow following
stages to find the correct vector defs to be used when vectorizing
stmts that use the defs of the current stmt. The example below
illustrates the vectorization process when VF=16 and nunits=4 (i.e., we
need to create 4 vectorized stmts):
before vectorization:
RELATED_STMT VEC_STMT
S1: x = memref - -
S2: z = x + 1 - -
step 1: vectorize stmt S1:
We first create the vector stmt VS1_0, and, as usual, record a
pointer to it in the STMT_VINFO_VEC_STMT of the scalar stmt S1.
Next, we create the vector stmt VS1_1, and record a pointer to
it in the STMT_VINFO_RELATED_STMT of the vector stmt VS1_0.
Similarly, for VS1_2 and VS1_3. This is the resulting chain of
stmts and pointers:
RELATED_STMT VEC_STMT
VS1_0: vx0 = memref0 VS1_1 -
VS1_1: vx1 = memref1 VS1_2 -
VS1_2: vx2 = memref2 VS1_3 -
VS1_3: vx3 = memref3 - -
S1: x = load - VS1_0
S2: z = x + 1 - -
See in documentation in vect_get_vec_def_for_stmt_copy for how the
information we recorded in RELATED_STMT field is used to vectorize
stmt S2. */
/* In case of interleaving (non-unit grouped access):
S1: x2 = &base + 2
S2: x0 = &base
S3: x1 = &base + 1
S4: x3 = &base + 3
Vectorized loads are created in the order of memory accesses
starting from the access of the first stmt of the chain:
VS1: vx0 = &base
VS2: vx1 = &base + vec_size*1
VS3: vx3 = &base + vec_size*2
VS4: vx4 = &base + vec_size*3
Then permutation statements are generated:
VS5: vx5 = VEC_PERM_EXPR < vx0, vx1, { 0, 2, ..., i*2 } >
VS6: vx6 = VEC_PERM_EXPR < vx0, vx1, { 1, 3, ..., i*2+1 } >
...
And they are put in STMT_VINFO_VEC_STMT of the corresponding scalar stmts
(the order of the data-refs in the output of vect_permute_load_chain
corresponds to the order of scalar stmts in the interleaving chain - see
the documentation of vect_permute_load_chain()).
The generation of permutation stmts and recording them in
STMT_VINFO_VEC_STMT is done in vect_transform_grouped_load().
In case of both multiple types and interleaving, the vector loads and
permutation stmts above are created for every copy. The result vector
stmts are put in STMT_VINFO_VEC_STMT for the first copy and in the
corresponding STMT_VINFO_RELATED_STMT for the next copies. */
/* If the data reference is aligned (dr_aligned) or potentially unaligned
on a target that supports unaligned accesses (dr_unaligned_supported)
we generate the following code:
p = initial_addr;
indx = 0;
loop {
p = p + indx * vectype_size;
vec_dest = *(p);
indx = indx + 1;
}
Otherwise, the data reference is potentially unaligned on a target that
does not support unaligned accesses (dr_explicit_realign_optimized) -
then generate the following code, in which the data in each iteration is
obtained by two vector loads, one from the previous iteration, and one
from the current iteration:
p1 = initial_addr;
msq_init = *(floor(p1))
p2 = initial_addr + VS - 1;
realignment_token = call target_builtin;
indx = 0;
loop {
p2 = p2 + indx * vectype_size
lsq = *(floor(p2))
vec_dest = realign_load (msq, lsq, realignment_token)
indx = indx + 1;
msq = lsq;
} */
/* If the misalignment remains the same throughout the execution of the
loop, we can create the init_addr and permutation mask at the loop
preheader. Otherwise, it needs to be created inside the loop.
This can only occur when vectorizing memory accesses in the inner-loop
nested within an outer-loop that is being vectorized. */
if (nested_in_vect_loop
&& !multiple_p (DR_STEP_ALIGNMENT (dr_info->dr),
GET_MODE_SIZE (TYPE_MODE (vectype))))
{
gcc_assert (alignment_support_scheme != dr_explicit_realign_optimized);
compute_in_loop = true;
}
bool diff_first_stmt_info
= first_stmt_info_for_drptr && first_stmt_info != first_stmt_info_for_drptr;
if ((alignment_support_scheme == dr_explicit_realign_optimized
|| alignment_support_scheme == dr_explicit_realign)
&& !compute_in_loop)
{
/* If we have different first_stmt_info, we can't set up realignment
here, since we can't guarantee first_stmt_info DR has been
initialized yet, use first_stmt_info_for_drptr DR by bumping the
distance from first_stmt_info DR instead as below. */
if (!diff_first_stmt_info)
msq = vect_setup_realignment (first_stmt_info, gsi, &realignment_token,
alignment_support_scheme, NULL_TREE,
&at_loop);
if (alignment_support_scheme == dr_explicit_realign_optimized)
{
phi = as_a <gphi *> (SSA_NAME_DEF_STMT (msq));
byte_offset = size_binop (MINUS_EXPR, TYPE_SIZE_UNIT (vectype),
size_one_node);
gcc_assert (!first_stmt_info_for_drptr);
}
}
else
at_loop = loop;
if (memory_access_type == VMAT_CONTIGUOUS_REVERSE)
offset = size_int (-TYPE_VECTOR_SUBPARTS (vectype) + 1);
tree bump;
tree vec_offset = NULL_TREE;
if (STMT_VINFO_GATHER_SCATTER_P (stmt_info))
{
aggr_type = NULL_TREE;
bump = NULL_TREE;
}
else if (memory_access_type == VMAT_GATHER_SCATTER)
{
aggr_type = elem_type;
vect_get_strided_load_store_ops (stmt_info, loop_vinfo, &gs_info,
&bump, &vec_offset);
}
else
{
if (memory_access_type == VMAT_LOAD_STORE_LANES)
aggr_type = build_array_type_nelts (elem_type, vec_num * nunits);
else
aggr_type = vectype;
bump = vect_get_data_ptr_increment (dr_info, aggr_type,
memory_access_type);
}
tree vec_mask = NULL_TREE;
prev_stmt_info = NULL;
poly_uint64 group_elt = 0;
for (j = 0; j < ncopies; j++)
{
stmt_vec_info new_stmt_info = NULL;
/* 1. Create the vector or array pointer update chain. */
if (j == 0)
{
bool simd_lane_access_p
= STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) != 0;
if (simd_lane_access_p
&& TREE_CODE (DR_BASE_ADDRESS (first_dr_info->dr)) == ADDR_EXPR
&& VAR_P (TREE_OPERAND (DR_BASE_ADDRESS (first_dr_info->dr), 0))
&& integer_zerop (get_dr_vinfo_offset (first_dr_info))
&& integer_zerop (DR_INIT (first_dr_info->dr))
&& alias_sets_conflict_p (get_alias_set (aggr_type),
get_alias_set (TREE_TYPE (ref_type)))
&& (alignment_support_scheme == dr_aligned
|| alignment_support_scheme == dr_unaligned_supported))
{
dataref_ptr = unshare_expr (DR_BASE_ADDRESS (first_dr_info->dr));
dataref_offset = build_int_cst (ref_type, 0);
}
else if (diff_first_stmt_info)
{
dataref_ptr
= vect_create_data_ref_ptr (first_stmt_info_for_drptr,
aggr_type, at_loop, offset, &dummy,
gsi, &ptr_incr, simd_lane_access_p,
byte_offset, bump);
/* Adjust the pointer by the difference to first_stmt. */
data_reference_p ptrdr
= STMT_VINFO_DATA_REF (first_stmt_info_for_drptr);
tree diff
= fold_convert (sizetype,
size_binop (MINUS_EXPR,
DR_INIT (first_dr_info->dr),
DR_INIT (ptrdr)));
dataref_ptr = bump_vector_ptr (dataref_ptr, ptr_incr, gsi,
stmt_info, diff);
if (alignment_support_scheme == dr_explicit_realign)
{
msq = vect_setup_realignment (first_stmt_info_for_drptr, gsi,
&realignment_token,
alignment_support_scheme,
dataref_ptr, &at_loop);
gcc_assert (!compute_in_loop);
}
}
else if (STMT_VINFO_GATHER_SCATTER_P (stmt_info))
vect_get_gather_scatter_ops (loop, stmt_info, &gs_info,
&dataref_ptr, &vec_offset);
else
dataref_ptr
= vect_create_data_ref_ptr (first_stmt_info, aggr_type, at_loop,
offset, &dummy, gsi, &ptr_incr,
simd_lane_access_p,
byte_offset, bump);
if (mask)
{
if (slp_node)
{
auto_vec<vec<tree> > vec_defs (1);
vect_get_slp_defs (slp_node, &vec_defs);
vec_mask = vec_defs[0][0];
}
else
vec_mask = vect_get_vec_def_for_operand (mask, stmt_info,
mask_vectype);
}
}
else
{
if (dataref_offset)
dataref_offset = int_const_binop (PLUS_EXPR, dataref_offset,
bump);
else if (STMT_VINFO_GATHER_SCATTER_P (stmt_info))
vec_offset = vect_get_vec_def_for_stmt_copy (vinfo, vec_offset);
else
dataref_ptr = bump_vector_ptr (dataref_ptr, ptr_incr, gsi,
stmt_info, bump);
if (mask)
vec_mask = vect_get_vec_def_for_stmt_copy (vinfo, vec_mask);
}
if (grouped_load || slp_perm)
dr_chain.create (vec_num);
if (memory_access_type == VMAT_LOAD_STORE_LANES)
{
tree vec_array;
vec_array = create_vector_array (vectype, vec_num);
tree final_mask = NULL_TREE;
if (loop_masks)
final_mask = vect_get_loop_mask (gsi, loop_masks, ncopies,
vectype, j);
if (vec_mask)
final_mask = prepare_load_store_mask (mask_vectype, final_mask,
vec_mask, gsi);
gcall *call;
if (final_mask)
{
/* Emit:
VEC_ARRAY = MASK_LOAD_LANES (DATAREF_PTR, ALIAS_PTR,
VEC_MASK). */
unsigned int align = TYPE_ALIGN (TREE_TYPE (vectype));
tree alias_ptr = build_int_cst (ref_type, align);
call = gimple_build_call_internal (IFN_MASK_LOAD_LANES, 3,
dataref_ptr, alias_ptr,
final_mask);
}
else
{
/* Emit:
VEC_ARRAY = LOAD_LANES (MEM_REF[...all elements...]). */
data_ref = create_array_ref (aggr_type, dataref_ptr, ref_type);
call = gimple_build_call_internal (IFN_LOAD_LANES, 1, data_ref);
}
gimple_call_set_lhs (call, vec_array);
gimple_call_set_nothrow (call, true);
new_stmt_info = vect_finish_stmt_generation (stmt_info, call, gsi);
/* Extract each vector into an SSA_NAME. */
for (i = 0; i < vec_num; i++)
{
new_temp = read_vector_array (stmt_info, gsi, scalar_dest,
vec_array, i);
dr_chain.quick_push (new_temp);
}
/* Record the mapping between SSA_NAMEs and statements. */
vect_record_grouped_load_vectors (stmt_info, dr_chain);
/* Record that VEC_ARRAY is now dead. */
vect_clobber_variable (stmt_info, gsi, vec_array);
}
else
{
for (i = 0; i < vec_num; i++)
{
tree final_mask = NULL_TREE;
if (loop_masks
&& memory_access_type != VMAT_INVARIANT)
final_mask = vect_get_loop_mask (gsi, loop_masks,
vec_num * ncopies,
vectype, vec_num * j + i);
if (vec_mask)
final_mask = prepare_load_store_mask (mask_vectype, final_mask,
vec_mask, gsi);
if (i > 0)
dataref_ptr = bump_vector_ptr (dataref_ptr, ptr_incr, gsi,
stmt_info, bump);
/* 2. Create the vector-load in the loop. */
gimple *new_stmt = NULL;
switch (alignment_support_scheme)
{
case dr_aligned:
case dr_unaligned_supported:
{
unsigned int misalign;
unsigned HOST_WIDE_INT align;
if (memory_access_type == VMAT_GATHER_SCATTER)
{
tree zero = build_zero_cst (vectype);
tree scale = size_int (gs_info.scale);
gcall *call;
if (loop_masks)
call = gimple_build_call_internal
(IFN_MASK_GATHER_LOAD, 5, dataref_ptr,
vec_offset, scale, zero, final_mask);
else
call = gimple_build_call_internal
(IFN_GATHER_LOAD, 4, dataref_ptr,
vec_offset, scale, zero);
gimple_call_set_nothrow (call, true);
new_stmt = call;
data_ref = NULL_TREE;
break;
}
align =
known_alignment (DR_TARGET_ALIGNMENT (first_dr_info));
if (alignment_support_scheme == dr_aligned)
{
gcc_assert (aligned_access_p (first_dr_info));
misalign = 0;
}
else if (DR_MISALIGNMENT (first_dr_info) == -1)
{
align = dr_alignment
(vect_dr_behavior (first_dr_info));
misalign = 0;
}
else
misalign = DR_MISALIGNMENT (first_dr_info);
if (dataref_offset == NULL_TREE
&& TREE_CODE (dataref_ptr) == SSA_NAME)
set_ptr_info_alignment (get_ptr_info (dataref_ptr),
align, misalign);
if (final_mask)
{
align = least_bit_hwi (misalign | align);
tree ptr = build_int_cst (ref_type,
align * BITS_PER_UNIT);
gcall *call
= gimple_build_call_internal (IFN_MASK_LOAD, 3,
dataref_ptr, ptr,
final_mask);
gimple_call_set_nothrow (call, true);
new_stmt = call;
data_ref = NULL_TREE;
}
else
{
tree ltype = vectype;
tree new_vtype = NULL_TREE;
/* If there's no peeling for gaps but we have a gap
with slp loads then load the lower half of the
vector only. See get_group_load_store_type for
when we apply this optimization. */
if (slp
&& loop_vinfo
&& !LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo)
&& DR_GROUP_GAP (first_stmt_info) != 0
&& known_eq (nunits,
(group_size
- DR_GROUP_GAP (first_stmt_info)) * 2)
&& known_eq (nunits, group_size))
{
tree half_vtype;
new_vtype
= vector_vector_composition_type (vectype, 2,
&half_vtype);
if (new_vtype != NULL_TREE)
ltype = half_vtype;
}
tree offset
= (dataref_offset ? dataref_offset
: build_int_cst (ref_type, 0));
if (ltype != vectype
&& memory_access_type == VMAT_CONTIGUOUS_REVERSE)
{
unsigned HOST_WIDE_INT gap
= DR_GROUP_GAP (first_stmt_info);
gap *= tree_to_uhwi (TYPE_SIZE_UNIT (elem_type));
tree gapcst = build_int_cst (ref_type, gap);
offset = size_binop (PLUS_EXPR, offset, gapcst);
}
data_ref
= fold_build2 (MEM_REF, ltype, dataref_ptr, offset);
if (alignment_support_scheme == dr_aligned)
;
else if (DR_MISALIGNMENT (first_dr_info) == -1)
TREE_TYPE (data_ref)
= build_aligned_type (TREE_TYPE (data_ref),
align * BITS_PER_UNIT);
else
TREE_TYPE (data_ref)
= build_aligned_type (TREE_TYPE (data_ref),
TYPE_ALIGN (elem_type));
if (ltype != vectype)
{
vect_copy_ref_info (data_ref,
DR_REF (first_dr_info->dr));
tree tem = make_ssa_name (ltype);
new_stmt = gimple_build_assign (tem, data_ref);
vect_finish_stmt_generation (stmt_info, new_stmt,
gsi);
data_ref = NULL;
vec<constructor_elt, va_gc> *v;
vec_alloc (v, 2);
if (memory_access_type == VMAT_CONTIGUOUS_REVERSE)
{
CONSTRUCTOR_APPEND_ELT (v, NULL_TREE,
build_zero_cst (ltype));
CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, tem);
}
else
{
CONSTRUCTOR_APPEND_ELT (v, NULL_TREE, tem);
CONSTRUCTOR_APPEND_ELT (v, NULL_TREE,
build_zero_cst (ltype));
}
gcc_assert (new_vtype != NULL_TREE);
if (new_vtype == vectype)
new_stmt = gimple_build_assign (
vec_dest, build_constructor (vectype, v));
else
{
tree new_vname = make_ssa_name (new_vtype);
new_stmt = gimple_build_assign (
new_vname, build_constructor (new_vtype, v));
vect_finish_stmt_generation (stmt_info,
new_stmt, gsi);
new_stmt = gimple_build_assign (
vec_dest, build1 (VIEW_CONVERT_EXPR, vectype,
new_vname));
}
}
}
break;
}
case dr_explicit_realign:
{
tree ptr, bump;
tree vs = size_int (TYPE_VECTOR_SUBPARTS (vectype));
if (compute_in_loop)
msq = vect_setup_realignment (first_stmt_info, gsi,
&realignment_token,
dr_explicit_realign,
dataref_ptr, NULL);
if (TREE_CODE (dataref_ptr) == SSA_NAME)
ptr = copy_ssa_name (dataref_ptr);
else
ptr = make_ssa_name (TREE_TYPE (dataref_ptr));
// For explicit realign the target alignment should be
// known at compile time.
unsigned HOST_WIDE_INT align =
DR_TARGET_ALIGNMENT (first_dr_info).to_constant ();
new_stmt = gimple_build_assign
(ptr, BIT_AND_EXPR, dataref_ptr,
build_int_cst
(TREE_TYPE (dataref_ptr),
-(HOST_WIDE_INT) align));
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
data_ref
= build2 (MEM_REF, vectype, ptr,
build_int_cst (ref_type, 0));
vect_copy_ref_info (data_ref, DR_REF (first_dr_info->dr));
vec_dest = vect_create_destination_var (scalar_dest,
vectype);
new_stmt = gimple_build_assign (vec_dest, data_ref);
new_temp = make_ssa_name (vec_dest, new_stmt);
gimple_assign_set_lhs (new_stmt, new_temp);
gimple_move_vops (new_stmt, stmt_info->stmt);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
msq = new_temp;
bump = size_binop (MULT_EXPR, vs,
TYPE_SIZE_UNIT (elem_type));
bump = size_binop (MINUS_EXPR, bump, size_one_node);
ptr = bump_vector_ptr (dataref_ptr, NULL, gsi,
stmt_info, bump);
new_stmt = gimple_build_assign
(NULL_TREE, BIT_AND_EXPR, ptr,
build_int_cst
(TREE_TYPE (ptr), -(HOST_WIDE_INT) align));
ptr = copy_ssa_name (ptr, new_stmt);
gimple_assign_set_lhs (new_stmt, ptr);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
data_ref
= build2 (MEM_REF, vectype, ptr,
build_int_cst (ref_type, 0));
break;
}
case dr_explicit_realign_optimized:
{
if (TREE_CODE (dataref_ptr) == SSA_NAME)
new_temp = copy_ssa_name (dataref_ptr);
else
new_temp = make_ssa_name (TREE_TYPE (dataref_ptr));
// We should only be doing this if we know the target
// alignment at compile time.
unsigned HOST_WIDE_INT align =
DR_TARGET_ALIGNMENT (first_dr_info).to_constant ();
new_stmt = gimple_build_assign
(new_temp, BIT_AND_EXPR, dataref_ptr,
build_int_cst (TREE_TYPE (dataref_ptr),
-(HOST_WIDE_INT) align));
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
data_ref
= build2 (MEM_REF, vectype, new_temp,
build_int_cst (ref_type, 0));
break;
}
default:
gcc_unreachable ();
}
vec_dest = vect_create_destination_var (scalar_dest, vectype);
/* DATA_REF is null if we've already built the statement. */
if (data_ref)
{
vect_copy_ref_info (data_ref, DR_REF (first_dr_info->dr));
new_stmt = gimple_build_assign (vec_dest, data_ref);
}
new_temp = make_ssa_name (vec_dest, new_stmt);
gimple_set_lhs (new_stmt, new_temp);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
/* 3. Handle explicit realignment if necessary/supported.
Create in loop:
vec_dest = realign_load (msq, lsq, realignment_token) */
if (alignment_support_scheme == dr_explicit_realign_optimized
|| alignment_support_scheme == dr_explicit_realign)
{
lsq = gimple_assign_lhs (new_stmt);
if (!realignment_token)
realignment_token = dataref_ptr;
vec_dest = vect_create_destination_var (scalar_dest, vectype);
new_stmt = gimple_build_assign (vec_dest, REALIGN_LOAD_EXPR,
msq, lsq, realignment_token);
new_temp = make_ssa_name (vec_dest, new_stmt);
gimple_assign_set_lhs (new_stmt, new_temp);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (alignment_support_scheme == dr_explicit_realign_optimized)
{
gcc_assert (phi);
if (i == vec_num - 1 && j == ncopies - 1)
add_phi_arg (phi, lsq,
loop_latch_edge (containing_loop),
UNKNOWN_LOCATION);
msq = lsq;
}
}
if (memory_access_type == VMAT_CONTIGUOUS_REVERSE)
{
tree perm_mask = perm_mask_for_reverse (vectype);
new_temp = permute_vec_elements (new_temp, new_temp,
perm_mask, stmt_info, gsi);
new_stmt_info = vinfo->lookup_def (new_temp);
}
/* Collect vector loads and later create their permutation in
vect_transform_grouped_load (). */
if (grouped_load || slp_perm)
dr_chain.quick_push (new_temp);
/* Store vector loads in the corresponding SLP_NODE. */
if (slp && !slp_perm)
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
/* With SLP permutation we load the gaps as well, without
we need to skip the gaps after we manage to fully load
all elements. group_gap_adj is DR_GROUP_SIZE here. */
group_elt += nunits;
if (maybe_ne (group_gap_adj, 0U)
&& !slp_perm
&& known_eq (group_elt, group_size - group_gap_adj))
{
poly_wide_int bump_val
= (wi::to_wide (TYPE_SIZE_UNIT (elem_type))
* group_gap_adj);
tree bump = wide_int_to_tree (sizetype, bump_val);
dataref_ptr = bump_vector_ptr (dataref_ptr, ptr_incr, gsi,
stmt_info, bump);
group_elt = 0;
}
}
/* Bump the vector pointer to account for a gap or for excess
elements loaded for a permuted SLP load. */
if (maybe_ne (group_gap_adj, 0U) && slp_perm)
{
poly_wide_int bump_val
= (wi::to_wide (TYPE_SIZE_UNIT (elem_type))
* group_gap_adj);
tree bump = wide_int_to_tree (sizetype, bump_val);
dataref_ptr = bump_vector_ptr (dataref_ptr, ptr_incr, gsi,
stmt_info, bump);
}
}
if (slp && !slp_perm)
continue;
if (slp_perm)
{
unsigned n_perms;
if (!vect_transform_slp_perm_load (slp_node, dr_chain, gsi, vf,
slp_node_instance, false,
&n_perms))
{
dr_chain.release ();
return false;
}
}
else
{
if (grouped_load)
{
if (memory_access_type != VMAT_LOAD_STORE_LANES)
vect_transform_grouped_load (stmt_info, dr_chain,
group_size, gsi);
*vec_stmt = STMT_VINFO_VEC_STMT (stmt_info);
}
else
{
if (j == 0)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
}
dr_chain.release ();
}
return true;
}
/* Function vect_is_simple_cond.
Input:
LOOP - the loop that is being vectorized.
COND - Condition that is checked for simple use.
Output:
*COMP_VECTYPE - the vector type for the comparison.
*DTS - The def types for the arguments of the comparison
Returns whether a COND can be vectorized. Checks whether
condition operands are supportable using vec_is_simple_use. */
static bool
vect_is_simple_cond (tree cond, vec_info *vinfo, slp_tree slp_node,
tree *comp_vectype, enum vect_def_type *dts,
tree vectype)
{
tree lhs, rhs;
tree vectype1 = NULL_TREE, vectype2 = NULL_TREE;
/* Mask case. */
if (TREE_CODE (cond) == SSA_NAME
&& VECT_SCALAR_BOOLEAN_TYPE_P (TREE_TYPE (cond)))
{
if (!vect_is_simple_use (cond, vinfo, &dts[0], comp_vectype)
|| !*comp_vectype
|| !VECTOR_BOOLEAN_TYPE_P (*comp_vectype))
return false;
return true;
}
if (!COMPARISON_CLASS_P (cond))
return false;
lhs = TREE_OPERAND (cond, 0);
rhs = TREE_OPERAND (cond, 1);
if (TREE_CODE (lhs) == SSA_NAME)
{
if (!vect_is_simple_use (lhs, vinfo, &dts[0], &vectype1))
return false;
}
else if (TREE_CODE (lhs) == INTEGER_CST || TREE_CODE (lhs) == REAL_CST
|| TREE_CODE (lhs) == FIXED_CST)
dts[0] = vect_constant_def;
else
return false;
if (TREE_CODE (rhs) == SSA_NAME)
{
if (!vect_is_simple_use (rhs, vinfo, &dts[1], &vectype2))
return false;
}
else if (TREE_CODE (rhs) == INTEGER_CST || TREE_CODE (rhs) == REAL_CST
|| TREE_CODE (rhs) == FIXED_CST)
dts[1] = vect_constant_def;
else
return false;
if (vectype1 && vectype2
&& maybe_ne (TYPE_VECTOR_SUBPARTS (vectype1),
TYPE_VECTOR_SUBPARTS (vectype2)))
return false;
*comp_vectype = vectype1 ? vectype1 : vectype2;
/* Invariant comparison. */
if (! *comp_vectype)
{
tree scalar_type = TREE_TYPE (lhs);
if (VECT_SCALAR_BOOLEAN_TYPE_P (scalar_type))
*comp_vectype = truth_type_for (vectype);
else
{
/* If we can widen the comparison to match vectype do so. */
if (INTEGRAL_TYPE_P (scalar_type)
&& !slp_node
&& tree_int_cst_lt (TYPE_SIZE (scalar_type),
TYPE_SIZE (TREE_TYPE (vectype))))
scalar_type = build_nonstandard_integer_type
(tree_to_uhwi (TYPE_SIZE (TREE_TYPE (vectype))),
TYPE_UNSIGNED (scalar_type));
*comp_vectype = get_vectype_for_scalar_type (vinfo, scalar_type,
slp_node);
}
}
return true;
}
/* vectorizable_condition.
Check if STMT_INFO is conditional modify expression that can be vectorized.
If VEC_STMT is also passed, vectorize STMT_INFO: create a vectorized
stmt using VEC_COND_EXPR to replace it, put it in VEC_STMT, and insert it
at GSI.
When STMT_INFO is vectorized as a nested cycle, for_reduction is true.
Return true if STMT_INFO is vectorizable in this way. */
static bool
vectorizable_condition (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt,
slp_tree slp_node, stmt_vector_for_cost *cost_vec)
{
vec_info *vinfo = stmt_info->vinfo;
tree scalar_dest = NULL_TREE;
tree vec_dest = NULL_TREE;
tree cond_expr, cond_expr0 = NULL_TREE, cond_expr1 = NULL_TREE;
tree then_clause, else_clause;
tree comp_vectype = NULL_TREE;
tree vec_cond_lhs = NULL_TREE, vec_cond_rhs = NULL_TREE;
tree vec_then_clause = NULL_TREE, vec_else_clause = NULL_TREE;
tree vec_compare;
tree new_temp;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
enum vect_def_type dts[4]
= {vect_unknown_def_type, vect_unknown_def_type,
vect_unknown_def_type, vect_unknown_def_type};
int ndts = 4;
int ncopies;
int vec_num;
enum tree_code code, cond_code, bitop1 = NOP_EXPR, bitop2 = NOP_EXPR;
stmt_vec_info prev_stmt_info = NULL;
int i, j;
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
vec<tree> vec_oprnds0 = vNULL;
vec<tree> vec_oprnds1 = vNULL;
vec<tree> vec_oprnds2 = vNULL;
vec<tree> vec_oprnds3 = vNULL;
tree vec_cmp_type;
bool masked = false;
if (!STMT_VINFO_RELEVANT_P (stmt_info) && !bb_vinfo)
return false;
/* Is vectorizable conditional operation? */
gassign *stmt = dyn_cast <gassign *> (stmt_info->stmt);
if (!stmt)
return false;
code = gimple_assign_rhs_code (stmt);
if (code != COND_EXPR)
return false;
stmt_vec_info reduc_info = NULL;
int reduc_index = -1;
vect_reduction_type reduction_type = TREE_CODE_REDUCTION;
bool for_reduction
= STMT_VINFO_REDUC_DEF (vect_orig_stmt (stmt_info)) != NULL;
if (for_reduction)
{
if (STMT_SLP_TYPE (stmt_info))
return false;
reduc_info = info_for_reduction (stmt_info);
reduction_type = STMT_VINFO_REDUC_TYPE (reduc_info);
reduc_index = STMT_VINFO_REDUC_IDX (stmt_info);
gcc_assert (reduction_type != EXTRACT_LAST_REDUCTION
|| reduc_index != -1);
}
else
{
if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def)
return false;
/* FORNOW: only supported as part of a reduction. */
if (STMT_VINFO_LIVE_P (stmt_info))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"value used after loop.\n");
return false;
}
}
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
tree vectype1 = NULL_TREE, vectype2 = NULL_TREE;
if (slp_node)
{
ncopies = 1;
vec_num = SLP_TREE_NUMBER_OF_VEC_STMTS (slp_node);
}
else
{
ncopies = vect_get_num_copies (loop_vinfo, vectype);
vec_num = 1;
}
gcc_assert (ncopies >= 1);
if (for_reduction && ncopies > 1)
return false; /* FORNOW */
cond_expr = gimple_assign_rhs1 (stmt);
then_clause = gimple_assign_rhs2 (stmt);
else_clause = gimple_assign_rhs3 (stmt);
if (!vect_is_simple_cond (cond_expr, stmt_info->vinfo, slp_node,
&comp_vectype, &dts[0], vectype)
|| !comp_vectype)
return false;
if (!vect_is_simple_use (then_clause, stmt_info->vinfo, &dts[2], &vectype1))
return false;
if (!vect_is_simple_use (else_clause, stmt_info->vinfo, &dts[3], &vectype2))
return false;
if (vectype1 && !useless_type_conversion_p (vectype, vectype1))
return false;
if (vectype2 && !useless_type_conversion_p (vectype, vectype2))
return false;
masked = !COMPARISON_CLASS_P (cond_expr);
vec_cmp_type = truth_type_for (comp_vectype);
if (vec_cmp_type == NULL_TREE)
return false;
cond_code = TREE_CODE (cond_expr);
if (!masked)
{
cond_expr0 = TREE_OPERAND (cond_expr, 0);
cond_expr1 = TREE_OPERAND (cond_expr, 1);
}
/* For conditional reductions, the "then" value needs to be the candidate
value calculated by this iteration while the "else" value needs to be
the result carried over from previous iterations. If the COND_EXPR
is the other way around, we need to swap it. */
bool must_invert_cmp_result = false;
if (reduction_type == EXTRACT_LAST_REDUCTION && reduc_index == 1)
{
if (masked)
must_invert_cmp_result = true;
else
{
bool honor_nans = HONOR_NANS (TREE_TYPE (cond_expr0));
tree_code new_code = invert_tree_comparison (cond_code, honor_nans);
if (new_code == ERROR_MARK)
must_invert_cmp_result = true;
else
{
cond_code = new_code;
/* Make sure we don't accidentally use the old condition. */
cond_expr = NULL_TREE;
}
}
std::swap (then_clause, else_clause);
}
if (!masked && VECTOR_BOOLEAN_TYPE_P (comp_vectype))
{
/* Boolean values may have another representation in vectors
and therefore we prefer bit operations over comparison for
them (which also works for scalar masks). We store opcodes
to use in bitop1 and bitop2. Statement is vectorized as
BITOP2 (rhs1 BITOP1 rhs2) or rhs1 BITOP2 (BITOP1 rhs2)
depending on bitop1 and bitop2 arity. */
switch (cond_code)
{
case GT_EXPR:
bitop1 = BIT_NOT_EXPR;
bitop2 = BIT_AND_EXPR;
break;
case GE_EXPR:
bitop1 = BIT_NOT_EXPR;
bitop2 = BIT_IOR_EXPR;
break;
case LT_EXPR:
bitop1 = BIT_NOT_EXPR;
bitop2 = BIT_AND_EXPR;
std::swap (cond_expr0, cond_expr1);
break;
case LE_EXPR:
bitop1 = BIT_NOT_EXPR;
bitop2 = BIT_IOR_EXPR;
std::swap (cond_expr0, cond_expr1);
break;
case NE_EXPR:
bitop1 = BIT_XOR_EXPR;
break;
case EQ_EXPR:
bitop1 = BIT_XOR_EXPR;
bitop2 = BIT_NOT_EXPR;
break;
default:
return false;
}
cond_code = SSA_NAME;
}
if (TREE_CODE_CLASS (cond_code) == tcc_comparison
&& reduction_type == EXTRACT_LAST_REDUCTION
&& !expand_vec_cmp_expr_p (comp_vectype, vec_cmp_type, cond_code))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"reduction comparison operation not supported.\n");
return false;
}
if (!vec_stmt)
{
if (bitop1 != NOP_EXPR)
{
machine_mode mode = TYPE_MODE (comp_vectype);
optab optab;
optab = optab_for_tree_code (bitop1, comp_vectype, optab_default);
if (!optab || optab_handler (optab, mode) == CODE_FOR_nothing)
return false;
if (bitop2 != NOP_EXPR)
{
optab = optab_for_tree_code (bitop2, comp_vectype,
optab_default);
if (!optab || optab_handler (optab, mode) == CODE_FOR_nothing)
return false;
}
}
if (loop_vinfo
&& LOOP_VINFO_CAN_FULLY_MASK_P (loop_vinfo)
&& reduction_type == EXTRACT_LAST_REDUCTION)
vect_record_loop_mask (loop_vinfo, &LOOP_VINFO_MASKS (loop_vinfo),
ncopies * vec_num, vectype, NULL);
vect_cost_for_stmt kind = vector_stmt;
if (reduction_type == EXTRACT_LAST_REDUCTION)
/* Count one reduction-like operation per vector. */
kind = vec_to_scalar;
else if (!expand_vec_cond_expr_p (vectype, comp_vectype, cond_code))
return false;
STMT_VINFO_TYPE (stmt_info) = condition_vec_info_type;
vect_model_simple_cost (stmt_info, ncopies, dts, ndts, slp_node,
cost_vec, kind);
return true;
}
/* Transform. */
if (!slp_node)
{
vec_oprnds0.create (1);
vec_oprnds1.create (1);
vec_oprnds2.create (1);
vec_oprnds3.create (1);
}
/* Handle def. */
scalar_dest = gimple_assign_lhs (stmt);
if (reduction_type != EXTRACT_LAST_REDUCTION)
vec_dest = vect_create_destination_var (scalar_dest, vectype);
/* Handle cond expr. */
for (j = 0; j < ncopies; j++)
{
bool swap_cond_operands = false;
/* See whether another part of the vectorized code applies a loop
mask to the condition, or to its inverse. */
vec_loop_masks *masks = NULL;
if (loop_vinfo && LOOP_VINFO_FULLY_MASKED_P (loop_vinfo))
{
if (reduction_type == EXTRACT_LAST_REDUCTION)
masks = &LOOP_VINFO_MASKS (loop_vinfo);
else
{
scalar_cond_masked_key cond (cond_expr, ncopies);
if (loop_vinfo->scalar_cond_masked_set.contains (cond))
masks = &LOOP_VINFO_MASKS (loop_vinfo);
else
{
bool honor_nans = HONOR_NANS (TREE_TYPE (cond.op0));
cond.code = invert_tree_comparison (cond.code, honor_nans);
if (loop_vinfo->scalar_cond_masked_set.contains (cond))
{
masks = &LOOP_VINFO_MASKS (loop_vinfo);
cond_code = cond.code;
swap_cond_operands = true;
}
}
}
}
stmt_vec_info new_stmt_info = NULL;
if (j == 0)
{
if (slp_node)
{
auto_vec<vec<tree>, 4> vec_defs;
vect_get_slp_defs (slp_node, &vec_defs);
vec_oprnds3 = vec_defs.pop ();
vec_oprnds2 = vec_defs.pop ();
if (!masked)
vec_oprnds1 = vec_defs.pop ();
vec_oprnds0 = vec_defs.pop ();
}
else
{
if (masked)
{
vec_cond_lhs
= vect_get_vec_def_for_operand (cond_expr, stmt_info,
comp_vectype);
}
else
{
vec_cond_lhs
= vect_get_vec_def_for_operand (cond_expr0,
stmt_info, comp_vectype);
vec_cond_rhs
= vect_get_vec_def_for_operand (cond_expr1,
stmt_info, comp_vectype);
}
vec_then_clause = vect_get_vec_def_for_operand (then_clause,
stmt_info);
if (reduction_type != EXTRACT_LAST_REDUCTION)
vec_else_clause = vect_get_vec_def_for_operand (else_clause,
stmt_info);
}
}
else
{
vec_cond_lhs
= vect_get_vec_def_for_stmt_copy (vinfo, vec_oprnds0.pop ());
if (!masked)
vec_cond_rhs
= vect_get_vec_def_for_stmt_copy (vinfo, vec_oprnds1.pop ());
vec_then_clause = vect_get_vec_def_for_stmt_copy (vinfo,
vec_oprnds2.pop ());
vec_else_clause = vect_get_vec_def_for_stmt_copy (vinfo,
vec_oprnds3.pop ());
}
if (!slp_node)
{
vec_oprnds0.quick_push (vec_cond_lhs);
if (!masked)
vec_oprnds1.quick_push (vec_cond_rhs);
vec_oprnds2.quick_push (vec_then_clause);
vec_oprnds3.quick_push (vec_else_clause);
}
/* Arguments are ready. Create the new vector stmt. */
FOR_EACH_VEC_ELT (vec_oprnds0, i, vec_cond_lhs)
{
vec_then_clause = vec_oprnds2[i];
vec_else_clause = vec_oprnds3[i];
if (swap_cond_operands)
std::swap (vec_then_clause, vec_else_clause);
if (masked)
vec_compare = vec_cond_lhs;
else
{
vec_cond_rhs = vec_oprnds1[i];
if (bitop1 == NOP_EXPR)
vec_compare = build2 (cond_code, vec_cmp_type,
vec_cond_lhs, vec_cond_rhs);
else
{
new_temp = make_ssa_name (vec_cmp_type);
gassign *new_stmt;
if (bitop1 == BIT_NOT_EXPR)
new_stmt = gimple_build_assign (new_temp, bitop1,
vec_cond_rhs);
else
new_stmt
= gimple_build_assign (new_temp, bitop1, vec_cond_lhs,
vec_cond_rhs);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (bitop2 == NOP_EXPR)
vec_compare = new_temp;
else if (bitop2 == BIT_NOT_EXPR)
{
/* Instead of doing ~x ? y : z do x ? z : y. */
vec_compare = new_temp;
std::swap (vec_then_clause, vec_else_clause);
}
else
{
vec_compare = make_ssa_name (vec_cmp_type);
new_stmt
= gimple_build_assign (vec_compare, bitop2,
vec_cond_lhs, new_temp);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
}
}
/* If we decided to apply a loop mask to the result of the vector
comparison, AND the comparison with the mask now. Later passes
should then be able to reuse the AND results between mulitple
vector statements.
For example:
for (int i = 0; i < 100; ++i)
x[i] = y[i] ? z[i] : 10;
results in following optimized GIMPLE:
mask__35.8_43 = vect__4.7_41 != { 0, ... };
vec_mask_and_46 = loop_mask_40 & mask__35.8_43;
_19 = &MEM[base: z_12(D), index: ivtmp_56, step: 4, offset: 0B];
vect_iftmp.11_47 = .MASK_LOAD (_19, 4B, vec_mask_and_46);
vect_iftmp.12_52 = VEC_COND_EXPR <vec_mask_and_46,
vect_iftmp.11_47, { 10, ... }>;
instead of using a masked and unmasked forms of
vec != { 0, ... } (masked in the MASK_LOAD,
unmasked in the VEC_COND_EXPR). */
/* Force vec_compare to be an SSA_NAME rather than a comparison,
in cases where that's necessary. */
if (masks || reduction_type == EXTRACT_LAST_REDUCTION)
{
if (!is_gimple_val (vec_compare))
{
tree vec_compare_name = make_ssa_name (vec_cmp_type);
gassign *new_stmt = gimple_build_assign (vec_compare_name,
vec_compare);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
vec_compare = vec_compare_name;
}
if (must_invert_cmp_result)
{
tree vec_compare_name = make_ssa_name (vec_cmp_type);
gassign *new_stmt = gimple_build_assign (vec_compare_name,
BIT_NOT_EXPR,
vec_compare);
vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
vec_compare = vec_compare_name;
}
if (masks)
{
unsigned vec_num = vec_oprnds0.length ();
tree loop_mask
= vect_get_loop_mask (gsi, masks, vec_num * ncopies,
vectype, vec_num * j + i);
tree tmp2 = make_ssa_name (vec_cmp_type);
gassign *g
= gimple_build_assign (tmp2, BIT_AND_EXPR, vec_compare,
loop_mask);
vect_finish_stmt_generation (stmt_info, g, gsi);
vec_compare = tmp2;
}
}
if (reduction_type == EXTRACT_LAST_REDUCTION)
{
gimple *old_stmt = vect_orig_stmt (stmt_info)->stmt;
tree lhs = gimple_get_lhs (old_stmt);
gcall *new_stmt = gimple_build_call_internal
(IFN_FOLD_EXTRACT_LAST, 3, else_clause, vec_compare,
vec_then_clause);
gimple_call_set_lhs (new_stmt, lhs);
SSA_NAME_DEF_STMT (lhs) = new_stmt;
if (old_stmt == gsi_stmt (*gsi))
new_stmt_info = vect_finish_replace_stmt (stmt_info, new_stmt);
else
{
/* In this case we're moving the definition to later in the
block. That doesn't matter because the only uses of the
lhs are in phi statements. */
gimple_stmt_iterator old_gsi = gsi_for_stmt (old_stmt);
gsi_remove (&old_gsi, true);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
}
else
{
new_temp = make_ssa_name (vec_dest);
gassign *new_stmt
= gimple_build_assign (new_temp, VEC_COND_EXPR, vec_compare,
vec_then_clause, vec_else_clause);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
if (slp_node)
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
}
if (slp_node)
continue;
if (j == 0)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
vec_oprnds0.release ();
vec_oprnds1.release ();
vec_oprnds2.release ();
vec_oprnds3.release ();
return true;
}
/* vectorizable_comparison.
Check if STMT_INFO is comparison expression that can be vectorized.
If VEC_STMT is also passed, vectorize STMT_INFO: create a vectorized
comparison, put it in VEC_STMT, and insert it at GSI.
Return true if STMT_INFO is vectorizable in this way. */
static bool
vectorizable_comparison (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
stmt_vec_info *vec_stmt,
slp_tree slp_node, stmt_vector_for_cost *cost_vec)
{
vec_info *vinfo = stmt_info->vinfo;
tree lhs, rhs1, rhs2;
tree vectype1 = NULL_TREE, vectype2 = NULL_TREE;
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
tree vec_rhs1 = NULL_TREE, vec_rhs2 = NULL_TREE;
tree new_temp;
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
enum vect_def_type dts[2] = {vect_unknown_def_type, vect_unknown_def_type};
int ndts = 2;
poly_uint64 nunits;
int ncopies;
enum tree_code code, bitop1 = NOP_EXPR, bitop2 = NOP_EXPR;
stmt_vec_info prev_stmt_info = NULL;
int i, j;
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
vec<tree> vec_oprnds0 = vNULL;
vec<tree> vec_oprnds1 = vNULL;
tree mask_type;
tree mask;
if (!STMT_VINFO_RELEVANT_P (stmt_info) && !bb_vinfo)
return false;
if (!vectype || !VECTOR_BOOLEAN_TYPE_P (vectype))
return false;
mask_type = vectype;
nunits = TYPE_VECTOR_SUBPARTS (vectype);
if (slp_node)
ncopies = 1;
else
ncopies = vect_get_num_copies (loop_vinfo, vectype);
gcc_assert (ncopies >= 1);
if (STMT_VINFO_DEF_TYPE (stmt_info) != vect_internal_def)
return false;
if (STMT_VINFO_LIVE_P (stmt_info))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"value used after loop.\n");
return false;
}
gassign *stmt = dyn_cast <gassign *> (stmt_info->stmt);
if (!stmt)
return false;
code = gimple_assign_rhs_code (stmt);
if (TREE_CODE_CLASS (code) != tcc_comparison)
return false;
rhs1 = gimple_assign_rhs1 (stmt);
rhs2 = gimple_assign_rhs2 (stmt);
if (!vect_is_simple_use (rhs1, stmt_info->vinfo, &dts[0], &vectype1))
return false;
if (!vect_is_simple_use (rhs2, stmt_info->vinfo, &dts[1], &vectype2))
return false;
if (vectype1 && vectype2
&& maybe_ne (TYPE_VECTOR_SUBPARTS (vectype1),
TYPE_VECTOR_SUBPARTS (vectype2)))
return false;
vectype = vectype1 ? vectype1 : vectype2;
/* Invariant comparison. */
if (!vectype)
{
if (VECT_SCALAR_BOOLEAN_TYPE_P (TREE_TYPE (rhs1)))
vectype = mask_type;
else
vectype = get_vectype_for_scalar_type (vinfo, TREE_TYPE (rhs1),
slp_node);
if (!vectype || maybe_ne (TYPE_VECTOR_SUBPARTS (vectype), nunits))
return false;
}
else if (maybe_ne (nunits, TYPE_VECTOR_SUBPARTS (vectype)))
return false;
/* Can't compare mask and non-mask types. */
if (vectype1 && vectype2
&& (VECTOR_BOOLEAN_TYPE_P (vectype1) ^ VECTOR_BOOLEAN_TYPE_P (vectype2)))
return false;
/* Boolean values may have another representation in vectors
and therefore we prefer bit operations over comparison for
them (which also works for scalar masks). We store opcodes
to use in bitop1 and bitop2. Statement is vectorized as
BITOP2 (rhs1 BITOP1 rhs2) or
rhs1 BITOP2 (BITOP1 rhs2)
depending on bitop1 and bitop2 arity. */
bool swap_p = false;
if (VECTOR_BOOLEAN_TYPE_P (vectype))
{
if (code == GT_EXPR)
{
bitop1 = BIT_NOT_EXPR;
bitop2 = BIT_AND_EXPR;
}
else if (code == GE_EXPR)
{
bitop1 = BIT_NOT_EXPR;
bitop2 = BIT_IOR_EXPR;
}
else if (code == LT_EXPR)
{
bitop1 = BIT_NOT_EXPR;
bitop2 = BIT_AND_EXPR;
swap_p = true;
}
else if (code == LE_EXPR)
{
bitop1 = BIT_NOT_EXPR;
bitop2 = BIT_IOR_EXPR;
swap_p = true;
}
else
{
bitop1 = BIT_XOR_EXPR;
if (code == EQ_EXPR)
bitop2 = BIT_NOT_EXPR;
}
}
if (!vec_stmt)
{
if (bitop1 == NOP_EXPR)
{
if (!expand_vec_cmp_expr_p (vectype, mask_type, code))
return false;
}
else
{
machine_mode mode = TYPE_MODE (vectype);
optab optab;
optab = optab_for_tree_code (bitop1, vectype, optab_default);
if (!optab || optab_handler (optab, mode) == CODE_FOR_nothing)
return false;
if (bitop2 != NOP_EXPR)
{
optab = optab_for_tree_code (bitop2, vectype, optab_default);
if (!optab || optab_handler (optab, mode) == CODE_FOR_nothing)
return false;
}
}
STMT_VINFO_TYPE (stmt_info) = comparison_vec_info_type;
vect_model_simple_cost (stmt_info, ncopies * (1 + (bitop2 != NOP_EXPR)),
dts, ndts, slp_node, cost_vec);
return true;
}
/* Transform. */
if (!slp_node)
{
vec_oprnds0.create (1);
vec_oprnds1.create (1);
}
/* Handle def. */
lhs = gimple_assign_lhs (stmt);
mask = vect_create_destination_var (lhs, mask_type);
/* Handle cmp expr. */
for (j = 0; j < ncopies; j++)
{
stmt_vec_info new_stmt_info = NULL;
if (j == 0)
{
if (slp_node)
{
auto_vec<vec<tree>, 2> vec_defs;
vect_get_slp_defs (slp_node, &vec_defs);
vec_oprnds1 = vec_defs.pop ();
vec_oprnds0 = vec_defs.pop ();
if (swap_p)
std::swap (vec_oprnds0, vec_oprnds1);
}
else
{
vec_rhs1 = vect_get_vec_def_for_operand (rhs1, stmt_info,
vectype);
vec_rhs2 = vect_get_vec_def_for_operand (rhs2, stmt_info,
vectype);
}
}
else
{
vec_rhs1 = vect_get_vec_def_for_stmt_copy (vinfo,
vec_oprnds0.pop ());
vec_rhs2 = vect_get_vec_def_for_stmt_copy (vinfo,
vec_oprnds1.pop ());
}
if (!slp_node)
{
if (swap_p && j == 0)
std::swap (vec_rhs1, vec_rhs2);
vec_oprnds0.quick_push (vec_rhs1);
vec_oprnds1.quick_push (vec_rhs2);
}
/* Arguments are ready. Create the new vector stmt. */
FOR_EACH_VEC_ELT (vec_oprnds0, i, vec_rhs1)
{
vec_rhs2 = vec_oprnds1[i];
new_temp = make_ssa_name (mask);
if (bitop1 == NOP_EXPR)
{
gassign *new_stmt = gimple_build_assign (new_temp, code,
vec_rhs1, vec_rhs2);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
else
{
gassign *new_stmt;
if (bitop1 == BIT_NOT_EXPR)
new_stmt = gimple_build_assign (new_temp, bitop1, vec_rhs2);
else
new_stmt = gimple_build_assign (new_temp, bitop1, vec_rhs1,
vec_rhs2);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
if (bitop2 != NOP_EXPR)
{
tree res = make_ssa_name (mask);
if (bitop2 == BIT_NOT_EXPR)
new_stmt = gimple_build_assign (res, bitop2, new_temp);
else
new_stmt = gimple_build_assign (res, bitop2, vec_rhs1,
new_temp);
new_stmt_info
= vect_finish_stmt_generation (stmt_info, new_stmt, gsi);
}
}
if (slp_node)
SLP_TREE_VEC_STMTS (slp_node).quick_push (new_stmt_info);
}
if (slp_node)
continue;
if (j == 0)
STMT_VINFO_VEC_STMT (stmt_info) = *vec_stmt = new_stmt_info;
else
STMT_VINFO_RELATED_STMT (prev_stmt_info) = new_stmt_info;
prev_stmt_info = new_stmt_info;
}
vec_oprnds0.release ();
vec_oprnds1.release ();
return true;
}
/* If SLP_NODE is nonnull, return true if vectorizable_live_operation
can handle all live statements in the node. Otherwise return true
if STMT_INFO is not live or if vectorizable_live_operation can handle it.
GSI and VEC_STMT_P are as for vectorizable_live_operation. */
static bool
can_vectorize_live_stmts (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
slp_tree slp_node, slp_instance slp_node_instance,
bool vec_stmt_p,
stmt_vector_for_cost *cost_vec)
{
if (slp_node)
{
stmt_vec_info slp_stmt_info;
unsigned int i;
FOR_EACH_VEC_ELT (SLP_TREE_SCALAR_STMTS (slp_node), i, slp_stmt_info)
{
if (STMT_VINFO_LIVE_P (slp_stmt_info)
&& !vectorizable_live_operation (slp_stmt_info, gsi, slp_node,
slp_node_instance, i,
vec_stmt_p, cost_vec))
return false;
}
}
else if (STMT_VINFO_LIVE_P (stmt_info)
&& !vectorizable_live_operation (stmt_info, gsi, slp_node,
slp_node_instance, -1,
vec_stmt_p, cost_vec))
return false;
return true;
}
/* Make sure the statement is vectorizable. */
opt_result
vect_analyze_stmt (stmt_vec_info stmt_info, bool *need_to_vectorize,
slp_tree node, slp_instance node_instance,
stmt_vector_for_cost *cost_vec)
{
vec_info *vinfo = stmt_info->vinfo;
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
enum vect_relevant relevance = STMT_VINFO_RELEVANT (stmt_info);
bool ok;
gimple_seq pattern_def_seq;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location, "==> examining statement: %G",
stmt_info->stmt);
if (gimple_has_volatile_ops (stmt_info->stmt))
return opt_result::failure_at (stmt_info->stmt,
"not vectorized:"
" stmt has volatile operands: %G\n",
stmt_info->stmt);
if (STMT_VINFO_IN_PATTERN_P (stmt_info)
&& node == NULL
&& (pattern_def_seq = STMT_VINFO_PATTERN_DEF_SEQ (stmt_info)))
{
gimple_stmt_iterator si;
for (si = gsi_start (pattern_def_seq); !gsi_end_p (si); gsi_next (&si))
{
stmt_vec_info pattern_def_stmt_info
= vinfo->lookup_stmt (gsi_stmt (si));
if (STMT_VINFO_RELEVANT_P (pattern_def_stmt_info)
|| STMT_VINFO_LIVE_P (pattern_def_stmt_info))
{
/* Analyze def stmt of STMT if it's a pattern stmt. */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"==> examining pattern def statement: %G",
pattern_def_stmt_info->stmt);
opt_result res
= vect_analyze_stmt (pattern_def_stmt_info,
need_to_vectorize, node, node_instance,
cost_vec);
if (!res)
return res;
}
}
}
/* Skip stmts that do not need to be vectorized. In loops this is expected
to include:
- the COND_EXPR which is the loop exit condition
- any LABEL_EXPRs in the loop
- computations that are used only for array indexing or loop control.
In basic blocks we only analyze statements that are a part of some SLP
instance, therefore, all the statements are relevant.
Pattern statement needs to be analyzed instead of the original statement
if the original statement is not relevant. Otherwise, we analyze both
statements. In basic blocks we are called from some SLP instance
traversal, don't analyze pattern stmts instead, the pattern stmts
already will be part of SLP instance. */
stmt_vec_info pattern_stmt_info = STMT_VINFO_RELATED_STMT (stmt_info);
if (!STMT_VINFO_RELEVANT_P (stmt_info)
&& !STMT_VINFO_LIVE_P (stmt_info))
{
if (STMT_VINFO_IN_PATTERN_P (stmt_info)
&& pattern_stmt_info
&& (STMT_VINFO_RELEVANT_P (pattern_stmt_info)
|| STMT_VINFO_LIVE_P (pattern_stmt_info)))
{
/* Analyze PATTERN_STMT instead of the original stmt. */
stmt_info = pattern_stmt_info;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"==> examining pattern statement: %G",
stmt_info->stmt);
}
else
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location, "irrelevant.\n");
return opt_result::success ();
}
}
else if (STMT_VINFO_IN_PATTERN_P (stmt_info)
&& node == NULL
&& pattern_stmt_info
&& (STMT_VINFO_RELEVANT_P (pattern_stmt_info)
|| STMT_VINFO_LIVE_P (pattern_stmt_info)))
{
/* Analyze PATTERN_STMT too. */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"==> examining pattern statement: %G",
pattern_stmt_info->stmt);
opt_result res
= vect_analyze_stmt (pattern_stmt_info, need_to_vectorize, node,
node_instance, cost_vec);
if (!res)
return res;
}
switch (STMT_VINFO_DEF_TYPE (stmt_info))
{
case vect_internal_def:
break;
case vect_reduction_def:
case vect_nested_cycle:
gcc_assert (!bb_vinfo
&& (relevance == vect_used_in_outer
|| relevance == vect_used_in_outer_by_reduction
|| relevance == vect_used_by_reduction
|| relevance == vect_unused_in_scope
|| relevance == vect_used_only_live));
break;
case vect_induction_def:
gcc_assert (!bb_vinfo);
break;
case vect_constant_def:
case vect_external_def:
case vect_unknown_def_type:
default:
gcc_unreachable ();
}
if (STMT_VINFO_RELEVANT_P (stmt_info))
{
tree type = gimple_expr_type (stmt_info->stmt);
gcc_assert (!VECTOR_MODE_P (TYPE_MODE (type)));
gcall *call = dyn_cast <gcall *> (stmt_info->stmt);
gcc_assert (STMT_VINFO_VECTYPE (stmt_info)
|| (call && gimple_call_lhs (call) == NULL_TREE));
*need_to_vectorize = true;
}
if (PURE_SLP_STMT (stmt_info) && !node)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"handled only by SLP analysis\n");
return opt_result::success ();
}
ok = true;
if (!bb_vinfo
&& (STMT_VINFO_RELEVANT_P (stmt_info)
|| STMT_VINFO_DEF_TYPE (stmt_info) == vect_reduction_def))
/* Prefer vectorizable_call over vectorizable_simd_clone_call so
-mveclibabi= takes preference over library functions with
the simd attribute. */
ok = (vectorizable_call (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_simd_clone_call (stmt_info, NULL, NULL, node,
cost_vec)
|| vectorizable_conversion (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_operation (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_assignment (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_load (stmt_info, NULL, NULL, node, node_instance,
cost_vec)
|| vectorizable_store (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_reduction (stmt_info, node, node_instance, cost_vec)
|| vectorizable_induction (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_shift (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_condition (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_comparison (stmt_info, NULL, NULL, node,
cost_vec)
|| vectorizable_lc_phi (stmt_info, NULL, node));
else
{
if (bb_vinfo)
ok = (vectorizable_call (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_simd_clone_call (stmt_info, NULL, NULL, node,
cost_vec)
|| vectorizable_conversion (stmt_info, NULL, NULL, node,
cost_vec)
|| vectorizable_shift (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_operation (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_assignment (stmt_info, NULL, NULL, node,
cost_vec)
|| vectorizable_load (stmt_info, NULL, NULL, node, node_instance,
cost_vec)
|| vectorizable_store (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_condition (stmt_info, NULL, NULL, node, cost_vec)
|| vectorizable_comparison (stmt_info, NULL, NULL, node,
cost_vec));
}
if (!ok)
return opt_result::failure_at (stmt_info->stmt,
"not vectorized:"
" relevant stmt not supported: %G",
stmt_info->stmt);
/* Stmts that are (also) "live" (i.e. - that are used out of the loop)
need extra handling, except for vectorizable reductions. */
if (!bb_vinfo
&& STMT_VINFO_TYPE (stmt_info) != reduc_vec_info_type
&& STMT_VINFO_TYPE (stmt_info) != lc_phi_info_type
&& !can_vectorize_live_stmts (stmt_info, NULL, node, node_instance,
false, cost_vec))
return opt_result::failure_at (stmt_info->stmt,
"not vectorized:"
" live stmt not supported: %G",
stmt_info->stmt);
return opt_result::success ();
}
/* Function vect_transform_stmt.
Create a vectorized stmt to replace STMT_INFO, and insert it at GSI. */
bool
vect_transform_stmt (stmt_vec_info stmt_info, gimple_stmt_iterator *gsi,
slp_tree slp_node, slp_instance slp_node_instance)
{
vec_info *vinfo = stmt_info->vinfo;
bool is_store = false;
stmt_vec_info vec_stmt = NULL;
bool done;
gcc_assert (slp_node || !PURE_SLP_STMT (stmt_info));
stmt_vec_info old_vec_stmt_info = STMT_VINFO_VEC_STMT (stmt_info);
bool nested_p = (STMT_VINFO_LOOP_VINFO (stmt_info)
&& nested_in_vect_loop_p
(LOOP_VINFO_LOOP (STMT_VINFO_LOOP_VINFO (stmt_info)),
stmt_info));
gimple *stmt = stmt_info->stmt;
switch (STMT_VINFO_TYPE (stmt_info))
{
case type_demotion_vec_info_type:
case type_promotion_vec_info_type:
case type_conversion_vec_info_type:
done = vectorizable_conversion (stmt_info, gsi, &vec_stmt, slp_node,
NULL);
gcc_assert (done);
break;
case induc_vec_info_type:
done = vectorizable_induction (stmt_info, gsi, &vec_stmt, slp_node,
NULL);
gcc_assert (done);
break;
case shift_vec_info_type:
done = vectorizable_shift (stmt_info, gsi, &vec_stmt, slp_node, NULL);
gcc_assert (done);
break;
case op_vec_info_type:
done = vectorizable_operation (stmt_info, gsi, &vec_stmt, slp_node,
NULL);
gcc_assert (done);
break;
case assignment_vec_info_type:
done = vectorizable_assignment (stmt_info, gsi, &vec_stmt, slp_node,
NULL);
gcc_assert (done);
break;
case load_vec_info_type:
done = vectorizable_load (stmt_info, gsi, &vec_stmt, slp_node,
slp_node_instance, NULL);
gcc_assert (done);
break;
case store_vec_info_type:
done = vectorizable_store (stmt_info, gsi, &vec_stmt, slp_node, NULL);
gcc_assert (done);
if (STMT_VINFO_GROUPED_ACCESS (stmt_info) && !slp_node)
{
/* In case of interleaving, the whole chain is vectorized when the
last store in the chain is reached. Store stmts before the last
one are skipped, and there vec_stmt_info shouldn't be freed
meanwhile. */
stmt_vec_info group_info = DR_GROUP_FIRST_ELEMENT (stmt_info);
if (DR_GROUP_STORE_COUNT (group_info) == DR_GROUP_SIZE (group_info))
is_store = true;
}
else
is_store = true;
break;
case condition_vec_info_type:
done = vectorizable_condition (stmt_info, gsi, &vec_stmt, slp_node, NULL);
gcc_assert (done);
break;
case comparison_vec_info_type:
done = vectorizable_comparison (stmt_info, gsi, &vec_stmt,
slp_node, NULL);
gcc_assert (done);
break;
case call_vec_info_type:
done = vectorizable_call (stmt_info, gsi, &vec_stmt, slp_node, NULL);
stmt = gsi_stmt (*gsi);
break;
case call_simd_clone_vec_info_type:
done = vectorizable_simd_clone_call (stmt_info, gsi, &vec_stmt,
slp_node, NULL);
stmt = gsi_stmt (*gsi);
break;
case reduc_vec_info_type:
done = vect_transform_reduction (stmt_info, gsi, &vec_stmt, slp_node);
gcc_assert (done);
break;
case cycle_phi_info_type:
done = vect_transform_cycle_phi (stmt_info, &vec_stmt, slp_node,
slp_node_instance);
gcc_assert (done);
break;
case lc_phi_info_type:
done = vectorizable_lc_phi (stmt_info, &vec_stmt, slp_node);
gcc_assert (done);
break;
default:
if (!STMT_VINFO_LIVE_P (stmt_info))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"stmt not supported.\n");
gcc_unreachable ();
}
}
/* Verify SLP vectorization doesn't mess with STMT_VINFO_VEC_STMT.
This would break hybrid SLP vectorization. */
if (slp_node)
gcc_assert (!vec_stmt
&& STMT_VINFO_VEC_STMT (stmt_info) == old_vec_stmt_info);
/* Handle inner-loop stmts whose DEF is used in the loop-nest that
is being vectorized, but outside the immediately enclosing loop. */
if (vec_stmt
&& nested_p
&& STMT_VINFO_TYPE (stmt_info) != reduc_vec_info_type
&& (STMT_VINFO_RELEVANT (stmt_info) == vect_used_in_outer
|| STMT_VINFO_RELEVANT (stmt_info) ==
vect_used_in_outer_by_reduction))
{
class loop *innerloop = LOOP_VINFO_LOOP (
STMT_VINFO_LOOP_VINFO (stmt_info))->inner;
imm_use_iterator imm_iter;
use_operand_p use_p;
tree scalar_dest;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"Record the vdef for outer-loop vectorization.\n");
/* Find the relevant loop-exit phi-node, and reord the vec_stmt there
(to be used when vectorizing outer-loop stmts that use the DEF of
STMT). */
if (gimple_code (stmt) == GIMPLE_PHI)
scalar_dest = PHI_RESULT (stmt);
else
scalar_dest = gimple_get_lhs (stmt);
FOR_EACH_IMM_USE_FAST (use_p, imm_iter, scalar_dest)
if (!flow_bb_inside_loop_p (innerloop, gimple_bb (USE_STMT (use_p))))
{
stmt_vec_info exit_phi_info
= vinfo->lookup_stmt (USE_STMT (use_p));
STMT_VINFO_VEC_STMT (exit_phi_info) = vec_stmt;
}
}
if (vec_stmt)
STMT_VINFO_VEC_STMT (stmt_info) = vec_stmt;
if (STMT_VINFO_TYPE (stmt_info) == store_vec_info_type)
return is_store;
/* Handle stmts whose DEF is used outside the loop-nest that is
being vectorized. */
done = can_vectorize_live_stmts (stmt_info, gsi, slp_node,
slp_node_instance, true, NULL);
gcc_assert (done);
return false;
}
/* Remove a group of stores (for SLP or interleaving), free their
stmt_vec_info. */
void
vect_remove_stores (stmt_vec_info first_stmt_info)
{
vec_info *vinfo = first_stmt_info->vinfo;
stmt_vec_info next_stmt_info = first_stmt_info;
while (next_stmt_info)
{
stmt_vec_info tmp = DR_GROUP_NEXT_ELEMENT (next_stmt_info);
next_stmt_info = vect_orig_stmt (next_stmt_info);
/* Free the attached stmt_vec_info and remove the stmt. */
vinfo->remove_stmt (next_stmt_info);
next_stmt_info = tmp;
}
}
/* If NUNITS is nonzero, return a vector type that contains NUNITS
elements of type SCALAR_TYPE, or null if the target doesn't support
such a type.
If NUNITS is zero, return a vector type that contains elements of
type SCALAR_TYPE, choosing whichever vector size the target prefers.
If PREVAILING_MODE is VOIDmode, we have not yet chosen a vector mode
for this vectorization region and want to "autodetect" the best choice.
Otherwise, PREVAILING_MODE is a previously-chosen vector TYPE_MODE
and we want the new type to be interoperable with it. PREVAILING_MODE
in this case can be a scalar integer mode or a vector mode; when it
is a vector mode, the function acts like a tree-level version of
related_vector_mode. */
tree
get_related_vectype_for_scalar_type (machine_mode prevailing_mode,
tree scalar_type, poly_uint64 nunits)
{
tree orig_scalar_type = scalar_type;
scalar_mode inner_mode;
machine_mode simd_mode;
tree vectype;
if (!is_int_mode (TYPE_MODE (scalar_type), &inner_mode)
&& !is_float_mode (TYPE_MODE (scalar_type), &inner_mode))
return NULL_TREE;
unsigned int nbytes = GET_MODE_SIZE (inner_mode);
/* For vector types of elements whose mode precision doesn't
match their types precision we use a element type of mode
precision. The vectorization routines will have to make sure
they support the proper result truncation/extension.
We also make sure to build vector types with INTEGER_TYPE
component type only. */
if (INTEGRAL_TYPE_P (scalar_type)
&& (GET_MODE_BITSIZE (inner_mode) != TYPE_PRECISION (scalar_type)
|| TREE_CODE (scalar_type) != INTEGER_TYPE))
scalar_type = build_nonstandard_integer_type (GET_MODE_BITSIZE (inner_mode),
TYPE_UNSIGNED (scalar_type));
/* We shouldn't end up building VECTOR_TYPEs of non-scalar components.
When the component mode passes the above test simply use a type
corresponding to that mode. The theory is that any use that
would cause problems with this will disable vectorization anyway. */
else if (!SCALAR_FLOAT_TYPE_P (scalar_type)
&& !INTEGRAL_TYPE_P (scalar_type))
scalar_type = lang_hooks.types.type_for_mode (inner_mode, 1);
/* We can't build a vector type of elements with alignment bigger than
their size. */
else if (nbytes < TYPE_ALIGN_UNIT (scalar_type))
scalar_type = lang_hooks.types.type_for_mode (inner_mode,
TYPE_UNSIGNED (scalar_type));
/* If we felt back to using the mode fail if there was
no scalar type for it. */
if (scalar_type == NULL_TREE)
return NULL_TREE;
/* If no prevailing mode was supplied, use the mode the target prefers.
Otherwise lookup a vector mode based on the prevailing mode. */
if (prevailing_mode == VOIDmode)
{
gcc_assert (known_eq (nunits, 0U));
simd_mode = targetm.vectorize.preferred_simd_mode (inner_mode);
if (SCALAR_INT_MODE_P (simd_mode))
{
/* Traditional behavior is not to take the integer mode
literally, but simply to use it as a way of determining
the vector size. It is up to mode_for_vector to decide
what the TYPE_MODE should be.
Note that nunits == 1 is allowed in order to support single
element vector types. */
if (!multiple_p (GET_MODE_SIZE (simd_mode), nbytes, &nunits)
|| !mode_for_vector (inner_mode, nunits).exists (&simd_mode))
return NULL_TREE;
}
}
else if (SCALAR_INT_MODE_P (prevailing_mode)
|| !related_vector_mode (prevailing_mode,
inner_mode, nunits).exists (&simd_mode))
{
/* Fall back to using mode_for_vector, mostly in the hope of being
able to use an integer mode. */
if (known_eq (nunits, 0U)
&& !multiple_p (GET_MODE_SIZE (prevailing_mode), nbytes, &nunits))
return NULL_TREE;
if (!mode_for_vector (inner_mode, nunits).exists (&simd_mode))
return NULL_TREE;
}
vectype = build_vector_type_for_mode (scalar_type, simd_mode);
/* In cases where the mode was chosen by mode_for_vector, check that
the target actually supports the chosen mode, or that it at least
allows the vector mode to be replaced by a like-sized integer. */
if (!VECTOR_MODE_P (TYPE_MODE (vectype))
&& !INTEGRAL_MODE_P (TYPE_MODE (vectype)))
return NULL_TREE;
/* Re-attach the address-space qualifier if we canonicalized the scalar
type. */
if (TYPE_ADDR_SPACE (orig_scalar_type) != TYPE_ADDR_SPACE (vectype))
return build_qualified_type
(vectype, KEEP_QUAL_ADDR_SPACE (TYPE_QUALS (orig_scalar_type)));
return vectype;
}
/* Function get_vectype_for_scalar_type.
Returns the vector type corresponding to SCALAR_TYPE as supported
by the target. If GROUP_SIZE is nonzero and we're performing BB
vectorization, make sure that the number of elements in the vector
is no bigger than GROUP_SIZE. */
tree
get_vectype_for_scalar_type (vec_info *vinfo, tree scalar_type,
unsigned int group_size)
{
/* For BB vectorization, we should always have a group size once we've
constructed the SLP tree; the only valid uses of zero GROUP_SIZEs
are tentative requests during things like early data reference
analysis and pattern recognition. */
if (is_a <bb_vec_info> (vinfo))
gcc_assert (vinfo->slp_instances.is_empty () || group_size != 0);
else
group_size = 0;
tree vectype = get_related_vectype_for_scalar_type (vinfo->vector_mode,
scalar_type);
if (vectype && vinfo->vector_mode == VOIDmode)
vinfo->vector_mode = TYPE_MODE (vectype);
/* Register the natural choice of vector type, before the group size
has been applied. */
if (vectype)
vinfo->used_vector_modes.add (TYPE_MODE (vectype));
/* If the natural choice of vector type doesn't satisfy GROUP_SIZE,
try again with an explicit number of elements. */
if (vectype
&& group_size
&& maybe_ge (TYPE_VECTOR_SUBPARTS (vectype), group_size))
{
/* Start with the biggest number of units that fits within
GROUP_SIZE and halve it until we find a valid vector type.
Usually either the first attempt will succeed or all will
fail (in the latter case because GROUP_SIZE is too small
for the target), but it's possible that a target could have
a hole between supported vector types.
If GROUP_SIZE is not a power of 2, this has the effect of
trying the largest power of 2 that fits within the group,
even though the group is not a multiple of that vector size.
The BB vectorizer will then try to carve up the group into
smaller pieces. */
unsigned int nunits = 1 << floor_log2 (group_size);
do
{
vectype = get_related_vectype_for_scalar_type (vinfo->vector_mode,
scalar_type, nunits);
nunits /= 2;
}
while (nunits > 1 && !vectype);
}
return vectype;
}
/* Return the vector type corresponding to SCALAR_TYPE as supported
by the target. NODE, if nonnull, is the SLP tree node that will
use the returned vector type. */
tree
get_vectype_for_scalar_type (vec_info *vinfo, tree scalar_type, slp_tree node)
{
unsigned int group_size = 0;
if (node)
{
group_size = SLP_TREE_SCALAR_OPS (node).length ();
if (group_size == 0)
group_size = SLP_TREE_SCALAR_STMTS (node).length ();
}
return get_vectype_for_scalar_type (vinfo, scalar_type, group_size);
}
/* Function get_mask_type_for_scalar_type.
Returns the mask type corresponding to a result of comparison
of vectors of specified SCALAR_TYPE as supported by target.
If GROUP_SIZE is nonzero and we're performing BB vectorization,
make sure that the number of elements in the vector is no bigger
than GROUP_SIZE. */
tree
get_mask_type_for_scalar_type (vec_info *vinfo, tree scalar_type,
unsigned int group_size)
{
tree vectype = get_vectype_for_scalar_type (vinfo, scalar_type, group_size);
if (!vectype)
return NULL;
return truth_type_for (vectype);
}
/* Function get_same_sized_vectype
Returns a vector type corresponding to SCALAR_TYPE of size
VECTOR_TYPE if supported by the target. */
tree
get_same_sized_vectype (tree scalar_type, tree vector_type)
{
if (VECT_SCALAR_BOOLEAN_TYPE_P (scalar_type))
return truth_type_for (vector_type);
poly_uint64 nunits;
if (!multiple_p (GET_MODE_SIZE (TYPE_MODE (vector_type)),
GET_MODE_SIZE (TYPE_MODE (scalar_type)), &nunits))
return NULL_TREE;
return get_related_vectype_for_scalar_type (TYPE_MODE (vector_type),
scalar_type, nunits);
}
/* Return true if replacing LOOP_VINFO->vector_mode with VECTOR_MODE
would not change the chosen vector modes. */
bool
vect_chooses_same_modes_p (vec_info *vinfo, machine_mode vector_mode)
{
for (vec_info::mode_set::iterator i = vinfo->used_vector_modes.begin ();
i != vinfo->used_vector_modes.end (); ++i)
if (!VECTOR_MODE_P (*i)
|| related_vector_mode (vector_mode, GET_MODE_INNER (*i), 0) != *i)
return false;
return true;
}
/* Function vect_is_simple_use.
Input:
VINFO - the vect info of the loop or basic block that is being vectorized.
OPERAND - operand in the loop or bb.
Output:
DEF_STMT_INFO_OUT (optional) - information about the defining stmt in
case OPERAND is an SSA_NAME that is defined in the vectorizable region
DEF_STMT_OUT (optional) - the defining stmt in case OPERAND is an SSA_NAME;
the definition could be anywhere in the function
DT - the type of definition
Returns whether a stmt with OPERAND can be vectorized.
For loops, supportable operands are constants, loop invariants, and operands
that are defined by the current iteration of the loop. Unsupportable
operands are those that are defined by a previous iteration of the loop (as
is the case in reduction/induction computations).
For basic blocks, supportable operands are constants and bb invariants.
For now, operands defined outside the basic block are not supported. */
bool
vect_is_simple_use (tree operand, vec_info *vinfo, enum vect_def_type *dt,
stmt_vec_info *def_stmt_info_out, gimple **def_stmt_out)
{
if (def_stmt_info_out)
*def_stmt_info_out = NULL;
if (def_stmt_out)
*def_stmt_out = NULL;
*dt = vect_unknown_def_type;
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"vect_is_simple_use: operand ");
if (TREE_CODE (operand) == SSA_NAME
&& !SSA_NAME_IS_DEFAULT_DEF (operand))
dump_gimple_expr (MSG_NOTE, TDF_SLIM, SSA_NAME_DEF_STMT (operand), 0);
else
dump_generic_expr (MSG_NOTE, TDF_SLIM, operand);
}
if (CONSTANT_CLASS_P (operand))
*dt = vect_constant_def;
else if (is_gimple_min_invariant (operand))
*dt = vect_external_def;
else if (TREE_CODE (operand) != SSA_NAME)
*dt = vect_unknown_def_type;
else if (SSA_NAME_IS_DEFAULT_DEF (operand))
*dt = vect_external_def;
else
{
gimple *def_stmt = SSA_NAME_DEF_STMT (operand);
stmt_vec_info stmt_vinfo = vinfo->lookup_def (operand);
if (!stmt_vinfo)
*dt = vect_external_def;
else
{
stmt_vinfo = vect_stmt_to_vectorize (stmt_vinfo);
def_stmt = stmt_vinfo->stmt;
switch (gimple_code (def_stmt))
{
case GIMPLE_PHI:
case GIMPLE_ASSIGN:
case GIMPLE_CALL:
*dt = STMT_VINFO_DEF_TYPE (stmt_vinfo);
break;
default:
*dt = vect_unknown_def_type;
break;
}
if (def_stmt_info_out)
*def_stmt_info_out = stmt_vinfo;
}
if (def_stmt_out)
*def_stmt_out = def_stmt;
}
if (dump_enabled_p ())
{
dump_printf (MSG_NOTE, ", type of def: ");
switch (*dt)
{
case vect_uninitialized_def:
dump_printf (MSG_NOTE, "uninitialized\n");
break;
case vect_constant_def:
dump_printf (MSG_NOTE, "constant\n");
break;
case vect_external_def:
dump_printf (MSG_NOTE, "external\n");
break;
case vect_internal_def:
dump_printf (MSG_NOTE, "internal\n");
break;
case vect_induction_def:
dump_printf (MSG_NOTE, "induction\n");
break;
case vect_reduction_def:
dump_printf (MSG_NOTE, "reduction\n");
break;
case vect_double_reduction_def:
dump_printf (MSG_NOTE, "double reduction\n");
break;
case vect_nested_cycle:
dump_printf (MSG_NOTE, "nested cycle\n");
break;
case vect_unknown_def_type:
dump_printf (MSG_NOTE, "unknown\n");
break;
}
}
if (*dt == vect_unknown_def_type)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"Unsupported pattern.\n");
return false;
}
return true;
}
/* Function vect_is_simple_use.
Same as vect_is_simple_use but also determines the vector operand
type of OPERAND and stores it to *VECTYPE. If the definition of
OPERAND is vect_uninitialized_def, vect_constant_def or
vect_external_def *VECTYPE will be set to NULL_TREE and the caller
is responsible to compute the best suited vector type for the
scalar operand. */
bool
vect_is_simple_use (tree operand, vec_info *vinfo, enum vect_def_type *dt,
tree *vectype, stmt_vec_info *def_stmt_info_out,
gimple **def_stmt_out)
{
stmt_vec_info def_stmt_info;
gimple *def_stmt;
if (!vect_is_simple_use (operand, vinfo, dt, &def_stmt_info, &def_stmt))
return false;
if (def_stmt_out)
*def_stmt_out = def_stmt;
if (def_stmt_info_out)
*def_stmt_info_out = def_stmt_info;
/* Now get a vector type if the def is internal, otherwise supply
NULL_TREE and leave it up to the caller to figure out a proper
type for the use stmt. */
if (*dt == vect_internal_def
|| *dt == vect_induction_def
|| *dt == vect_reduction_def
|| *dt == vect_double_reduction_def
|| *dt == vect_nested_cycle)
{
*vectype = STMT_VINFO_VECTYPE (def_stmt_info);
gcc_assert (*vectype != NULL_TREE);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_is_simple_use: vectype %T\n", *vectype);
}
else if (*dt == vect_uninitialized_def
|| *dt == vect_constant_def
|| *dt == vect_external_def)
*vectype = NULL_TREE;
else
gcc_unreachable ();
return true;
}
/* Function supportable_widening_operation
Check whether an operation represented by the code CODE is a
widening operation that is supported by the target platform in
vector form (i.e., when operating on arguments of type VECTYPE_IN
producing a result of type VECTYPE_OUT).
Widening operations we currently support are NOP (CONVERT), FLOAT,
FIX_TRUNC and WIDEN_MULT. This function checks if these operations
are supported by the target platform either directly (via vector
tree-codes), or via target builtins.
Output:
- CODE1 and CODE2 are codes of vector operations to be used when
vectorizing the operation, if available.
- MULTI_STEP_CVT determines the number of required intermediate steps in
case of multi-step conversion (like char->short->int - in that case
MULTI_STEP_CVT will be 1).
- INTERM_TYPES contains the intermediate type required to perform the
widening operation (short in the above example). */
bool
supportable_widening_operation (enum tree_code code, stmt_vec_info stmt_info,
tree vectype_out, tree vectype_in,
enum tree_code *code1, enum tree_code *code2,
int *multi_step_cvt,
vec<tree> *interm_types)
{
loop_vec_info loop_info = STMT_VINFO_LOOP_VINFO (stmt_info);
class loop *vect_loop = NULL;
machine_mode vec_mode;
enum insn_code icode1, icode2;
optab optab1, optab2;
tree vectype = vectype_in;
tree wide_vectype = vectype_out;
enum tree_code c1, c2;
int i;
tree prev_type, intermediate_type;
machine_mode intermediate_mode, prev_mode;
optab optab3, optab4;
*multi_step_cvt = 0;
if (loop_info)
vect_loop = LOOP_VINFO_LOOP (loop_info);
switch (code)
{
case WIDEN_MULT_EXPR:
/* The result of a vectorized widening operation usually requires
two vectors (because the widened results do not fit into one vector).
The generated vector results would normally be expected to be
generated in the same order as in the original scalar computation,
i.e. if 8 results are generated in each vector iteration, they are
to be organized as follows:
vect1: [res1,res2,res3,res4],
vect2: [res5,res6,res7,res8].
However, in the special case that the result of the widening
operation is used in a reduction computation only, the order doesn't
matter (because when vectorizing a reduction we change the order of
the computation). Some targets can take advantage of this and
generate more efficient code. For example, targets like Altivec,
that support widen_mult using a sequence of {mult_even,mult_odd}
generate the following vectors:
vect1: [res1,res3,res5,res7],
vect2: [res2,res4,res6,res8].
When vectorizing outer-loops, we execute the inner-loop sequentially
(each vectorized inner-loop iteration contributes to VF outer-loop
iterations in parallel). We therefore don't allow to change the
order of the computation in the inner-loop during outer-loop
vectorization. */
/* TODO: Another case in which order doesn't *really* matter is when we
widen and then contract again, e.g. (short)((int)x * y >> 8).
Normally, pack_trunc performs an even/odd permute, whereas the
repack from an even/odd expansion would be an interleave, which
would be significantly simpler for e.g. AVX2. */
/* In any case, in order to avoid duplicating the code below, recurse
on VEC_WIDEN_MULT_EVEN_EXPR. If it succeeds, all the return values
are properly set up for the caller. If we fail, we'll continue with
a VEC_WIDEN_MULT_LO/HI_EXPR check. */
if (vect_loop
&& STMT_VINFO_RELEVANT (stmt_info) == vect_used_by_reduction
&& !nested_in_vect_loop_p (vect_loop, stmt_info)
&& supportable_widening_operation (VEC_WIDEN_MULT_EVEN_EXPR,
stmt_info, vectype_out,
vectype_in, code1, code2,
multi_step_cvt, interm_types))
{
/* Elements in a vector with vect_used_by_reduction property cannot
be reordered if the use chain with this property does not have the
same operation. One such an example is s += a * b, where elements
in a and b cannot be reordered. Here we check if the vector defined
by STMT is only directly used in the reduction statement. */
tree lhs = gimple_assign_lhs (stmt_info->stmt);
stmt_vec_info use_stmt_info = loop_info->lookup_single_use (lhs);
if (use_stmt_info
&& STMT_VINFO_DEF_TYPE (use_stmt_info) == vect_reduction_def)
return true;
}
c1 = VEC_WIDEN_MULT_LO_EXPR;
c2 = VEC_WIDEN_MULT_HI_EXPR;
break;
case DOT_PROD_EXPR:
c1 = DOT_PROD_EXPR;
c2 = DOT_PROD_EXPR;
break;
case SAD_EXPR:
c1 = SAD_EXPR;
c2 = SAD_EXPR;
break;
case VEC_WIDEN_MULT_EVEN_EXPR:
/* Support the recursion induced just above. */
c1 = VEC_WIDEN_MULT_EVEN_EXPR;
c2 = VEC_WIDEN_MULT_ODD_EXPR;
break;
case WIDEN_LSHIFT_EXPR:
c1 = VEC_WIDEN_LSHIFT_LO_EXPR;
c2 = VEC_WIDEN_LSHIFT_HI_EXPR;
break;
CASE_CONVERT:
c1 = VEC_UNPACK_LO_EXPR;
c2 = VEC_UNPACK_HI_EXPR;
break;
case FLOAT_EXPR:
c1 = VEC_UNPACK_FLOAT_LO_EXPR;
c2 = VEC_UNPACK_FLOAT_HI_EXPR;
break;
case FIX_TRUNC_EXPR:
c1 = VEC_UNPACK_FIX_TRUNC_LO_EXPR;
c2 = VEC_UNPACK_FIX_TRUNC_HI_EXPR;
break;
default:
gcc_unreachable ();
}
if (BYTES_BIG_ENDIAN && c1 != VEC_WIDEN_MULT_EVEN_EXPR)
std::swap (c1, c2);
if (code == FIX_TRUNC_EXPR)
{
/* The signedness is determined from output operand. */
optab1 = optab_for_tree_code (c1, vectype_out, optab_default);
optab2 = optab_for_tree_code (c2, vectype_out, optab_default);
}
else if (CONVERT_EXPR_CODE_P (code)
&& VECTOR_BOOLEAN_TYPE_P (wide_vectype)
&& VECTOR_BOOLEAN_TYPE_P (vectype)
&& TYPE_MODE (wide_vectype) == TYPE_MODE (vectype)
&& SCALAR_INT_MODE_P (TYPE_MODE (vectype)))
{
/* If the input and result modes are the same, a different optab
is needed where we pass in the number of units in vectype. */
optab1 = vec_unpacks_sbool_lo_optab;
optab2 = vec_unpacks_sbool_hi_optab;
}
else
{
optab1 = optab_for_tree_code (c1, vectype, optab_default);
optab2 = optab_for_tree_code (c2, vectype, optab_default);
}
if (!optab1 || !optab2)
return false;
vec_mode = TYPE_MODE (vectype);
if ((icode1 = optab_handler (optab1, vec_mode)) == CODE_FOR_nothing
|| (icode2 = optab_handler (optab2, vec_mode)) == CODE_FOR_nothing)
return false;
*code1 = c1;
*code2 = c2;
if (insn_data[icode1].operand[0].mode == TYPE_MODE (wide_vectype)
&& insn_data[icode2].operand[0].mode == TYPE_MODE (wide_vectype))
{
if (!VECTOR_BOOLEAN_TYPE_P (vectype))
return true;
/* For scalar masks we may have different boolean
vector types having the same QImode. Thus we
add additional check for elements number. */
if (known_eq (TYPE_VECTOR_SUBPARTS (vectype),
TYPE_VECTOR_SUBPARTS (wide_vectype) * 2))
return true;
}
/* Check if it's a multi-step conversion that can be done using intermediate
types. */
prev_type = vectype;
prev_mode = vec_mode;
if (!CONVERT_EXPR_CODE_P (code))
return false;
/* We assume here that there will not be more than MAX_INTERM_CVT_STEPS
intermediate steps in promotion sequence. We try
MAX_INTERM_CVT_STEPS to get to NARROW_VECTYPE, and fail if we do
not. */
interm_types->create (MAX_INTERM_CVT_STEPS);
for (i = 0; i < MAX_INTERM_CVT_STEPS; i++)
{
intermediate_mode = insn_data[icode1].operand[0].mode;
if (VECTOR_BOOLEAN_TYPE_P (prev_type))
intermediate_type
= vect_halve_mask_nunits (prev_type, intermediate_mode);
else
intermediate_type
= lang_hooks.types.type_for_mode (intermediate_mode,
TYPE_UNSIGNED (prev_type));
if (VECTOR_BOOLEAN_TYPE_P (intermediate_type)
&& VECTOR_BOOLEAN_TYPE_P (prev_type)
&& intermediate_mode == prev_mode
&& SCALAR_INT_MODE_P (prev_mode))
{
/* If the input and result modes are the same, a different optab
is needed where we pass in the number of units in vectype. */
optab3 = vec_unpacks_sbool_lo_optab;
optab4 = vec_unpacks_sbool_hi_optab;
}
else
{
optab3 = optab_for_tree_code (c1, intermediate_type, optab_default);
optab4 = optab_for_tree_code (c2, intermediate_type, optab_default);
}
if (!optab3 || !optab4
|| (icode1 = optab_handler (optab1, prev_mode)) == CODE_FOR_nothing
|| insn_data[icode1].operand[0].mode != intermediate_mode
|| (icode2 = optab_handler (optab2, prev_mode)) == CODE_FOR_nothing
|| insn_data[icode2].operand[0].mode != intermediate_mode
|| ((icode1 = optab_handler (optab3, intermediate_mode))
== CODE_FOR_nothing)
|| ((icode2 = optab_handler (optab4, intermediate_mode))
== CODE_FOR_nothing))
break;
interm_types->quick_push (intermediate_type);
(*multi_step_cvt)++;
if (insn_data[icode1].operand[0].mode == TYPE_MODE (wide_vectype)
&& insn_data[icode2].operand[0].mode == TYPE_MODE (wide_vectype))
{
if (!VECTOR_BOOLEAN_TYPE_P (vectype))
return true;
if (known_eq (TYPE_VECTOR_SUBPARTS (intermediate_type),
TYPE_VECTOR_SUBPARTS (wide_vectype) * 2))
return true;
}
prev_type = intermediate_type;
prev_mode = intermediate_mode;
}
interm_types->release ();
return false;
}
/* Function supportable_narrowing_operation
Check whether an operation represented by the code CODE is a
narrowing operation that is supported by the target platform in
vector form (i.e., when operating on arguments of type VECTYPE_IN
and producing a result of type VECTYPE_OUT).
Narrowing operations we currently support are NOP (CONVERT), FIX_TRUNC
and FLOAT. This function checks if these operations are supported by
the target platform directly via vector tree-codes.
Output:
- CODE1 is the code of a vector operation to be used when
vectorizing the operation, if available.
- MULTI_STEP_CVT determines the number of required intermediate steps in
case of multi-step conversion (like int->short->char - in that case
MULTI_STEP_CVT will be 1).
- INTERM_TYPES contains the intermediate type required to perform the
narrowing operation (short in the above example). */
bool
supportable_narrowing_operation (enum tree_code code,
tree vectype_out, tree vectype_in,
enum tree_code *code1, int *multi_step_cvt,
vec<tree> *interm_types)
{
machine_mode vec_mode;
enum insn_code icode1;
optab optab1, interm_optab;
tree vectype = vectype_in;
tree narrow_vectype = vectype_out;
enum tree_code c1;
tree intermediate_type, prev_type;
machine_mode intermediate_mode, prev_mode;
int i;
bool uns;
*multi_step_cvt = 0;
switch (code)
{
CASE_CONVERT:
c1 = VEC_PACK_TRUNC_EXPR;
if (VECTOR_BOOLEAN_TYPE_P (narrow_vectype)
&& VECTOR_BOOLEAN_TYPE_P (vectype)
&& TYPE_MODE (narrow_vectype) == TYPE_MODE (vectype)
&& SCALAR_INT_MODE_P (TYPE_MODE (vectype)))
optab1 = vec_pack_sbool_trunc_optab;
else
optab1 = optab_for_tree_code (c1, vectype, optab_default);
break;
case FIX_TRUNC_EXPR:
c1 = VEC_PACK_FIX_TRUNC_EXPR;
/* The signedness is determined from output operand. */
optab1 = optab_for_tree_code (c1, vectype_out, optab_default);
break;
case FLOAT_EXPR:
c1 = VEC_PACK_FLOAT_EXPR;
optab1 = optab_for_tree_code (c1, vectype, optab_default);
break;
default:
gcc_unreachable ();
}
if (!optab1)
return false;
vec_mode = TYPE_MODE (vectype);
if ((icode1 = optab_handler (optab1, vec_mode)) == CODE_FOR_nothing)
return false;
*code1 = c1;
if (insn_data[icode1].operand[0].mode == TYPE_MODE (narrow_vectype))
{
if (!VECTOR_BOOLEAN_TYPE_P (vectype))
return true;
/* For scalar masks we may have different boolean
vector types having the same QImode. Thus we
add additional check for elements number. */
if (known_eq (TYPE_VECTOR_SUBPARTS (vectype) * 2,
TYPE_VECTOR_SUBPARTS (narrow_vectype)))
return true;
}
if (code == FLOAT_EXPR)
return false;
/* Check if it's a multi-step conversion that can be done using intermediate
types. */
prev_mode = vec_mode;
prev_type = vectype;
if (code == FIX_TRUNC_EXPR)
uns = TYPE_UNSIGNED (vectype_out);
else
uns = TYPE_UNSIGNED (vectype);
/* For multi-step FIX_TRUNC_EXPR prefer signed floating to integer
conversion over unsigned, as unsigned FIX_TRUNC_EXPR is often more
costly than signed. */
if (code == FIX_TRUNC_EXPR && uns)
{
enum insn_code icode2;
intermediate_type
= lang_hooks.types.type_for_mode (TYPE_MODE (vectype_out), 0);
interm_optab
= optab_for_tree_code (c1, intermediate_type, optab_default);
if (interm_optab != unknown_optab
&& (icode2 = optab_handler (optab1, vec_mode)) != CODE_FOR_nothing
&& insn_data[icode1].operand[0].mode
== insn_data[icode2].operand[0].mode)
{
uns = false;
optab1 = interm_optab;
icode1 = icode2;
}
}
/* We assume here that there will not be more than MAX_INTERM_CVT_STEPS
intermediate steps in promotion sequence. We try
MAX_INTERM_CVT_STEPS to get to NARROW_VECTYPE, and fail if we do not. */
interm_types->create (MAX_INTERM_CVT_STEPS);
for (i = 0; i < MAX_INTERM_CVT_STEPS; i++)
{
intermediate_mode = insn_data[icode1].operand[0].mode;
if (VECTOR_BOOLEAN_TYPE_P (prev_type))
intermediate_type
= vect_double_mask_nunits (prev_type, intermediate_mode);
else
intermediate_type
= lang_hooks.types.type_for_mode (intermediate_mode, uns);
if (VECTOR_BOOLEAN_TYPE_P (intermediate_type)
&& VECTOR_BOOLEAN_TYPE_P (prev_type)
&& intermediate_mode == prev_mode
&& SCALAR_INT_MODE_P (prev_mode))
interm_optab = vec_pack_sbool_trunc_optab;
else
interm_optab
= optab_for_tree_code (VEC_PACK_TRUNC_EXPR, intermediate_type,
optab_default);
if (!interm_optab
|| ((icode1 = optab_handler (optab1, prev_mode)) == CODE_FOR_nothing)
|| insn_data[icode1].operand[0].mode != intermediate_mode
|| ((icode1 = optab_handler (interm_optab, intermediate_mode))
== CODE_FOR_nothing))
break;
interm_types->quick_push (intermediate_type);
(*multi_step_cvt)++;
if (insn_data[icode1].operand[0].mode == TYPE_MODE (narrow_vectype))
{
if (!VECTOR_BOOLEAN_TYPE_P (vectype))
return true;
if (known_eq (TYPE_VECTOR_SUBPARTS (intermediate_type) * 2,
TYPE_VECTOR_SUBPARTS (narrow_vectype)))
return true;
}
prev_mode = intermediate_mode;
prev_type = intermediate_type;
optab1 = interm_optab;
}
interm_types->release ();
return false;
}
/* Generate and return a statement that sets vector mask MASK such that
MASK[I] is true iff J + START_INDEX < END_INDEX for all J <= I. */
gcall *
vect_gen_while (tree mask, tree start_index, tree end_index)
{
tree cmp_type = TREE_TYPE (start_index);
tree mask_type = TREE_TYPE (mask);
gcc_checking_assert (direct_internal_fn_supported_p (IFN_WHILE_ULT,
cmp_type, mask_type,
OPTIMIZE_FOR_SPEED));
gcall *call = gimple_build_call_internal (IFN_WHILE_ULT, 3,
start_index, end_index,
build_zero_cst (mask_type));
gimple_call_set_lhs (call, mask);
return call;
}
/* Generate a vector mask of type MASK_TYPE for which index I is false iff
J + START_INDEX < END_INDEX for all J <= I. Add the statements to SEQ. */
tree
vect_gen_while_not (gimple_seq *seq, tree mask_type, tree start_index,
tree end_index)
{
tree tmp = make_ssa_name (mask_type);
gcall *call = vect_gen_while (tmp, start_index, end_index);
gimple_seq_add_stmt (seq, call);
return gimple_build (seq, BIT_NOT_EXPR, mask_type, tmp);
}
/* Try to compute the vector types required to vectorize STMT_INFO,
returning true on success and false if vectorization isn't possible.
If GROUP_SIZE is nonzero and we're performing BB vectorization,
take sure that the number of elements in the vectors is no bigger
than GROUP_SIZE.
On success:
- Set *STMT_VECTYPE_OUT to:
- NULL_TREE if the statement doesn't need to be vectorized;
- the equivalent of STMT_VINFO_VECTYPE otherwise.
- Set *NUNITS_VECTYPE_OUT to the vector type that contains the maximum
number of units needed to vectorize STMT_INFO, or NULL_TREE if the
statement does not help to determine the overall number of units. */
opt_result
vect_get_vector_types_for_stmt (stmt_vec_info stmt_info,
tree *stmt_vectype_out,
tree *nunits_vectype_out,
unsigned int group_size)
{
vec_info *vinfo = stmt_info->vinfo;
gimple *stmt = stmt_info->stmt;
/* For BB vectorization, we should always have a group size once we've
constructed the SLP tree; the only valid uses of zero GROUP_SIZEs
are tentative requests during things like early data reference
analysis and pattern recognition. */
if (is_a <bb_vec_info> (vinfo))
gcc_assert (vinfo->slp_instances.is_empty () || group_size != 0);
else
group_size = 0;
*stmt_vectype_out = NULL_TREE;
*nunits_vectype_out = NULL_TREE;
if (gimple_get_lhs (stmt) == NULL_TREE
/* MASK_STORE has no lhs, but is ok. */
&& !gimple_call_internal_p (stmt, IFN_MASK_STORE))
{
if (is_a <gcall *> (stmt))
{
/* Ignore calls with no lhs. These must be calls to
#pragma omp simd functions, and what vectorization factor
it really needs can't be determined until
vectorizable_simd_clone_call. */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"defer to SIMD clone analysis.\n");
return opt_result::success ();
}
return opt_result::failure_at (stmt,
"not vectorized: irregular stmt.%G", stmt);
}
if (VECTOR_MODE_P (TYPE_MODE (gimple_expr_type (stmt))))
return opt_result::failure_at (stmt,
"not vectorized: vector stmt in loop:%G",
stmt);
tree vectype;
tree scalar_type = NULL_TREE;
if (group_size == 0 && STMT_VINFO_VECTYPE (stmt_info))
{
vectype = STMT_VINFO_VECTYPE (stmt_info);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"precomputed vectype: %T\n", vectype);
}
else if (vect_use_mask_type_p (stmt_info))
{
unsigned int precision = stmt_info->mask_precision;
scalar_type = build_nonstandard_integer_type (precision, 1);
vectype = get_mask_type_for_scalar_type (vinfo, scalar_type, group_size);
if (!vectype)
return opt_result::failure_at (stmt, "not vectorized: unsupported"
" data-type %T\n", scalar_type);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location, "vectype: %T\n", vectype);
}
else
{
if (data_reference *dr = STMT_VINFO_DATA_REF (stmt_info))
scalar_type = TREE_TYPE (DR_REF (dr));
else if (gimple_call_internal_p (stmt, IFN_MASK_STORE))
scalar_type = TREE_TYPE (gimple_call_arg (stmt, 3));
else
scalar_type = TREE_TYPE (gimple_get_lhs (stmt));
if (dump_enabled_p ())
{
if (group_size)
dump_printf_loc (MSG_NOTE, vect_location,
"get vectype for scalar type (group size %d):"
" %T\n", group_size, scalar_type);
else
dump_printf_loc (MSG_NOTE, vect_location,
"get vectype for scalar type: %T\n", scalar_type);
}
vectype = get_vectype_for_scalar_type (vinfo, scalar_type, group_size);
if (!vectype)
return opt_result::failure_at (stmt,
"not vectorized:"
" unsupported data-type %T\n",
scalar_type);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location, "vectype: %T\n", vectype);
}
*stmt_vectype_out = vectype;
/* Don't try to compute scalar types if the stmt produces a boolean
vector; use the existing vector type instead. */
tree nunits_vectype = vectype;
if (!VECTOR_BOOLEAN_TYPE_P (vectype))
{
/* The number of units is set according to the smallest scalar
type (or the largest vector size, but we only support one
vector size per vectorization). */
HOST_WIDE_INT dummy;
scalar_type = vect_get_smallest_scalar_type (stmt_info, &dummy, &dummy);
if (scalar_type != TREE_TYPE (vectype))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"get vectype for smallest scalar type: %T\n",
scalar_type);
nunits_vectype = get_vectype_for_scalar_type (vinfo, scalar_type,
group_size);
if (!nunits_vectype)
return opt_result::failure_at
(stmt, "not vectorized: unsupported data-type %T\n",
scalar_type);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location, "nunits vectype: %T\n",
nunits_vectype);
}
}
if (!multiple_p (TYPE_VECTOR_SUBPARTS (nunits_vectype),
TYPE_VECTOR_SUBPARTS (*stmt_vectype_out)))
return opt_result::failure_at (stmt,
"Not vectorized: Incompatible number "
"of vector subparts between %T and %T\n",
nunits_vectype, *stmt_vectype_out);
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location, "nunits = ");
dump_dec (MSG_NOTE, TYPE_VECTOR_SUBPARTS (nunits_vectype));
dump_printf (MSG_NOTE, "\n");
}
*nunits_vectype_out = nunits_vectype;
return opt_result::success ();
}
|
3d25pt_var.lbpar.c | #include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
/*
* Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*13);
for(m=0; m<13;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 4;
tile_size[1] = 4;
tile_size[2] = 4;
tile_size[3] = 2048;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<13; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) {
for (t1=-1;t1<=2*Nt-2;t1++) {
lbp=ceild(t1+2,2);
ubp=min(floord(4*Nt+Nz-9,4),floord(2*t1+Nz-4,4));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(ceild(t1+2,2),ceild(4*t2-Nz+9,4));t3<=min(min(floord(4*Nt+Ny-9,4),floord(2*t1+Ny-3,4)),floord(4*t2+Ny-9,4));t3++) {
for (t4=max(max(ceild(t1-1020,1024),ceild(4*t2-Nz-2035,2048)),ceild(4*t3-Ny-2035,2048));t4<=min(min(min(floord(4*Nt+Nx-9,2048),floord(2*t1+Nx-3,2048)),floord(4*t2+Nx-9,2048)),floord(4*t3+Nx-9,2048));t4++) {
for (t5=max(max(max(ceild(t1,2),ceild(4*t2-Nz+5,4)),ceild(4*t3-Ny+5,4)),ceild(2048*t4-Nx+5,4));t5<=floord(t1+1,2);t5++) {
for (t6=max(4*t2,-4*t1+4*t2+8*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+8*t5),4*t5+Nz-5);t6++) {
for (t7=4*t3;t7<=min(4*t3+3,4*t5+Ny-5);t7++) {
lbv=max(2048*t4,4*t5+4);
ubv=min(2048*t4+2047,4*t5+Nx-5);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));;
}
}
}
}
}
}
}
}
}
/* End of CLooG code */
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "variable axis-symmetric")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<13;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
GB_binop__gt_uint32.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__gt_uint32)
// A.*B function (eWiseMult): GB (_AemultB_08__gt_uint32)
// A.*B function (eWiseMult): GB (_AemultB_02__gt_uint32)
// A.*B function (eWiseMult): GB (_AemultB_04__gt_uint32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__gt_uint32)
// A*D function (colscale): GB (_AxD__gt_uint32)
// D*A function (rowscale): GB (_DxB__gt_uint32)
// C+=B function (dense accum): GB (_Cdense_accumB__gt_uint32)
// C+=b function (dense accum): GB (_Cdense_accumb__gt_uint32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__gt_uint32)
// C=scalar+B GB (_bind1st__gt_uint32)
// C=scalar+B' GB (_bind1st_tran__gt_uint32)
// C=A+scalar GB (_bind2nd__gt_uint32)
// C=A'+scalar GB (_bind2nd_tran__gt_uint32)
// C type: bool
// A type: uint32_t
// A pattern? 0
// B type: uint32_t
// B pattern? 0
// BinaryOp: cij = (aij > bij)
#define GB_ATYPE \
uint32_t
#define GB_BTYPE \
uint32_t
#define GB_CTYPE \
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) \
uint32_t aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint32_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
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_GT || GxB_NO_UINT32 || GxB_NO_GT_UINT32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__gt_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__gt_uint32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#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__gt_uint32)
(
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 uint32_t
uint32_t bwork = (*((uint32_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__gt_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
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__gt_uint32)
(
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__gt_uint32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
uint32_t alpha_scalar ;
uint32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint32_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__gt_uint32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__gt_uint32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__gt_uint32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__gt_uint32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__gt_uint32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *Cx = (bool *) Cx_output ;
uint32_t x = (*((uint32_t *) x_input)) ;
uint32_t *Bx = (uint32_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint32_t bij = GBX (Bx, p, false) ;
Cx [p] = (x > bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__gt_uint32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
bool *Cx = (bool *) Cx_output ;
uint32_t *Ax = (uint32_t *) Ax_input ;
uint32_t y = (*((uint32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint32_t aij = GBX (Ax, p, false) ;
Cx [p] = (aij > y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x > aij) ; \
}
GrB_Info GB (_bind1st_tran__gt_uint32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t x = (*((const uint32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij > y) ; \
}
GrB_Info GB (_bind2nd_tran__gt_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t y = (*((const uint32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
ten_tusscher_2004_epi_S2_17.c | //Original Ten Tusscher
#include <assert.h>
#include <stdlib.h>
#include "ten_tusscher_2004_epi_S2_17.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.5285006584511,0.00130106729313035,0.778730090563051,0.778532170509002,0.000175864034699588,0.484676327494511,0.00294864118836231,0.999998334805594,1.94635926887894e-08,1.90111810990968e-05,0.999770708859905,1.00748136518757,0.999998809936904,3.60224813237435e-05,1.18254991511234,9.21308723760909,140.066635187809};
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.7219011711698,0.000373800660274715,0.000150569617335446,0.000654485626385041,0.257379206595380,0.173802542474158,0.132458241657246,3.93296187661537,0.0158924919170214,2.50168625879054,1095.95864752453,0.000511327811652900,0.243193135425503,0.0192821673745436,0.00636346797017134,9.00104876078144e-06};
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;
}
|
oskar_dftw_m2m_3d_omp.c | /*
* Copyright (c) 2013-2017, The University of Oxford
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Oxford nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "math/oskar_dftw_m2m_3d_omp.h"
#include <math.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Single precision. */
void oskar_dftw_m2m_3d_omp_f(const int n_in, const float wavenumber,
const float* x_in, const float* y_in, const float* z_in,
const float2* weights_in, const int n_out, const float* x_out,
const float* y_out, const float* z_out, const float4c* data,
float4c* output)
{
int i_out = 0;
/* Loop over output points. */
#pragma omp parallel for private(i_out)
for (i_out = 0; i_out < n_out; ++i_out)
{
int i;
float xp_out, yp_out, zp_out;
float4c out;
/* Clear output value. */
out.a.x = 0.0f;
out.a.y = 0.0f;
out.b.x = 0.0f;
out.b.y = 0.0f;
out.c.x = 0.0f;
out.c.y = 0.0f;
out.d.x = 0.0f;
out.d.y = 0.0f;
/* Get the output position. */
xp_out = wavenumber * x_out[i_out];
yp_out = wavenumber * y_out[i_out];
zp_out = wavenumber * z_out[i_out];
/* Loop over input points. */
for (i = 0; i < n_in; ++i)
{
float2 weight;
/* Calculate the DFT phase for the output position. */
{
float t;
float2 w;
/* Phase. */
t = xp_out * x_in[i] + yp_out * y_in[i] + zp_out * z_in[i];
weight.x = cosf(t);
weight.y = sinf(t);
/* Multiply the supplied DFT weight by the computed phase. */
w = weights_in[i];
t = weight.x; /* Copy the real part. */
weight.x *= w.x;
weight.x -= w.y * weight.y;
weight.y *= w.x;
weight.y += w.y * t;
}
/* Complex multiply-accumulate input signal and weight. */
{
float4c in;
in = data[i * n_out + i_out];
out.a.x += in.a.x * weight.x;
out.a.x -= in.a.y * weight.y;
out.a.y += in.a.y * weight.x;
out.a.y += in.a.x * weight.y;
out.b.x += in.b.x * weight.x;
out.b.x -= in.b.y * weight.y;
out.b.y += in.b.y * weight.x;
out.b.y += in.b.x * weight.y;
out.c.x += in.c.x * weight.x;
out.c.x -= in.c.y * weight.y;
out.c.y += in.c.y * weight.x;
out.c.y += in.c.x * weight.y;
out.d.x += in.d.x * weight.x;
out.d.x -= in.d.y * weight.y;
out.d.y += in.d.y * weight.x;
out.d.y += in.d.x * weight.y;
}
}
/* Store the output point. */
output[i_out] = out;
}
}
/* Double precision. */
void oskar_dftw_m2m_3d_omp_d(const int n_in, const double wavenumber,
const double* x_in, const double* y_in, const double* z_in,
const double2* weights_in, const int n_out, const double* x_out,
const double* y_out, const double* z_out, const double4c* data,
double4c* output)
{
int i_out = 0;
/* Loop over output points. */
#pragma omp parallel for private(i_out)
for (i_out = 0; i_out < n_out; ++i_out)
{
int i;
double xp_out, yp_out, zp_out;
double4c out;
/* Clear output value. */
out.a.x = 0.0;
out.a.y = 0.0;
out.b.x = 0.0;
out.b.y = 0.0;
out.c.x = 0.0;
out.c.y = 0.0;
out.d.x = 0.0;
out.d.y = 0.0;
/* Get the output position. */
xp_out = wavenumber * x_out[i_out];
yp_out = wavenumber * y_out[i_out];
zp_out = wavenumber * z_out[i_out];
/* Loop over input points. */
for (i = 0; i < n_in; ++i)
{
double2 weight;
/* Calculate the DFT phase for the output position. */
{
double t;
double2 w;
/* Phase. */
t = xp_out * x_in[i] + yp_out * y_in[i] + zp_out * z_in[i];
weight.x = cos(t);
weight.y = sin(t);
/* Multiply the supplied DFT weight by the computed phase. */
w = weights_in[i];
t = weight.x; /* Copy the real part. */
weight.x *= w.x;
weight.x -= w.y * weight.y;
weight.y *= w.x;
weight.y += w.y * t;
}
/* Complex multiply-accumulate input signal and weight. */
{
double4c in;
in = data[i * n_out + i_out];
out.a.x += in.a.x * weight.x;
out.a.x -= in.a.y * weight.y;
out.a.y += in.a.y * weight.x;
out.a.y += in.a.x * weight.y;
out.b.x += in.b.x * weight.x;
out.b.x -= in.b.y * weight.y;
out.b.y += in.b.y * weight.x;
out.b.y += in.b.x * weight.y;
out.c.x += in.c.x * weight.x;
out.c.x -= in.c.y * weight.y;
out.c.y += in.c.y * weight.x;
out.c.y += in.c.x * weight.y;
out.d.x += in.d.x * weight.x;
out.d.x -= in.d.y * weight.y;
out.d.y += in.d.y * weight.x;
out.d.y += in.d.x * weight.y;
}
}
/* Store the output point. */
output[i_out] = out;
}
}
#ifdef __cplusplus
}
#endif
|
GB_unaryop__abs_uint16_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__abs_uint16_int16
// op(A') function: GB_tran__abs_uint16_int16
// C type: uint16_t
// A type: int16_t
// cast: uint16_t cij = (uint16_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int16_t
#define GB_CTYPE \
uint16_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) \
uint16_t z = (uint16_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_ABS || GxB_NO_UINT16 || GxB_NO_INT16)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_uint16_int16
(
uint16_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__abs_uint16_int16
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_binop__islt_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 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__islt_fp64)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__islt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_03__islt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__islt_fp64)
// A*D function (colscale): GB (_AxD__islt_fp64)
// D*A function (rowscale): GB (_DxB__islt_fp64)
// C+=B function (dense accum): GB (_Cdense_accumB__islt_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__islt_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__islt_fp64)
// C=scalar+B GB (_bind1st__islt_fp64)
// C=scalar+B' GB (_bind1st_tran__islt_fp64)
// C=A+scalar GB (_bind2nd__islt_fp64)
// C=A'+scalar GB (_bind2nd_tran__islt_fp64)
// C type: double
// A type: double
// B,b type: double
// BinaryOp: cij = (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) \
double aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
double bij = Bx [pB]
// 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) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y, i, j) \
z = (x < y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ISLT || GxB_NO_FP64 || GxB_NO_ISLT_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__islt_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__islt_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__islt_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
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__islt_fp64)
(
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_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__islt_fp64)
(
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_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__islt_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__islt_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__islt_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__islt_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__islt_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__islt_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 anz,
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 < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
double 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__islt_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 = 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) \
{ \
double aij = Ax [pA] ; \
Cx [pC] = (x < aij) ; \
}
GrB_Info GB (_bind1st_tran__islt_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 = Ax [pA] ; \
Cx [pC] = (aij < y) ; \
}
GrB_Info GB (_bind2nd_tran__islt_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
|
ffindex_unpack.c | /*
* FFindex
* written by Andreas Hauser <andy@splashground.de>.
* Please add your name here if you distribute modified versions.
*
* FFindex is provided under the Create Commons license "Attribution-ShareAlike
* 3.0", which basically captures the spirit of the Gnu Public License (GPL).
*
* See:
* http://creativecommons.org/licenses/by-sa/3.0/
*
* ffindex_apply
* apply a program to each FFindex entry
*/
#define _GNU_SOURCE 1
#define _LARGEFILE64_SOURCE 1
#define _FILE_OFFSET_BITS 64
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "ffindex.h"
#include "ffutil.h"
int main(int argn, char **argv)
{
if(argn < 4)
{
fprintf(stderr, "USAGE: %s DATA_FILENAME INDEX_FILENAME OUT_DIR\n"
FFINDEX_COPYRIGHT,
argv[0]);
return -1;
}
char *data_filename = argv[1];
char *index_filename = argv[2];
char *out_dir = argv[3];
FILE *data_file = fopen(data_filename, "r");
FILE *index_file = fopen(index_filename, "r");
if( data_file == NULL) { fferror_print(__FILE__, __LINE__, argv[0], data_filename); exit(EXIT_FAILURE); }
if(index_file == NULL) { fferror_print(__FILE__, __LINE__, argv[0], index_filename); exit(EXIT_FAILURE); }
size_t data_size;
char *data = ffindex_mmap_data(data_file, &data_size);
ffindex_index_t* index = ffindex_index_parse(index_file, 0);
if(index == NULL)
{
fferror_print(__FILE__, __LINE__, "ffindex_index_parse", index_filename);
exit(EXIT_FAILURE);
}
if(chdir(out_dir) < 0){ fferror_print(__FILE__, __LINE__, argv[0], out_dir); exit(EXIT_FAILURE); }
size_t range_start = 0;
size_t range_end = index->n_entries;
// Foreach entry
//#pragma omp parallel for
for(size_t entry_index = range_start; entry_index < range_end; entry_index++)
{
//fprintf(stderr, "index %ld\n", entry_index);
ffindex_entry_t* entry = ffindex_get_entry_by_index(index, entry_index);
if(entry == NULL) { perror(entry->name); continue; }
FILE *output_file = fopen(entry->name, "w");
// Write file data to child's stdin.
char *filedata = ffindex_get_data_by_entry(data, entry);
size_t written = fwrite(filedata, entry->length - 1, 1, output_file);
if(written < 1) { perror(entry->name); break; }
fclose(output_file);
}
return 0;
}
/* vim: ts=2 sw=2 et
*/
|
psd.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP SSSSS DDDD %
% P P SS D D %
% PPPP SSS D D %
% P SS D D %
% P SSSSS DDDD %
% %
% %
% Read/Write Adobe Photoshop Image Format %
% %
% Software Design %
% Cristy %
% Leonard Rosenthol %
% July 1992 %
% Dirk Lemstra %
% December 2013 %
% %
% %
% Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Photoshop spec @ https://www.adobe.com/devnet-apps/photoshop/fileformatashtml
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/channel.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/policy.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/registry.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "coders/coders-private.h"
#ifdef MAGICKCORE_ZLIB_DELEGATE
#include <zlib.h>
#endif
#include "psd-private.h"
/*
Define declaractions.
*/
#define MaxPSDChannels 56
#define PSDQuantum(x) (((ssize_t) (x)+1) & -2)
/*
Enumerated declaractions.
*/
typedef enum
{
Raw = 0,
RLE = 1,
ZipWithoutPrediction = 2,
ZipWithPrediction = 3
} PSDCompressionType;
typedef enum
{
BitmapMode = 0,
GrayscaleMode = 1,
IndexedMode = 2,
RGBMode = 3,
CMYKMode = 4,
MultichannelMode = 7,
DuotoneMode = 8,
LabMode = 9
} PSDImageType;
/*
Typedef declaractions.
*/
typedef struct _ChannelInfo
{
short
type;
size_t
size;
} ChannelInfo;
typedef struct _MaskInfo
{
Image
*image;
RectangleInfo
page;
unsigned char
background,
flags;
} MaskInfo;
typedef struct _LayerInfo
{
ChannelInfo
channel_info[MaxPSDChannels];
char
blendkey[4];
Image
*image;
MaskInfo
mask;
Quantum
opacity;
RectangleInfo
page;
size_t
offset_x,
offset_y;
unsigned char
clipping,
flags,
name[257],
visible;
unsigned short
channels;
StringInfo
*info;
} LayerInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s P S D %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsPSD()() returns MagickTrue if the image format type, identified by the
% magick string, is PSD.
%
% The format of the IsPSD method is:
%
% MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"8BPS",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadPSDImage() reads an Adobe Photoshop image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadPSDImage method is:
%
% Image *ReadPSDImage(image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static const char *CompositeOperatorToPSDBlendMode(Image *image)
{
switch (image->compose)
{
case ColorBurnCompositeOp:
return(image->endian == LSBEndian ? "vidi" : "idiv");
case ColorDodgeCompositeOp:
return(image->endian == LSBEndian ? " vid" : "div ");
case ColorizeCompositeOp:
return(image->endian == LSBEndian ? "rloc" : "colr");
case DarkenCompositeOp:
return(image->endian == LSBEndian ? "krad" : "dark");
case DifferenceCompositeOp:
return(image->endian == LSBEndian ? "ffid" : "diff");
case DissolveCompositeOp:
return(image->endian == LSBEndian ? "ssid" : "diss");
case ExclusionCompositeOp:
return(image->endian == LSBEndian ? "dums" : "smud");
case HardLightCompositeOp:
return(image->endian == LSBEndian ? "tiLh" : "hLit");
case HardMixCompositeOp:
return(image->endian == LSBEndian ? "xiMh" : "hMix");
case HueCompositeOp:
return(image->endian == LSBEndian ? " euh" : "hue ");
case LightenCompositeOp:
return(image->endian == LSBEndian ? "etil" : "lite");
case LinearBurnCompositeOp:
return(image->endian == LSBEndian ? "nrbl" : "lbrn");
case LinearDodgeCompositeOp:
return(image->endian == LSBEndian ? "gddl" : "lddg");
case LinearLightCompositeOp:
return(image->endian == LSBEndian ? "tiLl" : "lLit");
case LuminizeCompositeOp:
return(image->endian == LSBEndian ? " mul" : "lum ");
case MultiplyCompositeOp:
return(image->endian == LSBEndian ? " lum" : "mul ");
case OverlayCompositeOp:
return(image->endian == LSBEndian ? "revo" : "over");
case PinLightCompositeOp:
return(image->endian == LSBEndian ? "tiLp" : "pLit");
case SaturateCompositeOp:
return(image->endian == LSBEndian ? " tas" : "sat ");
case ScreenCompositeOp:
return(image->endian == LSBEndian ? "nrcs" : "scrn");
case SoftLightCompositeOp:
return(image->endian == LSBEndian ? "tiLs" : "sLit");
case VividLightCompositeOp:
return(image->endian == LSBEndian ? "tiLv" : "vLit");
case OverCompositeOp:
default:
return(image->endian == LSBEndian ? "mron" : "norm");
}
}
/*
For some reason Photoshop seems to blend semi-transparent pixels with white.
This method reverts the blending. This can be disabled by setting the
option 'psd:alpha-unblend' to off.
*/
static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info,
Image *image,ExceptionInfo* exception)
{
const char
*option;
MagickBooleanType
status;
ssize_t
y;
if ((image->alpha_trait != BlendPixelTrait) ||
(image->colorspace != sRGBColorspace))
return(MagickTrue);
option=GetImageOption(image_info,"psd:alpha-unblend");
if (IsStringFalse(option) != MagickFalse)
return(MagickTrue);
status=MagickTrue;
#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++)
{
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
ssize_t
i;
gamma=QuantumScale*GetPixelAlpha(image, q);
if (gamma != 0.0 && gamma != 1.0)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
if (channel != AlphaPixelChannel)
q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static inline CompressionType ConvertPSDCompression(
PSDCompressionType compression)
{
switch (compression)
{
case RLE:
return RLECompression;
case ZipWithPrediction:
case ZipWithoutPrediction:
return ZipCompression;
default:
return NoCompression;
}
}
static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity,
MagickBooleanType revert,ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying layer opacity %.20g", (double) opacity);
if (opacity == OpaqueAlpha)
return(MagickTrue);
if (image->alpha_trait != BlendPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
status=MagickTrue;
#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++)
{
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (revert == MagickFalse)
SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))*
opacity),q);
else if (opacity > 0)
SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/
(MagickRealType) opacity)),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask,
Quantum background,MagickBooleanType revert,ExceptionInfo *exception)
{
Image
*complete_mask;
MagickBooleanType
status;
PixelInfo
color;
ssize_t
y;
if (image->alpha_trait == UndefinedPixelTrait)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" applying opacity mask");
complete_mask=CloneImage(image,0,0,MagickTrue,exception);
if (complete_mask == (Image *) NULL)
return(MagickFalse);
complete_mask->alpha_trait=BlendPixelTrait;
GetPixelInfo(complete_mask,&color);
color.red=(MagickRealType) background;
(void) SetImageColor(complete_mask,&color,exception);
status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue,
mask->page.x-image->page.x,mask->page.y-image->page.y,exception);
if (status == MagickFalse)
{
complete_mask=DestroyImage(complete_mask);
return(status);
}
#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++)
{
Quantum
*magick_restrict q;
Quantum
*p;
ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception);
if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
alpha,
intensity;
alpha=(MagickRealType) GetPixelAlpha(image,q);
intensity=GetPixelIntensity(complete_mask,p);
if (revert == MagickFalse)
SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q);
else if (intensity > 0)
SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q);
q+=GetPixelChannels(image);
p+=GetPixelChannels(complete_mask);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
status=MagickFalse;
}
complete_mask=DestroyImage(complete_mask);
return(status);
}
static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info,
ExceptionInfo *exception)
{
char
*key;
RandomInfo
*random_info;
StringInfo
*key_info;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" preserving opacity mask");
random_info=AcquireRandomInfo();
key_info=GetRandomKey(random_info,2+1);
key=(char *) GetStringInfoDatum(key_info);
key[8]=(char) layer_info->mask.background;
key[9]='\0';
layer_info->mask.image->page.x+=layer_info->page.x;
layer_info->mask.image->page.y+=layer_info->page.y;
(void) SetImageRegistry(ImageRegistryType,(const char *) key,
layer_info->mask.image,exception);
(void) SetImageArtifact(layer_info->image,"psd:opacity-mask",
(const char *) key);
key_info=DestroyStringInfo(key_info);
random_info=DestroyRandomInfo(random_info);
}
static ssize_t DecodePSDPixels(const size_t number_compact_pixels,
const unsigned char *compact_pixels,const ssize_t depth,
const size_t number_pixels,unsigned char *pixels)
{
#define CheckNumberCompactPixels \
if (packets == 0) \
return(i); \
packets--
#define CheckNumberPixels(count) \
if (((ssize_t) i + count) > (ssize_t) number_pixels) \
return(i); \
i+=count
int
pixel;
ssize_t
i,
j;
size_t
length;
ssize_t
packets;
packets=(ssize_t) number_compact_pixels;
for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); )
{
packets--;
length=(size_t) (*compact_pixels++);
if (length == 128)
continue;
if (length > 128)
{
length=256-length+1;
CheckNumberCompactPixels;
pixel=(*compact_pixels++);
for (j=0; j < (ssize_t) length; j++)
{
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(pixel >> 7) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 6) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 5) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 4) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 3) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 2) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 1) & 0x01 ? 0U : 255U;
*pixels++=(pixel >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(unsigned char) ((pixel >> 6) & 0x03);
*pixels++=(unsigned char) ((pixel >> 4) & 0x03);
*pixels++=(unsigned char) ((pixel >> 2) & 0x03);
*pixels++=(unsigned char) ((pixel & 0x03) & 0x03);
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(unsigned char) ((pixel >> 4) & 0xff);
*pixels++=(unsigned char) ((pixel & 0x0f) & 0xff);
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(unsigned char) pixel;
break;
}
}
}
continue;
}
length++;
for (j=0; j < (ssize_t) length; j++)
{
CheckNumberCompactPixels;
switch (depth)
{
case 1:
{
CheckNumberPixels(8);
*pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U;
*pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U;
break;
}
case 2:
{
CheckNumberPixels(4);
*pixels++=(*compact_pixels >> 6) & 0x03;
*pixels++=(*compact_pixels >> 4) & 0x03;
*pixels++=(*compact_pixels >> 2) & 0x03;
*pixels++=(*compact_pixels & 0x03) & 0x03;
break;
}
case 4:
{
CheckNumberPixels(2);
*pixels++=(*compact_pixels >> 4) & 0xff;
*pixels++=(*compact_pixels & 0x0f) & 0xff;
break;
}
default:
{
CheckNumberPixels(1);
*pixels++=(*compact_pixels);
break;
}
}
compact_pixels++;
}
}
return(i);
}
static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info,
const ssize_t number_layers)
{
ssize_t
i;
for (i=0; i<number_layers; i++)
{
if (layer_info[i].image != (Image *) NULL)
layer_info[i].image=DestroyImage(layer_info[i].image);
if (layer_info[i].mask.image != (Image *) NULL)
layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image);
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
return (LayerInfo *) RelinquishMagickMemory(layer_info);
}
static inline size_t GetPSDPacketSize(const Image *image)
{
if (image->storage_class == PseudoClass)
{
if (image->colors > 256)
return(2);
}
if (image->depth > 16)
return(4);
if (image->depth > 8)
return(2);
return(1);
}
static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image)
{
if (psd_info->version == 1)
return((MagickSizeType) ReadBlobLong(image));
return((MagickSizeType) ReadBlobLongLong(image));
}
static inline size_t GetPSDRowSize(Image *image)
{
if (image->depth == 1)
return(((image->columns+7)/8)*GetPSDPacketSize(image));
else
return(image->columns*GetPSDPacketSize(image));
}
static const char *ModeToString(PSDImageType type)
{
switch (type)
{
case BitmapMode: return "Bitmap";
case GrayscaleMode: return "Grayscale";
case IndexedMode: return "Indexed";
case RGBMode: return "RGB";
case CMYKMode: return "CMYK";
case MultichannelMode: return "Multichannel";
case DuotoneMode: return "Duotone";
case LabMode: return "L*A*B";
default: return "unknown";
}
}
static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception)
{
ChannelType
channel_mask;
MagickBooleanType
status;
channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~
AlphaChannel));
status=NegateImage(image,MagickFalse,exception);
(void) SetImageChannelMask(image,channel_mask);
return(status);
}
static StringInfo *ParseImageResourceBlocks(PSDInfo *psd_info,Image *image,
const unsigned char *blocks,size_t length)
{
const unsigned char
*p;
ssize_t
offset;
StringInfo
*profile;
unsigned char
name_length;
unsigned int
count;
unsigned short
id,
short_sans;
if (length < 16)
return((StringInfo *) NULL);
profile=BlobToStringInfo((const unsigned char *) NULL,length);
SetStringInfoDatum(profile,blocks);
SetStringInfoName(profile,"8bim");
for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); )
{
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p+=4;
p=PushShortPixel(MSBEndian,p,&id);
p=PushCharPixel(p,&name_length);
if ((name_length % 2) == 0)
name_length++;
p+=name_length;
if (p > (blocks+length-4))
break;
p=PushLongPixel(MSBEndian,p,&count);
offset=(ssize_t) count;
if (((p+offset) < blocks) || ((p+offset) > (blocks+length)))
break;
switch (id)
{
case 0x03ed:
{
unsigned short
resolution;
/*
Resolution info.
*/
if (offset < 16)
break;
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.x=(double) resolution;
(void) FormatImageProperty(image,"tiff:XResolution","%*g",
GetMagickPrecision(),image->resolution.x);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.y=(double) resolution;
(void) FormatImageProperty(image,"tiff:YResolution","%*g",
GetMagickPrecision(),image->resolution.y);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
image->units=PixelsPerInchResolution;
break;
}
case 0x0421:
{
if ((offset > 4) && (*(p+4) == 0))
psd_info->has_merged_image=MagickFalse;
p+=offset;
break;
}
default:
{
p+=offset;
break;
}
}
if ((offset & 0x01) != 0)
p++;
}
return(profile);
}
static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode)
{
if (mode == (const char *) NULL)
return(OverCompositeOp);
if (LocaleNCompare(mode,"norm",4) == 0)
return(OverCompositeOp);
if (LocaleNCompare(mode,"mul ",4) == 0)
return(MultiplyCompositeOp);
if (LocaleNCompare(mode,"diss",4) == 0)
return(DissolveCompositeOp);
if (LocaleNCompare(mode,"diff",4) == 0)
return(DifferenceCompositeOp);
if (LocaleNCompare(mode,"dark",4) == 0)
return(DarkenCompositeOp);
if (LocaleNCompare(mode,"lite",4) == 0)
return(LightenCompositeOp);
if (LocaleNCompare(mode,"hue ",4) == 0)
return(HueCompositeOp);
if (LocaleNCompare(mode,"sat ",4) == 0)
return(SaturateCompositeOp);
if (LocaleNCompare(mode,"colr",4) == 0)
return(ColorizeCompositeOp);
if (LocaleNCompare(mode,"lum ",4) == 0)
return(LuminizeCompositeOp);
if (LocaleNCompare(mode,"scrn",4) == 0)
return(ScreenCompositeOp);
if (LocaleNCompare(mode,"over",4) == 0)
return(OverlayCompositeOp);
if (LocaleNCompare(mode,"hLit",4) == 0)
return(HardLightCompositeOp);
if (LocaleNCompare(mode,"sLit",4) == 0)
return(SoftLightCompositeOp);
if (LocaleNCompare(mode,"smud",4) == 0)
return(ExclusionCompositeOp);
if (LocaleNCompare(mode,"div ",4) == 0)
return(ColorDodgeCompositeOp);
if (LocaleNCompare(mode,"idiv",4) == 0)
return(ColorBurnCompositeOp);
if (LocaleNCompare(mode,"lbrn",4) == 0)
return(LinearBurnCompositeOp);
if (LocaleNCompare(mode,"lddg",4) == 0)
return(LinearDodgeCompositeOp);
if (LocaleNCompare(mode,"lLit",4) == 0)
return(LinearLightCompositeOp);
if (LocaleNCompare(mode,"vLit",4) == 0)
return(VividLightCompositeOp);
if (LocaleNCompare(mode,"pLit",4) == 0)
return(PinLightCompositeOp);
if (LocaleNCompare(mode,"hMix",4) == 0)
return(HardMixCompositeOp);
return(OverCompositeOp);
}
static inline ssize_t ReadPSDString(Image *image,char *p,const size_t length)
{
ssize_t
count;
count=ReadBlob(image,length,(unsigned char *) p);
if ((count == (ssize_t) length) && (image->endian != MSBEndian))
{
char
*q;
q=p+length;
for(--q; p < q; ++p, --q)
{
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}
}
return(count);
}
static inline void SetPSDPixel(Image *image,const size_t channels,
const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q,
ExceptionInfo *exception)
{
if (image->storage_class == PseudoClass)
{
PixelInfo
*color;
Quantum
index;
index=pixel;
if (packet_size == 1)
index=(Quantum) ScaleQuantumToChar(index);
index=(Quantum) ConstrainColormapIndex(image,(ssize_t) index,
exception);
if (type == 0)
SetPixelIndex(image,index,q);
if ((type == 0) && (channels > 1))
return;
color=image->colormap+(ssize_t) GetPixelIndex(image,q);
if (type != 0)
color->alpha=(MagickRealType) pixel;
SetPixelViaPixelInfo(image,color,q);
return;
}
switch (type)
{
case -1:
{
SetPixelAlpha(image,pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
break;
}
case -3:
case 1:
{
SetPixelGreen(image,pixel,q);
break;
}
case -4:
case 2:
{
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
}
}
static MagickBooleanType ReadPSDChannelPixels(Image *image,
const size_t channels,const ssize_t row,const ssize_t type,
const unsigned char *pixels,ExceptionInfo *exception)
{
Quantum
pixel;
const unsigned char
*p;
Quantum
*q;
ssize_t
x;
size_t
packet_size;
p=pixels;
q=GetAuthenticPixels(image,0,row,image->columns,1,exception);
if (q == (Quantum *) NULL)
return MagickFalse;
packet_size=GetPSDPacketSize(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (packet_size == 1)
pixel=ScaleCharToQuantum(*p++);
else
if (packet_size == 2)
{
unsigned short
nibble;
p=PushShortPixel(MSBEndian,p,&nibble);
pixel=ScaleShortToQuantum(nibble);
}
else
{
MagickFloatType
nibble;
p=PushFloatPixel(MSBEndian,p,&nibble);
pixel=ClampToQuantum((MagickRealType) (QuantumRange*nibble));
}
if (image->depth > 1)
{
SetPSDPixel(image,channels,type,packet_size,pixel,q,exception);
q+=GetPixelChannels(image);
}
else
{
ssize_t
bit,
number_bits;
number_bits=(ssize_t) image->columns-x;
if (number_bits > 8)
number_bits=8;
for (bit = 0; bit < (ssize_t) number_bits; bit++)
{
SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel)
& (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception);
q+=GetPixelChannels(image);
x++;
}
if (x != (ssize_t) image->columns)
x--;
continue;
}
}
return(SyncAuthenticPixels(image,exception));
}
static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels,
const ssize_t type,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
row_size;
ssize_t
count,
y;
unsigned char
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RAW");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
(void) memset(pixels,0,row_size*sizeof(*pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
static inline MagickOffsetType *ReadPSDRLESizes(Image *image,
const PSDInfo *psd_info,const size_t size)
{
MagickOffsetType
*sizes;
ssize_t
y;
sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes));
if(sizes != (MagickOffsetType *) NULL)
{
for (y=0; y < (ssize_t) size; y++)
{
if (psd_info->version == 1)
sizes[y]=(MagickOffsetType) ReadBlobShort(image);
else
sizes[y]=(MagickOffsetType) ReadBlobLong(image);
}
}
return sizes;
}
static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception)
{
MagickBooleanType
status;
size_t
length,
row_size;
ssize_t
count,
y;
unsigned char
*compact_pixels,
*pixels;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is RLE compressed");
row_size=GetPSDRowSize(image);
pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
if ((MagickOffsetType) length < sizes[y])
length=(size_t) sizes[y];
if (length > (row_size+2048)) /* arbitrary number */
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"InvalidLength",image->filename);
}
compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels));
if (compact_pixels == (unsigned char *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) memset(compact_pixels,0,length*sizeof(*compact_pixels));
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=MagickFalse;
count=ReadBlob(image,(size_t) sizes[y],compact_pixels);
if (count != (ssize_t) sizes[y])
break;
count=DecodePSDPixels((size_t) sizes[y],compact_pixels,
(ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels);
if (count != (ssize_t) row_size)
break;
status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels,
exception);
if (status == MagickFalse)
break;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
static void Unpredict8Bit(const Image *image,unsigned char *pixels,
const size_t count,const size_t row_size)
{
unsigned char
*p;
size_t
length,
remaining;
p=pixels;
remaining=count;
while (remaining > 0)
{
length=image->columns;
while (--length)
{
*(p+1)+=*p;
p++;
}
p++;
remaining-=row_size;
}
}
static void Unpredict16Bit(const Image *image,unsigned char *pixels,
const size_t count,const size_t row_size)
{
unsigned char
*p;
size_t
length,
remaining;
p=pixels;
remaining=count;
while (remaining > 0)
{
length=image->columns;
while (--length)
{
p[2]+=p[0]+((p[1]+p[3]) >> 8);
p[3]+=p[1];
p+=2;
}
p+=2;
remaining-=row_size;
}
}
static void Unpredict32Bit(const Image *image,unsigned char *pixels,
unsigned char *output_pixels,const size_t row_size)
{
unsigned char
*p,
*q;
ssize_t
y;
size_t
offset1,
offset2,
offset3,
remaining;
unsigned char
*start;
offset1=image->columns;
offset2=2*offset1;
offset3=3*offset1;
p=pixels;
q=output_pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
start=p;
remaining=row_size;
while (--remaining)
{
*(p+1)+=*p;
p++;
}
p=start;
remaining=image->columns;
while (remaining--)
{
*(q++)=*p;
*(q++)=*(p+offset1);
*(q++)=*(p+offset2);
*(q++)=*(p+offset3);
p++;
}
p=start+row_size;
}
}
static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,
const ssize_t type,const PSDCompressionType compression,
const size_t compact_size,ExceptionInfo *exception)
{
MagickBooleanType
status;
unsigned char
*p;
size_t
count,
packet_size,
row_size;
ssize_t
y;
unsigned char
*compact_pixels,
*pixels;
z_stream
stream;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is ZIP compressed");
if ((MagickSizeType) compact_size > GetBlobSize(image))
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size,
sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
packet_size=GetPSDPacketSize(image);
row_size=image->columns*packet_size;
count=image->rows*row_size;
pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
memset(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
stream.next_in=(Bytef *)compact_pixels;
stream.avail_in=(uInt) compact_size;
stream.next_out=(Bytef *)pixels;
stream.avail_out=(uInt) count;
if (inflateInit(&stream) == Z_OK)
{
int
ret;
while (stream.avail_out > 0)
{
ret=inflate(&stream,Z_SYNC_FLUSH);
if ((ret != Z_OK) && (ret != Z_STREAM_END))
{
(void) inflateEnd(&stream);
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(MagickFalse);
}
if (ret == Z_STREAM_END)
break;
}
(void) inflateEnd(&stream);
}
if (compression == ZipWithPrediction)
{
if (packet_size == 1)
Unpredict8Bit(image,pixels,count,row_size);
else if (packet_size == 2)
Unpredict16Bit(image,pixels,count,row_size);
else if (packet_size == 4)
{
unsigned char
*output_pixels;
output_pixels=(unsigned char *) AcquireQuantumMemory(count,
sizeof(*output_pixels));
if (pixels == (unsigned char *) NULL)
{
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,
"MemoryAllocationFailed",image->filename);
}
Unpredict32Bit(image,pixels,output_pixels,row_size);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
pixels=output_pixels;
}
}
status=MagickTrue;
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
status=ReadPSDChannelPixels(image,channels,y,type,p,exception);
if (status == MagickFalse)
break;
p+=row_size;
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return(status);
}
#endif
static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if ((layer_info->channel_info[channel].type < -1) &&
(layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0))
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
(void) SeekBlob(image,(MagickOffsetType)
layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
if (mask != (Image *) NULL)
{
(void) ResetImagePixels(mask,exception);
(void) SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
}
offset=TellBlob(image);
status=MagickFalse;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
(ssize_t) layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
(ssize_t) layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
(ssize_t) layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
(void) SeekBlob(image,offset+layer_info->channel_info[channel].size-2,
SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
(void) DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
if (mask != (Image *) NULL)
{
if (layer_info->mask.image != (Image *) NULL)
layer_info->mask.image=DestroyImage(layer_info->mask.image);
layer_info->mask.image=mask;
}
return(status);
}
static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info,
const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception)
{
char
message[MagickPathExtent];
MagickBooleanType
status;
PSDCompressionType
compression;
ssize_t
j;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" setting up new layer image");
if (psd_info->mode != IndexedMode)
(void) SetImageBackgroundColor(layer_info->image,exception);
layer_info->image->compose=PSDBlendModeToCompositeOperator(
layer_info->blendkey);
if (layer_info->visible == MagickFalse)
layer_info->image->compose=NoCompositeOp;
/*
Set up some hidden attributes for folks that need them.
*/
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.x);
(void) SetImageArtifact(layer_info->image,"psd:layer.x",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.y);
(void) SetImageArtifact(layer_info->image,"psd:layer.y",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double)
layer_info->opacity);
(void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message);
(void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name,
exception);
status=MagickTrue;
for (j=0; j < (ssize_t) layer_info->channels; j++)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for channel %.20g",(double) j);
compression=(PSDCompressionType) ReadBlobShort(layer_info->image);
layer_info->image->compression=ConvertPSDCompression(compression);
if (layer_info->channel_info[j].type == -1)
layer_info->image->alpha_trait=BlendPixelTrait;
status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,
(size_t) j,compression,exception);
if (status == MagickFalse)
break;
}
if (status != MagickFalse)
status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity,
MagickFalse,exception);
if ((status != MagickFalse) &&
(layer_info->image->colorspace == CMYKColorspace))
status=NegateCMYK(layer_info->image,exception);
if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL))
{
const char
*option;
layer_info->mask.image->page.x=layer_info->mask.page.x;
layer_info->mask.image->page.y=layer_info->mask.page.y;
/* Do not composite the mask when it is disabled */
if ((layer_info->mask.flags & 0x02) == 0x02)
layer_info->mask.image->compose=NoCompositeOp;
else
status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image,
layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse,
exception);
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if (IsStringTrue(option) != MagickFalse)
PreservePSDOpacityMask(image,layer_info,exception);
layer_info->mask.image=DestroyImage(layer_info->mask.image);
}
return(status);
}
static MagickBooleanType CheckPSDChannels(const PSDInfo *psd_info,
LayerInfo *layer_info)
{
int
channel_type;
ssize_t
i;
if (layer_info->channels < psd_info->min_channels)
return(MagickFalse);
channel_type=RedChannel;
if (psd_info->min_channels >= 3)
channel_type|=(GreenChannel | BlueChannel);
if (psd_info->min_channels >= 4)
channel_type|=BlackChannel;
for (i=0; i < (ssize_t) layer_info->channels; i++)
{
short
type;
type=layer_info->channel_info[i].type;
if ((i == 0) && (psd_info->mode == IndexedMode) && (type != 0))
return(MagickFalse);
if (type == -1)
{
channel_type|=AlphaChannel;
continue;
}
if (type < -1)
continue;
if (type == 0)
channel_type&=~RedChannel;
else if (type == 1)
channel_type&=~GreenChannel;
else if (type == 2)
channel_type&=~BlueChannel;
else if (type == 3)
channel_type&=~BlackChannel;
}
if (channel_type == 0)
return(MagickTrue);
if ((channel_type == AlphaChannel) &&
(layer_info->channels >= psd_info->min_channels + 1))
return(MagickTrue);
return(MagickFalse);
}
static void AttachPSDLayers(Image *image,LayerInfo *layer_info,
ssize_t number_layers)
{
ssize_t
i;
ssize_t
j;
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers == 0)
{
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
return;
}
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
static inline MagickBooleanType PSDSkipImage(const PSDInfo *psd_info,
const ImageInfo *image_info,const size_t index)
{
if (psd_info->has_merged_image == MagickFalse)
return(MagickFalse);
if (image_info->number_scenes == 0)
return(MagickFalse);
if (index < image_info->scene)
return(MagickTrue);
if (index > image_info->scene+image_info->number_scenes-1)
return(MagickTrue);
return(MagickFalse);
}
static void CheckMergedImageAlpha(const PSDInfo *psd_info,Image *image)
{
/*
The number of layers cannot be used to determine if the merged image
contains an alpha channel. So we enable it when we think we should.
*/
if (((psd_info->mode == GrayscaleMode) && (psd_info->channels > 1)) ||
((psd_info->mode == RGBMode) && (psd_info->channels > 3)) ||
((psd_info->mode == CMYKMode) && (psd_info->channels > 4)))
image->alpha_trait=BlendPixelTrait;
}
static void ParseAdditionalInfo(LayerInfo *layer_info)
{
char
key[5];
size_t
remaining_length;
unsigned char
*p;
unsigned int
size;
p=GetStringInfoDatum(layer_info->info);
remaining_length=GetStringInfoLength(layer_info->info);
while (remaining_length >= 12)
{
/* skip over signature */
p+=4;
key[0]=(char) (*p++);
key[1]=(char) (*p++);
key[2]=(char) (*p++);
key[3]=(char) (*p++);
key[4]='\0';
size=(unsigned int) (*p++) << 24;
size|=(unsigned int) (*p++) << 16;
size|=(unsigned int) (*p++) << 8;
size|=(unsigned int) (*p++);
size=size & 0xffffffff;
remaining_length-=12;
if ((size_t) size > remaining_length)
break;
if (LocaleNCompare(key,"luni",sizeof(key)) == 0)
{
unsigned char
*name;
unsigned int
length;
length=(unsigned int) (*p++) << 24;
length|=(unsigned int) (*p++) << 16;
length|=(unsigned int) (*p++) << 8;
length|=(unsigned int) (*p++);
if (length * 2 > size - 4)
break;
if (sizeof(layer_info->name) <= length)
break;
name=layer_info->name;
while (length > 0)
{
/* Only ASCII strings are supported */
if (*p++ != '\0')
break;
*name++=*p++;
length--;
}
if (length == 0)
*name='\0';
break;
}
else
p+=size;
remaining_length-=(size_t) size;
}
}
static MagickSizeType GetLayerInfoSize(const PSDInfo *psd_info,Image *image)
{
char
type[4];
MagickSizeType
size;
ssize_t
count;
size=GetPSDSize(psd_info,image);
if (size != 0)
return(size);
(void) ReadBlobLong(image);
count=ReadPSDString(image,type,4);
if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0))
return(0);
count=ReadPSDString(image,type,4);
if ((count == 4) && ((LocaleNCompare(type,"Mt16",4) == 0) ||
(LocaleNCompare(type,"Mt32",4) == 0) ||
(LocaleNCompare(type,"Mtrn",4) == 0)))
{
size=GetPSDSize(psd_info,image);
if (size != 0)
return(0);
image->alpha_trait=BlendPixelTrait;
count=ReadPSDString(image,type,4);
if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0))
return(0);
count=ReadPSDString(image,type,4);
}
if ((count == 4) && ((LocaleNCompare(type,"Lr16",4) == 0) ||
(LocaleNCompare(type,"Lr32",4) == 0)))
size=GetPSDSize(psd_info,image);
return(size);
}
static MagickBooleanType ReadPSDLayersInternal(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
ssize_t
i;
ssize_t
count,
index,
j,
number_layers;
size=GetLayerInfoSize(psd_info,image);
if (size == 0)
{
CheckMergedImageAlpha(psd_info,image);
return(MagickTrue);
}
layer_info=(LayerInfo *) NULL;
number_layers=(ssize_t) ReadBlobSignedShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->alpha_trait=BlendPixelTrait;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) memset(layer_info,0,(size_t) number_layers*sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
top,
left,
bottom,
right;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
top=(ssize_t) ReadBlobSignedLong(image);
left=(ssize_t) ReadBlobSignedLong(image);
bottom=(ssize_t) ReadBlobSignedLong(image);
right=(ssize_t) ReadBlobSignedLong(image);
if ((right < left) || (bottom < top))
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
layer_info[i].page.y=top;
layer_info[i].page.x=left;
layer_info[i].page.width=(size_t) (right-left);
layer_info[i].page.height=(size_t) (bottom-top);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
if ((layer_info[i].channel_info[j].type < -4) ||
(layer_info[i].channel_info[j].type > 4))
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"NoSuchImageChannel",
image->filename);
}
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
if (CheckPSDChannels(psd_info,&layer_info[i]) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
count=ReadPSDString(image,type,4);
if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
count=ReadPSDString(image,layer_info[i].blendkey,4);
if (count != 4)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=(ssize_t) ReadBlobSignedLong(image);
layer_info[i].mask.page.x=(ssize_t) ReadBlobSignedLong(image);
layer_info[i].mask.page.height=(size_t)
(ReadBlobSignedLong(image)-layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (
ReadBlobSignedLong(image)-layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double)
layer_info[i].mask.page.width,(double)
layer_info[i].mask.page.height,(double) ((MagickOffsetType)
length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
if (DiscardBlobBytes(image,length) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
/*
Layer name.
*/
length=(MagickSizeType) (unsigned char) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
if ((length % 4) != 0)
{
length=4-(length % 4);
combined_length+=length;
/* Skip over the padding of the layer name */
if (DiscardBlobBytes(image,length) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
length=(MagickSizeType) size-combined_length;
if (length > 0)
{
unsigned char
*info;
if (length > GetBlobSize(image))
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"InsufficientImageDataInFile",image->filename);
}
layer_info[i].info=AcquireStringInfo((const size_t) length);
info=GetStringInfoDatum(layer_info[i].info);
(void) ReadBlob(image,(const size_t) length,info);
ParseAdditionalInfo(&layer_info[i]);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
if (layer_info[i].info != (StringInfo *) NULL)
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
if (layer_info[i].info != (StringInfo *) NULL)
{
(void) SetImageProfile(layer_info[i].image,"psd:additional-info",
layer_info[i].info,exception);
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
}
if (image_info->ping != MagickFalse)
{
AttachPSDLayers(image,layer_info,number_layers);
return(MagickTrue);
}
status=MagickTrue;
index=0;
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].image == (Image *) NULL) ||
(PSDSkipImage(psd_info, image_info,++index) != MagickFalse))
{
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],
exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i,
(MagickSizeType) number_layers);
if (status == MagickFalse)
break;
}
if (status != MagickFalse)
AttachPSDLayers(image,layer_info,number_layers);
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
return(status);
}
ModuleExport MagickBooleanType ReadPSDLayers(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception)
{
PolicyDomain
domain;
PolicyRights
rights;
domain=CoderPolicyDomain;
rights=ReadPolicyRights;
if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse)
return(MagickTrue);
return(ReadPSDLayersInternal(image,image_info,psd_info,MagickFalse,
exception));
}
static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info,
Image *image,const PSDInfo *psd_info,ExceptionInfo *exception)
{
MagickOffsetType
*sizes;
MagickBooleanType
status;
PSDCompressionType
compression;
ssize_t
i;
if ((image_info->number_scenes != 0) && (image_info->scene != 0))
return(MagickTrue);
compression=(PSDCompressionType) ReadBlobMSBShort(image);
image->compression=ConvertPSDCompression(compression);
if (compression != Raw && compression != RLE)
{
(void) ThrowMagickException(exception,GetMagickModule(),
TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression);
return(MagickFalse);
}
sizes=(MagickOffsetType *) NULL;
if (compression == RLE)
{
sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
status=MagickTrue;
for (i=0; i < (ssize_t) psd_info->channels; i++)
{
ssize_t
type;
type=i;
if ((type == 1) && (psd_info->channels == 2))
type=-1;
if (compression == RLE)
status=ReadPSDChannelRLE(image,psd_info,type,sizes+(i*image->rows),
exception);
else
status=ReadPSDChannelRaw(image,psd_info->channels,type,exception);
if (status != MagickFalse)
status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i,
psd_info->channels);
if (status == MagickFalse)
break;
}
if ((status != MagickFalse) && (image->colorspace == CMYKColorspace))
status=NegateCMYK(image,exception);
if (status != MagickFalse)
status=CorrectPSDAlphaBlend(image_info,image,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
return(status);
}
static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
skip_layers;
MagickOffsetType
offset;
MagickSizeType
length;
MagickBooleanType
status;
PSDInfo
psd_info;
ssize_t
i;
size_t
image_list_length;
ssize_t
count;
StringInfo
*profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read image header.
*/
image->endian=MSBEndian;
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count != 4) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels < 1)
ThrowReaderException(CorruptImageError,"MissingImageChannel");
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) &&
(psd_info.depth != 16) && (psd_info.depth != 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if ((psd_info.mode == IndexedMode) && (psd_info.channels > 3))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
psd_info.min_channels=3;
switch (psd_info.mode)
{
case LabMode:
{
(void) SetImageColorspace(image,LabColorspace,exception);
break;
}
case CMYKMode:
{
psd_info.min_channels=4;
(void) SetImageColorspace(image,CMYKColorspace,exception);
break;
}
case BitmapMode:
case GrayscaleMode:
case DuotoneMode:
{
if (psd_info.depth != 32)
{
status=AcquireImageColormap(image,MagickMin((size_t)
(psd_info.depth < 16 ? 256 : 65536), MaxColormapSize),exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
}
psd_info.min_channels=1;
(void) SetImageColorspace(image,GRAYColorspace,exception);
break;
}
case IndexedMode:
{
psd_info.min_channels=1;
break;
}
case MultichannelMode:
{
if ((psd_info.channels > 0) && (psd_info.channels < 3))
{
psd_info.min_channels=psd_info.channels;
(void) SetImageColorspace(image,GRAYColorspace,exception);
}
break;
}
}
if (psd_info.channels < psd_info.min_channels)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if ((psd_info.mode == IndexedMode) && (length < 3))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if ((psd_info.mode == DuotoneMode) || (psd_info.depth == 32))
{
/*
Duotone image data; the format of this data is undocumented.
32 bits per pixel; the colormap is ignored.
*/
(void) SeekBlob(image,(const MagickOffsetType) length,SEEK_CUR);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=(size_t) length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(
(unsigned char) ReadBlobByte(image));
image->alpha_trait=UndefinedPixelTrait;
}
}
if ((image->depth == 1) && (image->storage_class != PseudoClass))
ThrowReaderException(CorruptImageError, "ImproperImageHeader");
psd_info.has_merged_image=MagickTrue;
profile=(StringInfo *) NULL;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
if (length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) || (length < 4) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
profile=ParseImageResourceBlocks(&psd_info,image,blocks,(size_t) length);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(psd_info.has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers,
exception) != MagickTrue)
{
if (profile != (StringInfo *) NULL)
profile=DestroyStringInfo(profile);
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
(void) SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (EOFBlob(image) != MagickFalse)
{
if (profile != (StringInfo *) NULL)
profile=DestroyStringInfo(profile);
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
if (image_info->ping != MagickFalse)
{
if (profile != (StringInfo *) NULL)
profile=DestroyStringInfo(profile);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
image_list_length=GetImageListLength(image);
if ((psd_info.has_merged_image != MagickFalse) || (image_list_length == 1))
psd_info.has_merged_image=(MagickBooleanType) ReadPSDMergedImage(
image_info,image,&psd_info,exception);
if ((psd_info.has_merged_image == MagickFalse) && (image_list_length == 1) &&
(length != 0))
{
(void) SeekBlob(image,offset,SEEK_SET);
status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse,
exception);
if (status != MagickTrue)
{
if (profile != (StringInfo *) NULL)
profile=DestroyStringInfo(profile);
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
image_list_length=GetImageListLength(image);
}
if (psd_info.has_merged_image == MagickFalse)
{
Image
*merged;
if (image_list_length == 1)
{
if (profile != (StringInfo *) NULL)
profile=DestroyStringInfo(profile);
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
}
image->background_color.alpha=(MagickRealType) TransparentAlpha;
image->background_color.alpha_trait=BlendPixelTrait;
(void) SetImageBackgroundColor(image,exception);
merged=MergeImageLayers(image,FlattenLayer,exception);
if (merged == (Image *) NULL)
{
(void) CloseBlob(image);
image=DestroyImageList(image);
return((Image *) NULL);
}
ReplaceImageInList(&image,merged);
}
if (profile != (StringInfo *) NULL)
{
Image
*next;
i=0;
next=image;
while (next != (Image *) NULL)
{
if (PSDSkipImage(&psd_info,image_info,i++) == MagickFalse)
(void) SetImageProfile(next,GetStringInfoName(profile),profile,
exception);
next=next->next;
}
profile=DestroyStringInfo(profile);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterPSDImage() adds properties for the PSD image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterPSDImage method is:
%
% size_t RegisterPSDImage(void)
%
*/
ModuleExport size_t RegisterPSDImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags|=CoderEncoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->flags|=CoderEncoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterPSDImage() removes format registrations made by the
% PSD module from the list of supported formats.
%
% The format of the UnregisterPSDImage method is:
%
% UnregisterPSDImage(void)
%
*/
ModuleExport void UnregisterPSDImage(void)
{
(void) UnregisterMagickInfo("PSB");
(void) UnregisterMagickInfo("PSD");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P S D I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePSDImage() writes an image in the Adobe Photoshop encoded image format.
%
% The format of the WritePSDImage method is:
%
% MagickBooleanType WritePSDImage(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.
%
*/
static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image,
const size_t offset)
{
if (psd_info->version == 1)
return(WriteBlobMSBShort(image,(unsigned short) offset));
return(WriteBlobMSBLong(image,(unsigned int) offset));
}
static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image,
const MagickSizeType size,const MagickOffsetType offset)
{
MagickOffsetType
current_offset;
ssize_t
result;
current_offset=TellBlob(image);
(void) SeekBlob(image,offset,SEEK_SET);
if (psd_info->version == 1)
result=WriteBlobMSBShort(image,(unsigned short) size);
else
result=WriteBlobMSBLong(image,(unsigned int) size);
(void) SeekBlob(image,current_offset,SEEK_SET);
return(result);
}
static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size)
{
if (psd_info->version == 1)
return(WriteBlobLong(image,(unsigned int) size));
return(WriteBlobLongLong(image,size));
}
static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image,
const MagickSizeType size,const MagickOffsetType offset)
{
MagickOffsetType
current_offset;
ssize_t
result;
current_offset=TellBlob(image);
(void) SeekBlob(image,offset,SEEK_SET);
result=SetPSDSize(psd_info,image,size);
(void) SeekBlob(image,current_offset,SEEK_SET);
return(result);
}
static size_t PSDPackbitsEncodeImage(Image *image,const size_t length,
const unsigned char *pixels,unsigned char *compact_pixels,
ExceptionInfo *exception)
{
int
count;
ssize_t
i,
j;
unsigned char
*q;
unsigned char
*packbits;
/*
Compress pixels with Packbits encoding.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (unsigned char *) NULL);
assert(compact_pixels != (unsigned char *) NULL);
packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits));
if (packbits == (unsigned char *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
q=compact_pixels;
for (i=(ssize_t) length; i != 0; )
{
switch (i)
{
case 1:
{
i--;
*q++=(unsigned char) 0;
*q++=(*pixels);
break;
}
case 2:
{
i-=2;
*q++=(unsigned char) 1;
*q++=(*pixels);
*q++=pixels[1];
break;
}
case 3:
{
i-=3;
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
*q++=(unsigned char) ((256-3)+1);
*q++=(*pixels);
break;
}
*q++=(unsigned char) 2;
*q++=(*pixels);
*q++=pixels[1];
*q++=pixels[2];
break;
}
default:
{
if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2)))
{
/*
Packed run.
*/
count=3;
while (((ssize_t) count < i) && (*pixels == *(pixels+count)))
{
count++;
if (count >= 127)
break;
}
i-=count;
*q++=(unsigned char) ((256-count)+1);
*q++=(*pixels);
pixels+=count;
break;
}
/*
Literal run.
*/
count=0;
while ((*(pixels+count) != *(pixels+count+1)) ||
(*(pixels+count+1) != *(pixels+count+2)))
{
packbits[count+1]=pixels[count];
count++;
if (((ssize_t) count >= (i-3)) || (count >= 127))
break;
}
i-=count;
*packbits=(unsigned char) (count-1);
for (j=0; j <= (ssize_t) count; j++)
*q++=packbits[j];
pixels+=count;
break;
}
}
}
*q++=(unsigned char) 128; /* EOD marker */
packbits=(unsigned char *) RelinquishMagickMemory(packbits);
return((size_t) (q-compact_pixels));
}
static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image,
const Image *next_image,const CompressionType compression,
const ssize_t channels)
{
size_t
length;
ssize_t
i,
y;
if (compression == RLECompression)
{
length=(size_t) WriteBlobShort(image,RLE);
for (i=0; i < channels; i++)
for (y=0; y < (ssize_t) next_image->rows; y++)
length+=SetPSDOffset(psd_info,image,0);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (compression == ZipCompression)
length=(size_t) WriteBlobShort(image,ZipWithoutPrediction);
#endif
else
length=(size_t) WriteBlobShort(image,Raw);
return(length);
}
static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
const CompressionType compression,ExceptionInfo *exception)
{
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
const Quantum
*p;
ssize_t
i;
size_t
count,
length;
ssize_t
y;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,compression,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,next_image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(
MagickMinBufferExtent,sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
memset(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) MagickMinBufferExtent;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) MagickMinBufferExtent-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
}
static unsigned char *AcquireCompactPixels(const Image *image,
ExceptionInfo *exception)
{
size_t
packet_size;
unsigned char
*compact_pixels;
packet_size=image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) AcquireQuantumMemory((9*
image->columns)+1,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
}
return(compact_pixels);
}
static size_t WritePSDChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
CompressionType
compression;
Image
*mask;
MagickOffsetType
rows_offset;
size_t
channels,
count,
length,
offset_length;
unsigned char
*compact_pixels;
count=0;
offset_length=0;
rows_offset=0;
compact_pixels=(unsigned char *) NULL;
compression=next_image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
if (compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(next_image,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
channels=1;
if (separate == MagickFalse)
{
if ((next_image->storage_class != PseudoClass) ||
(IsImageGray(next_image) != MagickFalse))
{
if (IsImageGray(next_image) == MagickFalse)
channels=(size_t) (next_image->colorspace == CMYKColorspace ? 4 :
3);
if (next_image->alpha_trait != UndefinedPixelTrait)
channels++;
}
rows_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,compression,
(ssize_t) channels);
offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));
}
size_offset+=2;
if ((next_image->storage_class == PseudoClass) &&
(IsImageGray(next_image) == MagickFalse))
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
IndexQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (IsImageGray(next_image) != MagickFalse)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
GrayQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
length=WritePSDChannel(psd_info,image_info,image,next_image,
RedQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
GreenQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlueQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
if (next_image->colorspace == CMYKColorspace)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlackQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
if (next_image->alpha_trait != UndefinedPixelTrait)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
AlphaQuantum,compact_pixels,rows_offset,separate,compression,
exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (separate != MagickFalse)
{
const char
*property;
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,
exception);
if (mask != (Image *) NULL)
{
if (compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(mask,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
length=WritePSDChannel(psd_info,image_info,image,mask,
RedQuantum,compact_pixels,rows_offset,MagickTrue,compression,
exception);
(void) WritePSDSize(psd_info,image,length,size_offset);
count+=length;
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
}
}
}
return(count);
}
static size_t WritePascalString(Image *image,const char *value,size_t padding)
{
size_t
count,
length;
ssize_t
i;
/*
Max length is 255.
*/
count=0;
length=(strlen(value) > 255UL ) ? 255UL : strlen(value);
if (length == 0)
count+=WriteBlobByte(image,0);
else
{
count+=WriteBlobByte(image,(unsigned char) length);
count+=WriteBlob(image,length,(const unsigned char *) value);
}
length++;
if ((length % padding) == 0)
return(count);
for (i=0; i < (ssize_t) (padding-(length % padding)); i++)
count+=WriteBlobByte(image,0);
return(count);
}
static void WriteResolutionResourceBlock(Image *image)
{
double
x_resolution,
y_resolution;
unsigned short
units;
if (image->units == PixelsPerCentimeterResolution)
{
x_resolution=2.54*65536.0*image->resolution.x+0.5;
y_resolution=2.54*65536.0*image->resolution.y+0.5;
units=2;
}
else
{
x_resolution=65536.0*image->resolution.x+0.5;
y_resolution=65536.0*image->resolution.y+0.5;
units=1;
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x03ED);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,16); /* resource size */
(void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */
(void) WriteBlobMSBShort(image,units); /* width unit */
(void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,units); /* vertical resolution unit */
(void) WriteBlobMSBShort(image,units); /* height unit */
}
static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image,
const signed short channel)
{
size_t
count;
count=(size_t) WriteBlobShort(image,(const unsigned short) channel);
count+=SetPSDSize(psd_info,image,0);
return(count);
}
static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile)
{
const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
unsigned char
*q;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
break;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
if (id == 0x0000040f)
{
ssize_t
quantum;
quantum=PSDQuantum(count)+12;
if ((quantum >= 12) && (quantum < (ssize_t) length))
{
if ((q+quantum < (datum+length-16)))
(void) memmove(q,q+quantum,length-quantum-(q-datum));
SetStringInfoLength(bim_profile,length-quantum);
}
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile)
{
const unsigned char
*p;
size_t
length;
unsigned char
*datum;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
length=GetStringInfoLength(bim_profile);
if (length < 16)
return;
datum=GetStringInfoDatum(bim_profile);
for (p=datum; (p >= datum) && (p < (datum+length-16)); )
{
unsigned char
*q;
ssize_t
cnt;
q=(unsigned char *) p;
if (LocaleNCompare((const char *) p,"8BIM",4) != 0)
return;
p=PushLongPixel(MSBEndian,p,&long_sans);
p=PushShortPixel(MSBEndian,p,&id);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushLongPixel(MSBEndian,p,&count);
cnt=PSDQuantum(count);
if (cnt < 0)
return;
if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)) &&
((ssize_t) length-(cnt+12)-(q-datum)) > 0)
{
(void) memmove(q,q+cnt+12,length-(cnt+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(cnt+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
#define PSDKeySize 5
#define PSDAllowedLength 36
char
key[PSDKeySize];
/* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */
const char
allowed[PSDAllowedLength][PSDKeySize] = {
"blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk",
"GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr",
"lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl",
"post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA"
},
*option;
const StringInfo
*info;
MagickBooleanType
found;
size_t
i;
size_t
remaining_length,
length;
StringInfo
*profile;
unsigned char
*p;
unsigned int
size;
info=GetImageProfile(image,"psd:additional-info");
if (info == (const StringInfo *) NULL)
return((const StringInfo *) NULL);
option=GetImageOption(image_info,"psd:additional-info");
if (LocaleCompare(option,"all") == 0)
return(info);
if (LocaleCompare(option,"selective") != 0)
{
profile=RemoveImageProfile(image,"psd:additional-info");
return(DestroyStringInfo(profile));
}
length=GetStringInfoLength(info);
p=GetStringInfoDatum(info);
remaining_length=length;
length=0;
while (remaining_length >= 12)
{
/* skip over signature */
p+=4;
key[0]=(char) (*p++);
key[1]=(char) (*p++);
key[2]=(char) (*p++);
key[3]=(char) (*p++);
key[4]='\0';
size=(unsigned int) (*p++) << 24;
size|=(unsigned int) (*p++) << 16;
size|=(unsigned int) (*p++) << 8;
size|=(unsigned int) (*p++);
size=size & 0xffffffff;
remaining_length-=12;
if ((size_t) size > remaining_length)
return((const StringInfo *) NULL);
found=MagickFalse;
for (i=0; i < PSDAllowedLength; i++)
{
if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0)
continue;
found=MagickTrue;
break;
}
remaining_length-=(size_t) size;
if (found == MagickFalse)
{
if (remaining_length > 0)
p=(unsigned char *) memmove(p-12,p+size,remaining_length);
continue;
}
length+=(size_t) size+12;
p+=size;
}
profile=RemoveImageProfile(image,"psd:additional-info");
if (length == 0)
return(DestroyStringInfo(profile));
SetStringInfoLength(profile,(const size_t) length);
(void) SetImageProfile(image,"psd:additional-info",info,exception);
return(profile);
}
static MagickBooleanType WritePSDLayersInternal(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,size_t *layers_size,
ExceptionInfo *exception)
{
char
layer_name[MagickPathExtent];
const char
*property;
const StringInfo
*info;
Image
*base_image,
*next_image;
MagickBooleanType
status;
MagickOffsetType
*layer_size_offsets,
size_offset;
ssize_t
i;
size_t
layer_count,
layer_index,
length,
name_length,
rounded_size,
size;
status=MagickTrue;
base_image=GetNextImageInList(image);
if (base_image == (Image *) NULL)
base_image=image;
size=0;
size_offset=TellBlob(image);
(void) SetPSDSize(psd_info,image,0);
layer_count=0;
for (next_image=base_image; next_image != NULL; )
{
layer_count++;
next_image=GetNextImageInList(next_image);
}
if (image->alpha_trait != UndefinedPixelTrait)
size+=WriteBlobShort(image,-(unsigned short) layer_count);
else
size+=WriteBlobShort(image,(unsigned short) layer_count);
layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory(
(size_t) layer_count,sizeof(MagickOffsetType));
if (layer_size_offsets == (MagickOffsetType *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
layer_index=0;
for (next_image=base_image; next_image != NULL; )
{
Image
*mask;
unsigned char
default_color;
unsigned short
channels,
total_channels;
mask=(Image *) NULL;
property=GetImageArtifact(next_image,"psd:opacity-mask");
default_color=0;
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception);
default_color=(unsigned char) (strlen(property) == 9 ? 255 : 0);
}
size+=WriteBlobSignedLong(image,(signed int) next_image->page.y);
size+=WriteBlobSignedLong(image,(signed int) next_image->page.x);
size+=WriteBlobSignedLong(image,(signed int) (next_image->page.y+
next_image->rows));
size+=WriteBlobSignedLong(image,(signed int) (next_image->page.x+
next_image->columns));
channels=1;
if ((next_image->storage_class != PseudoClass) &&
(IsImageGray(next_image) == MagickFalse))
channels=(unsigned short) (next_image->colorspace == CMYKColorspace ? 4 :
3);
total_channels=channels;
if (next_image->alpha_trait != UndefinedPixelTrait)
total_channels++;
if (mask != (Image *) NULL)
total_channels++;
size+=WriteBlobShort(image,total_channels);
layer_size_offsets[layer_index++]=TellBlob(image);
for (i=0; i < (ssize_t) channels; i++)
size+=WriteChannelSize(psd_info,image,(signed short) i);
if (next_image->alpha_trait != UndefinedPixelTrait)
size+=WriteChannelSize(psd_info,image,-1);
if (mask != (Image *) NULL)
size+=WriteChannelSize(psd_info,image,-2);
size+=WriteBlobString(image,image->endian == LSBEndian ? "MIB8" :"8BIM");
size+=WriteBlobString(image,CompositeOperatorToPSDBlendMode(next_image));
property=GetImageArtifact(next_image,"psd:layer.opacity");
if (property != (const char *) NULL)
{
Quantum
opacity;
opacity=(Quantum) StringToInteger(property);
size+=WriteBlobByte(image,ScaleQuantumToChar(opacity));
(void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception);
}
else
size+=WriteBlobByte(image,255);
size+=WriteBlobByte(image,0);
size+=WriteBlobByte(image,(const unsigned char)
(next_image->compose == NoCompositeOp ? 1 << 0x02 : 1)); /* layer properties - visible, etc. */
size+=WriteBlobByte(image,0);
info=GetAdditionalInformation(image_info,next_image,exception);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
{
(void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g",
(double) layer_index);
property=layer_name;
}
name_length=strlen(property)+1;
if ((name_length % 4) != 0)
name_length+=(4-(name_length % 4));
if (info != (const StringInfo *) NULL)
name_length+=GetStringInfoLength(info);
name_length+=8;
if (mask != (Image *) NULL)
name_length+=20;
size+=WriteBlobLong(image,(unsigned int) name_length);
if (mask == (Image *) NULL)
size+=WriteBlobLong(image,0);
else
{
if (mask->compose != NoCompositeOp)
(void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum(
default_color),MagickTrue,exception);
mask->page.y+=image->page.y;
mask->page.x+=image->page.x;
size+=WriteBlobLong(image,20);
size+=WriteBlobSignedLong(image,(const signed int) mask->page.y);
size+=WriteBlobSignedLong(image,(const signed int) mask->page.x);
size+=WriteBlobSignedLong(image,(const signed int) (mask->rows+
mask->page.y));
size+=WriteBlobSignedLong(image,(const signed int) (mask->columns+
mask->page.x));
size+=WriteBlobByte(image,default_color);
size+=WriteBlobByte(image,(const unsigned char)
(mask->compose == NoCompositeOp ? 2 : 0));
size+=WriteBlobMSBShort(image,0);
}
size+=WriteBlobLong(image,0);
size+=WritePascalString(image,property,4);
if (info != (const StringInfo *) NULL)
size+=WriteBlob(image,GetStringInfoLength(info),
GetStringInfoDatum(info));
next_image=GetNextImageInList(next_image);
}
/*
Now the image data!
*/
next_image=base_image;
layer_index=0;
while (next_image != NULL)
{
length=WritePSDChannels(psd_info,image_info,image,next_image,
layer_size_offsets[layer_index++],MagickTrue,exception);
if (length == 0)
{
status=MagickFalse;
break;
}
size+=length;
next_image=GetNextImageInList(next_image);
}
/*
Write the total size
*/
if (layers_size != (size_t*) NULL)
*layers_size=size;
if ((size/2) != ((size+1)/2))
rounded_size=size+1;
else
rounded_size=size;
(void) WritePSDSize(psd_info,image,rounded_size,size_offset);
layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory(
layer_size_offsets);
/*
Remove the opacity mask from the registry
*/
next_image=base_image;
while (next_image != (Image *) NULL)
{
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
(void) DeleteImageRegistry(property);
next_image=GetNextImageInList(next_image);
}
return(status);
}
ModuleExport MagickBooleanType WritePSDLayers(Image * image,
const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception)
{
PolicyDomain
domain;
PolicyRights
rights;
domain=CoderPolicyDomain;
rights=WritePolicyRights;
if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse)
return(MagickTrue);
return WritePSDLayersInternal(image,image_info,psd_info,(size_t*) NULL,
exception);
}
static MagickBooleanType WritePSDImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const StringInfo
*icc_profile;
ImageType
type;
MagickBooleanType
status;
PSDInfo
psd_info;
ssize_t
i;
size_t
length,
num_channels,
packet_size;
StringInfo
*bim_profile;
/*
Open image file.
*/
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);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
packet_size=(size_t) (image->depth > 8 ? 6 : 3);
if (image->alpha_trait != UndefinedPixelTrait)
packet_size+=image->depth > 8 ? 2 : 1;
psd_info.version=1;
if ((LocaleCompare(image_info->magick,"PSB") == 0) ||
(image->columns > 30000) || (image->rows > 30000))
psd_info.version=2;
(void) WriteBlob(image,4,(const unsigned char *) "8BPS");
(void) WriteBlobMSBShort(image,psd_info.version); /* version */
for (i=1; i <= 6; i++)
(void) WriteBlobByte(image, 0); /* 6 bytes of reserved */
/* When the image has a color profile it won't be converted to gray scale */
type=IdentifyImageCoderType(image,exception);
(void) type;
if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) &&
(SetImageGray(image,exception) != MagickFalse))
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorAlphaType) &&
(image->storage_class == PseudoClass))
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
{
if (image->storage_class == PseudoClass)
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->colorspace != CMYKColorspace)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);
else
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);
}
(void) WriteBlobMSBShort(image,(unsigned short) num_channels);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
if (IsImageGray(image) != MagickFalse)
{
MagickBooleanType
monochrome;
/*
Write depth & mode.
*/
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8));
(void) WriteBlobMSBShort(image,(unsigned short)
(monochrome != MagickFalse ? BitmapMode : GrayscaleMode));
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class ==
PseudoClass ? 8 : image->depth > 8 ? 16 : 8));
if (((image_info->colorspace != UndefinedColorspace) ||
(image->colorspace != CMYKColorspace)) &&
(image_info->colorspace != CMYKColorspace))
{
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) WriteBlobMSBShort(image,(unsigned short)
(image->storage_class == PseudoClass ? IndexedMode : RGBMode));
}
else
{
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace,exception);
(void) WriteBlobMSBShort(image,CMYKMode);
}
}
if ((IsImageGray(image) != MagickFalse) ||
(image->storage_class == DirectClass) || (image->colors > 256))
(void) WriteBlobMSBLong(image,0);
else
{
/*
Write PSD raster colormap.
*/
(void) WriteBlobMSBLong(image,768);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[i].red)));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[i].green)));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum(
image->colormap[i].blue)));
for ( ; i < 256; i++)
(void) WriteBlobByte(image,0);
}
/*
Image resource block.
*/
length=28; /* 0x03EB */
bim_profile=(StringInfo *) GetImageProfile(image,"8bim");
icc_profile=GetImageProfile(image,"icc");
if (bim_profile != (StringInfo *) NULL)
{
bim_profile=CloneStringInfo(bim_profile);
if (icc_profile != (StringInfo *) NULL)
RemoveICCProfileFromResourceBlock(bim_profile);
RemoveResolutionFromResourceBlock(bim_profile);
length+=PSDQuantum(GetStringInfoLength(bim_profile));
}
if (icc_profile != (const StringInfo *) NULL)
length+=PSDQuantum(GetStringInfoLength(icc_profile))+12;
(void) WriteBlobMSBLong(image,(unsigned int) length);
WriteResolutionResourceBlock(image);
if (bim_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,GetStringInfoLength(bim_profile),
GetStringInfoDatum(bim_profile));
bim_profile=DestroyStringInfo(bim_profile);
}
if (icc_profile != (StringInfo *) NULL)
{
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlobMSBShort(image,0x0000040F);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength(
icc_profile));
(void) WriteBlob(image,GetStringInfoLength(icc_profile),
GetStringInfoDatum(icc_profile));
if ((ssize_t) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile)))
(void) WriteBlobByte(image,0);
}
if (status != MagickFalse)
{
const char
*option;
MagickOffsetType
size_offset;
size_t
size;
size_offset=TellBlob(image);
(void) SetPSDSize(&psd_info,image,0);
option=GetImageOption(image_info,"psd:write-layers");
if (IsStringFalse(option) != MagickTrue)
{
status=WritePSDLayersInternal(image,image_info,&psd_info,&size,
exception);
(void) WritePSDSize(&psd_info,image,size+
(psd_info.version == 1 ? 8 : 12),size_offset);
}
}
(void) WriteBlobMSBLong(image,0); /* user mask data */
/*
Write composite image.
*/
if (status != MagickFalse)
{
CompressionType
compression;
compression=image->compression;
if (image_info->compression != UndefinedCompression)
image->compression=image_info->compression;
if (image->compression == ZipCompression)
image->compression=RLECompression;
if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse,
exception) == 0)
status=MagickFalse;
image->compression=compression;
}
(void) CloseBlob(image);
return(status);
}
|
convolution_quantize_arm.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
static void conv_quantize_neon(const Mat &bottom_blob, Mat &bottom_blob_s8, const float dataScale)
{
float ufDataFactor = dataScale;
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int size = w * h;
int FPSCR_value = 0;
#if NCNN_INT8_INFO
fprintf(stderr, "scale %f\n", dataScale);
#endif
asm volatile(
"VMRS r10, FPSCR \n"
"MOV %0, r10 \n"
"BIC r10, r10,#0x00c00000 \n"
"VMSR FPSCR,r10 \n"
: "=r"(FPSCR_value)
: "0"(FPSCR_value)
: "cc", "r10"
);
size = w*h;
#pragma omp parallel for
for (int qidx=0; qidx<inch; qidx++)
{
const float* img0 = bottom_blob.channel(qidx);
signed char* img0_s8 = bottom_blob_s8.channel(qidx);
int nn = size >> 3;
int remain = size & 7;
if(nn > 0)
{
asm volatile(
"PLD [%1, #256] \n"
"VLD1.F32 {D0-D3}, [%1]! \n"
"VDUP.32 Q10, %3 \n"
"0: \n"
"VMUL.F32 Q0,Q0,Q10 \n"
"VMUL.F32 Q1,Q1,Q10 \n"
"VCVTR.S32.F32 S0,S0 \n"
"VCVTR.S32.F32 S1,S1 \n"
"VCVTR.S32.F32 S2,S2 \n"
"VCVTR.S32.F32 S3,S3 \n"
"VCVTR.S32.F32 S4,S4 \n"
"VCVTR.S32.F32 S5,S5 \n"
"VCVTR.S32.F32 S6,S6 \n"
"VCVTR.S32.F32 S7,S7 \n"
"VQMOVN.S32 D4,Q0 \n"
"VQMOVN.S32 D5,Q1 \n"
"PLD [%1, #256] \n"
"VLD1.F32 {D0-D3}, [%1]! \n"
"VQMOVN.S16 D4,Q2 \n"
"VST1.8 {D4}, [%2]! \n"
"SUBS %0, #1 \n"
"BNE 0b \n"
"SUB %1, #32 \n"
: "=r"(nn), // %0
"=r"(img0), // %1
"=r"(img0_s8), // %2
"=r"(ufDataFactor) // %3
: "0"(nn),
"1"(img0),
"2"(img0_s8),
"3"(ufDataFactor)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q10", "q11"
);
}
if(remain > 0)
{
asm volatile(
"VLD1.F32 {D0[0]}, [%1]! \n"
"VDUP.32 Q10, %3 \n"
"0: \n"
"VMUL.F32 Q0,Q0,Q10 \n"
"VCVTR.S32.F32 S0,S0 \n"
"VQMOVN.S32 D4,Q0 \n"
"VLD1.F32 {D0[0]}, [%1]! \n"
"VQMOVN.S16 D4,Q2 \n"
"VST1.8 {D4[0]}, [%2]! \n"
"SUBS %0, #1 \n"
"BNE 0b \n"
: "=r"(remain), // %0
"=r"(img0), // %1
"=r"(img0_s8), // %2
"=r"(ufDataFactor) // %3
: "0"(remain),
"1"(img0),
"2"(img0_s8),
"3"(ufDataFactor)
: "cc", "memory", "q0", "q1", "q2", "q10"
);
}
}
//ncnn_comm_print_blob(bottom_blob, PRINT_BLOB_TYPE_S16);
asm volatile(
"MOV r10, %0 \n"
"VMSR FPSCR, r10 \n"
: "=r"(FPSCR_value)
: "0"(FPSCR_value)
: "cc", "r10"
);
}
static void conv_dequantize_neon(Mat &top_blob, const Mat &_bias, const float dataScale, const float weightScale)
{
float ufReverseFactor = 0.f;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
int size = outh * outw;
const float *bias = _bias;
if (0 != dataScale * weightScale)
{
ufReverseFactor = 1 / (dataScale * weightScale);
}
#pragma omp parallel for
for (int p=0; p<outch; p++)
{
const float* img0 = top_blob.channel(p);
int* img0_s32 = (int*)img0;
float* img0_f32 = (float*)img0;
float bias0 = bias ? bias[p] : 0.f;
int nn = size >> 3;
int remain = size & 7;
if(nn > 0)
{
asm volatile(
"PLD [%1, #256] \n"
"VLD1.S32 {D0-D3}, [%1]! \n" //Q0-Q1 data
"VDUP.F32 Q10, %3 \n" //Q10 scale
"VDUP.F32 Q12, %4 \n" //Q12 bias
"0: \n"
"VCVTR.F32.S32 Q0,Q0 \n"
"VCVTR.F32.S32 Q1,Q1 \n"
"VMUL.F32 Q0,Q0,Q10 \n"
"VMUL.F32 Q1,Q1,Q10 \n"
"VADD.F32 Q2,Q0,Q12 \n"
"VADD.F32 Q3,Q1,Q12 \n"
"PLD [%1, #256] \n"
"VLD1.S32 {D0-D3}, [%1]! \n"
"VST1.F32 {D4-D7}, [%2]! \n"
"SUBS %0, #1 \n"
"BNE 0b \n"
"SUB %1, #32 \n"
: "=r"(nn), // %0
"=r"(img0_s32), // %1
"=r"(img0_f32), // %2
"=r"(ufReverseFactor), // %3
"=r"(bias0) // %4
: "0"(nn),
"1"(img0_s32),
"2"(img0_f32),
"3"(ufReverseFactor),
"4"(bias0)
: "cc", "memory", "q0", "q1", "q2", "q4", "q10", "q12"
);
}
if(remain > 0)
{
asm volatile(
"VLD1.F32 {D0[0]}, [%1]! \n" //D0 data
"VDUP.32 Q10, %3 \n" //Q10 scale
"VDUP.32 Q12, %4 \n" //Q12 bias
"0: \n"
"VCVTR.F32.S32 S0,S0 \n"
"VMUL.F32 Q0,Q0,Q10 \n"
"VADD.F32 Q2,Q0,Q12 \n"
//store
"VLD1.F32 {D0[0]}, [%1]! \n"
"VST1.F32 {D4[0]}, [%2]! \n"
"SUBS %0, #1 \n"
"BNE 0b \n"
: "=r"(remain), // %0
"=r"(img0_s32), // %1
"=r"(img0_f32), // %2
"=r"(ufReverseFactor), // %3
"=r"(bias0) // %4
: "0"(remain),
"1"(img0_s32),
"2"(img0_f32),
"3"(ufReverseFactor),
"4"(bias0)
: "cc", "memory", "q0", "q1", "q2", "q4", "q10", "q12"
);
}
}
}
|
general_basis_get_vec.h | #ifndef _GENERAL_BASIS_GET_VEC_H
#define _GENERAL_BASIS_GET_VEC_H
#include "general_basis_core.h"
#include "numpy/ndarraytypes.h"
#include "misc.h"
#include "openmp.h"
namespace basis_general {
// NOTE about openmp:
// As the basis representative states for a unique sub-groups of the full H-space.
// each thread will never access the same elements as other threads.
template<class T,class P>
bool inline update_out_dense(std::complex<double> c, P phase, npy_intp n_vec,const std::complex<T> *in, std::complex<T> *out){
for(npy_intp i=0;i<n_vec;i++){
out[i] += T(phase) * std::complex<T>(c) * in[i];
}
return true;
}
template<class T,class P>
bool inline update_out_dense(std::complex<double> c, P phase, npy_intp n_vec,const T *in, T *out){
if(std::abs(c.imag())>1.1e-15){
return false;
}
else{
T re = c.real();
for(npy_intp i=0;i<n_vec;i++){
out[i] += T(phase) * re * in[i];
}
return true;
}
}
template<class T>
bool inline update_out_dense(std::complex<double> c, std::complex<double> phase, npy_intp n_vec,const std::complex<T> *in, std::complex<T> *out){
for(npy_intp i=0;i<n_vec;i++){
out[i] += std::complex<T>(phase*c) * in[i];
}
return true;
}
template<class T>
bool inline update_out_dense(std::complex<double> c, std::complex<double> phase, npy_intp n_vec,const T *in, T *out){
c *= phase;
if(std::abs(c.imag())>1.1e-15){
return false;
}
else{
T re = c.real();
for(npy_intp i=0;i<n_vec;i++){
out[i] += re * in[i];
}
return true;
}
}
template<class I,class T,class P=signed char>
bool project_from_rep(general_basis_core<I,P> *B,
I s,
P &phase,
const int nt,
const npy_intp n_vec,
const npy_intp Ns_full,
const T in[],
std::complex<double> c,
T out[],
const int depth = 0)
{
bool err = true;
if(nt<=0){
const npy_intp full = (Ns_full - s - 1)*n_vec;
err = update_out_dense(c,phase,n_vec,in,&out[full]);
return err;
}
int per = B->pers[depth];
double q = (2.0*M_PI*B->qs[depth])/per;
std::complex<double> cc = std::exp(std::complex<double>(0,-q));
if(depth < nt-1){
for(int j=0;j<per && err;j++){
err = project_from_rep(B,s,phase,nt,n_vec,Ns_full,in,c,out,depth+1);
c *= cc;
s = B->map_state(s,depth,phase);
}
return err;
}
else{
for(int j=0;j<per && err;j++){
const npy_intp full = (Ns_full - s - 1)*n_vec;
err = update_out_dense(c,phase,n_vec,in,&out[full]);
c *= cc;
s = B->map_state(s,depth,phase);
}
return err;
}
}
template<class I,class T,class P=signed char>
bool project_from_rep_basis(general_basis_core<I,P> *B,
I s,
P &phase,
const int nt,
const npy_intp n_vec,
const I basis[],
const npy_intp Ns,
const T in[],
std::complex<double> c,
T out[],
const int depth = 0)
{
bool err = true;
if(nt<=0){
const npy_intp full = rep_position(Ns,basis,s)*n_vec;
err = update_out_dense(c,phase,n_vec,in,&out[full]);
return err;
}
int per = B->pers[depth];
double q = (2.0*M_PI*B->qs[depth])/per;
std::complex<double> cc = std::exp(std::complex<double>(0,-q));
if(depth < nt-1){
for(int j=0;j<per && err;j++){
err = project_from_rep_basis(B,s,phase,nt,n_vec,basis,Ns,in,c,out,depth+1);
c *= cc;
s = B->map_state(s,depth,phase);
}
return err;
}
else{
for(int j=0;j<per && err;j++){
const npy_intp full = rep_position(Ns,basis,s)*n_vec;
err = update_out_dense(c,phase,n_vec,in,&out[full]);
c *= cc;
s = B->map_state(s,depth,phase);
}
return err;
}
}
template<class I,class J,class T,class P=signed char>
bool project_from_general_pcon_dense(general_basis_core<I,P> *B,
const I basis[],
const J n[],
const npy_intp n_vec,
const npy_intp Ns,
const npy_intp Ns_full,
const I basis_pcon[],
const T in[],
T out[])
{
bool err = true;
const int nt = B->get_nt();
const npy_intp chunk = std::max(Ns/(100*omp_get_max_threads()),(npy_intp)1);
double norm = 1.0;
for(int i=0;i<nt;i++){
norm *= B->pers[i];
}
#pragma omp parallel for schedule(dynamic,chunk) firstprivate(norm)
for(npy_intp k=0;k<Ns;k++){
if(!err){continue;}
std::complex<double> c = 1.0/std::sqrt(n[k]*norm);
P phase = 1;
bool local_err = project_from_rep_basis(B,basis[k],phase,nt,n_vec,basis_pcon,Ns_full,&in[k*n_vec],c,out);
if(!local_err){
#pragma omp critical
err = local_err;
}
}
return err;
}
template<class I,class J,class T,class P=signed char>
bool project_from_general_dense(general_basis_core<I,P> *B,
const I basis[],
const J n[],
const npy_intp n_vec,
const npy_intp Ns,
const npy_intp Ns_full,
const T in[],
T out[])
{
bool err = true;
const int nt = B->get_nt();
const npy_intp chunk = std::max(Ns/(100*omp_get_max_threads()),(npy_intp)1);
double norm = 1.0;
for(int i=0;i<nt;i++){
norm *= B->pers[i];
}
#pragma omp parallel for schedule(dynamic,chunk) firstprivate(norm)
for(npy_intp k=0;k<Ns;k++){
if(!err){continue;}
std::complex<double> c = 1.0/std::sqrt(n[k]*norm);
P phase = 1;
bool local_err = project_from_rep(B,basis[k],phase,nt,n_vec,Ns_full,&in[k*n_vec],c,out);
if(!local_err){
#pragma omp critical
err = local_err;
}
}
return err;
}
// get_vec -> project_from
// get_vec_inv -> project_to
template<class I,class T,class P=signed char>
bool project_to_rep(general_basis_core<I,P> *B,
I s,
P &phase,
const int nt,
const npy_intp n_vec,
const npy_intp Ns_full,
const T in[],
std::complex<double> c,
T out[],
const int depth = 0)
{
bool err = true;
if(nt<=0){
const npy_intp full = (Ns_full - s - 1)*n_vec;
err = update_out_dense(c,phase,n_vec,&in[full],out);
return err;
}
int per = B->pers[depth];
double q = (2.0*M_PI*B->qs[depth])/per;
std::complex<double> cc = std::exp(std::complex<double>(0,q));
if(depth < nt-1){
for(int j=0;j<per && err;j++){
err = project_to_rep(B,s,phase,nt,n_vec,Ns_full,in,c,out,depth+1);
c *= cc;
s = B->map_state(s,depth,phase);
}
return err;
}
else{
for(int j=0;j<per && err;j++){
const npy_intp full = (Ns_full - s - 1)*n_vec;
err = update_out_dense(c,phase,n_vec,&in[full],out);
c *= cc;
s = B->map_state(s,depth,phase);
}
return err;
}
}
template<class I,class T,class P=signed char>
bool project_to_rep_basis(general_basis_core<I,P> *B,
I s,
P &phase,
const int nt,
const npy_intp n_vec,
const I basis[],
const npy_intp Ns,
const T in[],
std::complex<double> c,
T out[],
const int depth = 0)
{
bool err = true;
if(nt<=0){
const npy_intp full = rep_position(Ns,basis,s)*n_vec;
err = update_out_dense(c,phase,n_vec,&in[full],out);
return err;
}
int per = B->pers[depth];
double q = (2.0*M_PI*B->qs[depth])/per;
std::complex<double> cc = std::exp(std::complex<double>(0,-q));
if(depth < nt-1){
for(int j=0;j<per && err;j++){
err = project_from_rep_basis(B,s,phase,nt,n_vec,basis,Ns,in,c,out,depth+1);
c *= cc;
s = B->map_state(s,depth,phase);
}
return err;
}
else{
for(int j=0;j<per && err;j++){
const npy_intp full = rep_position(Ns,basis,s)*n_vec;
err = update_out_dense(c,phase,n_vec,&in[full],out);
c *= cc;
s = B->map_state(s,depth,phase);
}
return err;
}
}
template<class I,class J,class T,class P=signed char>
bool project_to_general_pcon_dense(general_basis_core<I,P> *B,
const I basis[],
const J n[],
const npy_intp n_vec,
const npy_intp Ns,
const npy_intp Ns_full,
const I basis_pcon[],
const T in[],
T out[])
{
bool err = true;
const int nt = B->get_nt();
const npy_intp chunk = std::max(Ns/(100*omp_get_max_threads()),(npy_intp)1);
double norm = 1.0;
for(int i=0;i<nt;i++){
norm *= B->pers[i];
}
#pragma omp parallel for schedule(dynamic,chunk) firstprivate(norm)
for(npy_intp k=0;k<Ns;k++){
if(!err){continue;}
std::complex<double> c = 1.0/std::sqrt(n[k]*norm);
P phase = 1;
bool local_err = project_to_rep_basis(B,basis[k],phase,nt,n_vec,basis_pcon,Ns_full,in,c,&out[k*n_vec]);
if(!local_err){
#pragma omp critical
err = local_err;
}
}
return err;
}
template<class I,class J,class T,class P=signed char>
bool project_to_general_dense(general_basis_core<I,P> *B,
const I basis[],
const J n[],
const npy_intp n_vec,
const npy_intp Ns,
const npy_intp Ns_full,
const T in[],
T out[])
{
bool err = true;
const int nt = B->get_nt();
const npy_intp chunk = std::max(Ns/(100*omp_get_max_threads()),(npy_intp)1);
double norm = 1.0;
for(int i=0;i<nt;i++){
norm *= B->pers[i];
}
#pragma omp parallel for schedule(dynamic,chunk) firstprivate(norm)
for(npy_intp k=0;k<Ns;k++){
if(!err){continue;}
std::complex<double> c = 1.0/std::sqrt(n[k]*norm);
P phase = 1;
bool local_err = project_to_rep(B,basis[k],phase,nt,n_vec,Ns_full,in,c,&out[k*n_vec]);
if(!local_err){
#pragma omp critical
err = local_err;
}
}
return err;
}
}
#endif
|
matfit.c | #include "matrix.h"
#include <string.h>
#define MAX_ITERS_RB 20
/** \brief Performs 2-d polynomial model fitting using least squares
*
* \param[in] A Input data column matrix
* \param[in] Y Input observation column matrix
* \param[in] deg Polynomial degree \f$ N \f$
* \param[in] result Matrix to store the result
* \return Polynomial co-efficient matrix \f$ \begin{bmatrix} \alpha_N & \cdots & \alpha_0\end{bmatrix}^T \f$
*
*/
MATRIX mat_linear_ls_fit(MATRIX A, MATRIX Y, int deg, MATRIX result)
{
int i, j, n;
MATRIX B;
n = MatRow(A);
B = mat_creat(n, deg+1, ONES_MATRIX);
#pragma omp parallel for private(j)
for(i=0; i<n; ++i)
{
for(j=deg-1; j>=0; --j) B[i][j] = A[i][0]*B[i][j+1];
}
result = mat_least_squares(B, Y, result);
mat_free(B);
return result;
}
/** \brief Solves linear equations using least squares
*
* \param[in] A Input data matrix
* \param[in] Y Input observation matrix
* \param[in] result Matrix to store the result
* \return \f$ \left(\mathbf{A}^{T}\mathbf{A}\right)^{-1}\mathbf{A}^{T}\mathbf{Y} \f$
*
*/
MATRIX mat_least_squares(MATRIX A, MATRIX Y, MATRIX result)
{
int m, n, o, i, j, k;
MATRIX Apinv;
if(MatRow(A)!=MatRow(Y)) return mat_error(MAT_SIZEMISMATCH);
Apinv = mat_pinv(A, NULL);
if(Apinv ==NULL) return mat_error(MAT_INVERSE_ILL_COND);
m = MatCol(Apinv);
n = MatRow(Apinv);
o = MatCol(Y);
if(result==NULL) if((result= mat_creat(n, o, UNDEFINED))==NULL)
return mat_error(MAT_MALLOC);
#pragma omp parallel for private(j, k) firstprivate(m)
for(i=0; i<n; ++i)
{
for(j=0; j<o; ++j)
{
for(k=0, result[i][j]=0.0; k<m; ++k)
{
result[i][j] += Apinv[i][k]*Y[k][j];
}
}
}
mat_free(Apinv);
return result;
}
/** \brief Solves linear equations using weighted least squares
*
* \param[in] A Input data matrix
* \param[in] Y Input observation matrix
* \param[in] w Input weight column matrix
* \param[in] result Matrix to store the result
* \return \f$ \left(\mathbf{A}^{T}\textrm{diag}(w)\mathbf{A}\right)^{-1}\mathbf{A}^{T}\textrm{diag}(w)\mathbf{Y} \f$
*
*/
MATRIX mat_w_least_squares(MATRIX A, MATRIX Y, MATRIX w, MATRIX result)
{
int m, n, o, i, j, k;
MATRIX Awpinv, W;
if(MatRow(w)!= MatRow(Y)) return mat_error(MAT_SIZEMISMATCH);
W = mat_creat_diag(w, NULL);
if(MatRow(A)!= MatRow(Y)) return mat_error(MAT_SIZEMISMATCH);
Awpinv = mat_wpinv(A, W, NULL);
if(Awpinv==NULL) return mat_error(MAT_INVERSE_ILL_COND);
m = MatCol(Awpinv);
n = MatRow(Awpinv);
o = MatCol(Y);
if(result==NULL) if((result = mat_creat(n, o, UNDEFINED))==NULL)
return mat_error(MAT_MALLOC);
#pragma omp parallel for private(j, k) firstprivate(m)
for(i=0; i<n; ++i)
{
for(j=0; j<o; ++j)
{
for(k=0, result[i][j]=0.0; k<m; ++k)
{
result[i][j] += Awpinv[i][k]*Y[k][j];
}
}
}
mat_free(Awpinv);
mat_free(W);
return result;
}
/** \brief Solves linear equations using robust reweighted least squares
*
* \param[in] A Input data matrix
* \param[in] Y Input observation matrix
* \param[in] lossfunc Loss function type (MAT_LOSS_BISQUARE/MAT_LOSS_HUBER)
* \param[in] result Matrix to store the result
* \return Robust \f$ \mathbf{X}\f$
*
*/
MATRIX mat_rob_least_squares(MATRIX A, MATRIX Y, int lossfunc, MATRIX result)
{
int n, k;
int flag = 0;
mtype med = 0, madn_ = 0, norm_th= 0;
MATRIX res = NULL, res_ = NULL, W = NULL, tmp1 = NULL, tmp2 = NULL;
n = MatRow(A);
W = mat_creat(n, 1, ONES_MATRIX);
tmp1 = mat_abs(Y, NULL);
norm_th = 0.0001f*mat_sum(tmp1);
mat_free(tmp1);
tmp1 = NULL;
for(k=0; k<MAX_ITERS_RB && flag==0; ++k)
{
result = mat_w_least_squares(A, Y, W, result);
tmp1 = mat_mul(A, result, tmp1);
res_ = mat_sub(tmp1, Y, res_);
if(k==0)
{
med = mat_median(res_);
tmp1 = mat_subs(res_, med, tmp1);
tmp2 = mat_abs(tmp1, tmp2);
madn_ = mat_median(tmp2)*1.4826+(mtype)eps;/* *6.9414 */
mat_free(tmp2);
}
res = mat_abs(res_, res);
if(mat_sum(res)<norm_th) flag = 1;
if(k!=(MAX_ITERS_RB-1))
{
switch(lossfunc)
{
case MAT_LOSS_HUBER:
W = mat_huber_wt(res, 1.0, madn_*1.345, W);
break;
case MAT_LOSS_BISQUARE:
W = mat_bisquare_wt(res, 1.0, madn_*4.685, W);
break;
default:
W = mat_bisquare_wt(res, 1.0, madn_*4.685, W);
}
}
}
mat_free(W);
mat_free(res);
mat_free(res_);
mat_free(tmp1);
return result;
}
/** \brief Performs 2-d polynomial model fitting using robust least squares
*
* \param[in] A Input data column matrix
* \param[in] Y Input observation column matrix
* \param[in] deg Polynomial degree \f$ N \f$
* \param[in] lossfunc Loss function type (MAT_LOSS_BISQUARE/MAT_LOSS_HUBER)
* \param[in] result Matrix to store the result
* \return Polynomial co-efficient matrix \f$ \begin{bmatrix} \alpha_N & \cdots & \alpha_0\end{bmatrix}^T \f$
*
*/
MATRIX mat_robust_fit(MATRIX A, MATRIX Y, int deg, int lossfunc, MATRIX result)
{
int i, j, n;
MATRIX B = NULL;
n = MatRow(A);
B = mat_creat(n, deg+1, ONES_MATRIX);
#pragma omp parallel for private(j)
for(i=0; i<n; ++i)
{
for(j=deg-1; j>=0; --j) B[i][j] = A[i][0]*B[i][j+1];
}
result = mat_rob_least_squares(B, Y, lossfunc, result);
mat_free(B);
return result;
}
|
GB_binop__lxor_int64.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_mkl.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB_AaddB__lxor_int64
// A.*B function (eWiseMult): GB_AemultB__lxor_int64
// A*D function (colscale): GB_AxD__lxor_int64
// D*A function (rowscale): GB_DxB__lxor_int64
// C+=B function (dense accum): GB_Cdense_accumB__lxor_int64
// C+=b function (dense accum): GB_Cdense_accumb__lxor_int64
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__lxor_int64
// C=scalar+B GB_bind1st__lxor_int64
// C=scalar+B' GB_bind1st_tran__lxor_int64
// C=A+scalar GB_bind2nd__lxor_int64
// C=A'+scalar GB_bind2nd_tran__lxor_int64
// C type: int64_t
// A type: int64_t
// B,b type: int64_t
// BinaryOp: cij = ((aij != 0) != (bij != 0))
#define GB_ATYPE \
int64_t
#define GB_BTYPE \
int64_t
#define GB_CTYPE \
int64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int64_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
int64_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y) \
z = ((x != 0) != (y != 0)) ;
// 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_LXOR || GxB_NO_INT64 || GxB_NO_LXOR_INT64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void (none)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__lxor_int64
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumB__lxor_int64
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__lxor_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__lxor_int64
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *GB_RESTRICT Cx = (int64_t *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_DxB__lxor_int64
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *GB_RESTRICT Cx = (int64_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB_AaddB__lxor_int64
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_add_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB_AemultB__lxor_int64
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB_bind1st__lxor_int64
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *Cx = (int64_t *) Cx_output ;
int64_t x = (*((int64_t *) x_input)) ;
int64_t *Bx = (int64_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int64_t bij = Bx [p] ;
Cx [p] = ((x != 0) != (bij != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__lxor_int64
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
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++)
{
int64_t aij = Ax [p] ;
Cx [p] = ((aij != 0) != (y != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int64_t aij = Ax [pA] ; \
Cx [pC] = ((x != 0) != (aij != 0)) ; \
}
GrB_Info GB_bind1st_tran__lxor_int64
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t x = (*((const int64_t *) x_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int64_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int64_t aij = Ax [pA] ; \
Cx [pC] = ((aij != 0) != (y != 0)) ; \
}
GrB_Info GB_bind2nd_tran__lxor_int64
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t y = (*((const int64_t *) y_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
inference.c | #include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <sys/time.h>
#include <assert.h>
#include <string.h>
/* Optionally include OpenMP with the -fopenmp flag */
#if defined(_OPENMP)
#include <omp.h>
#endif
#include "include/lbfgs.h"
#include "include/twister.h"
#include "include/plm.h"
#include "include/inference.h"
/* Internal prototypes */
numeric_t ElapsedTime(struct timeval *start);
/* Numerical bounds for ZeroAPCPriors */
#define LAMBDA_J_MIN 1E-2
#define LAMBDA_J_MAX 1E4
#define REGULARIZATION_GROUP_EPS 0.001
/* Internal to InferPairModel:
MAP estimation of parameters by L-BFGS */
void EstimatePairModelMAP(numeric_t *x, numeric_t *lambdas, alignment_t *ali,
options_t *options);
/* Internal to EstimatePairModelMAP:
Stochastic optimization with SGD */
typedef numeric_t (*gradfun_t) (void *data, const numeric_t *x, numeric_t *g,
const int n);
void SGDOptimize(gradfun_t grad, void *data, numeric_t *x, const int n,
const int maxIter, const numeric_t crit);
numeric_t SGDWrapperPLM(void *data, const numeric_t *x, numeric_t *g, const int n);
/* Internal to EstimatePairModelMAP:
Objective functions for point parameter estimates (MAP) */
static lbfgsfloatval_t PLMNegLogPosterior(void *instance,
const lbfgsfloatval_t *x, lbfgsfloatval_t *g, const int n,
const lbfgsfloatval_t step);
static lbfgsfloatval_t PLMNegLogPosteriorGapReduce(void *instance,
const lbfgsfloatval_t *x, lbfgsfloatval_t *g, const int n,
const lbfgsfloatval_t step);
static lbfgsfloatval_t PLMNegLogPosteriorBlock(void *instance,
const lbfgsfloatval_t *x, lbfgsfloatval_t *g, const int n,
const lbfgsfloatval_t step);
static lbfgsfloatval_t PLMNegLogPosteriorDO(void *instance,
const lbfgsfloatval_t *x, lbfgsfloatval_t *g, const int n,
const lbfgsfloatval_t step);
/* Internal to EstimatePairModelMAP: progress reporting */
static int ReportProgresslBFGS(void *instance, const lbfgsfloatval_t *x,
const lbfgsfloatval_t *g, const lbfgsfloatval_t fx,
const lbfgsfloatval_t xnorm, const lbfgsfloatval_t gnorm,
const lbfgsfloatval_t step, int n, int k, int ls);
/* Internal to EstimatePairModelMAP: parameter processing */
void PreCondition(const lbfgsfloatval_t *x, lbfgsfloatval_t *g,
alignment_t *ali, options_t *options);
lbfgsfloatval_t PostCondition(const lbfgsfloatval_t *x, lbfgsfloatval_t *g, lbfgsfloatval_t fx,
alignment_t *ali, options_t *options);
void ZeroAPCPriors(alignment_t *ali, options_t *options, numeric_t *lambdas,
lbfgsfloatval_t *x);
/* Internal to EstimatePairModelMAP: utility functions to L-BFGS */
const char *LBFGSErrorString(int ret);
numeric_t *InferPairModel(alignment_t *ali, options_t *options) {
/* Estimate the parameters of a maximum entropy model for a
multiple sequence alignment */
/* Initialize the regularization parameters */
numeric_t *lambdas =
(numeric_t *) malloc((ali->nSites + ali->nSites * (ali->nSites - 1) / 2)
* sizeof(numeric_t));
for (int i = 0; i < ali->nSites; i++) lambdaHi(i) = options->lambdaH;
for (int i = 0; i < ali->nSites - 1; i++)
for (int j = i + 1; j < ali->nSites; j++)
lambdaEij(i, j) = options->lambdaE;
/* For gap-reduced problems, eliminate the gaps and reduce the alphabet */
if (options->estimatorMAP == INFER_MAP_PLM_GAPREDUCE) {
ali->nCodes = strlen(ali->alphabet) - 1;
for (int i = 0; i < ali->nSites; i++)
for (int s = 0; s < ali->nSeqs; s++)
seq(s, i) -= 1;
}
/* Initialize parameters */
ali->nParams = ali->nSites * ali->nCodes
+ ali->nSites * (ali->nSites - 1) / 2 * ali->nCodes * ali->nCodes;
numeric_t *x = (numeric_t *) malloc(sizeof(numeric_t) * ali->nParams);
if (x == NULL) {
fprintf(stderr,
"ERROR: Failed to allocate a memory block for variables.\n");
exit(1);
}
for (int i = 0; i < ali->nParams; i++) x[i] = 0.0;
/* Initialize site parameters with the ML estimates
hi = log(fi) + C
A single pseudocount is added for stability
(Laplace's rule or Morcos et al. with lambda = nCodes) */
if (options->zeroAPC != 1) {
for (int i = 0; i < ali->nSites; i++)
for (int ai = 0; ai < ali->nCodes; ai++)
xHi(i, ai) = log(fi(i, ai) * ali->nEff + 1.0);
/* Zero-sum gauge */
for (int i = 0; i < ali->nSites; i++) {
numeric_t hSum = 0.0;
for (int ai = 0; ai < ali->nCodes; ai++) hSum += xHi(i, ai);
numeric_t hShift = hSum / (numeric_t) ali->nCodes;
for (int ai = 0; ai < ali->nCodes; ai++)
xHi(i, ai) -= hShift;
}
}
switch(options->estimator) {
/* Point estimates */
case INFER_MAP:
/* Maximum a posteriori estimates of model parameters */
EstimatePairModelMAP(x, lambdas, ali, options);
break;
/* For: future alternative estimators */
default:
/* Maximum a posteriori estimates of model parameters */
EstimatePairModelMAP(x, lambdas, ali, options);
}
/* Restore the alignment encoding after inference */
if (options->estimatorMAP == INFER_MAP_PLM_GAPREDUCE) {
for (int i = 0; i < ali->nSites; i++)
for (int s = 0; s < ali->nSeqs; s++)
seq(s, i) += 1;
}
return (numeric_t *) x;
}
void EstimatePairModelMAP(numeric_t *x, numeric_t *lambdas, alignment_t *ali,
options_t *options) {
/* Computes Maximum a posteriori (MAP) estimates for the parameters of
and undirected graphical model by L-BFGS */
/* Start timer */
gettimeofday(&ali->start, NULL);
/* Initialize L-BFGS */
lbfgs_parameter_t param;
lbfgs_parameter_init(¶m);
param.epsilon = 1E-3;
param.max_iterations = options->maxIter; /* 0 is unbounded */
/* Estimate parameters by optimization */
static lbfgs_evaluate_t algo;
switch(options->estimatorMAP) {
case INFER_MAP_PLM:
algo = PLMNegLogPosterior;
break;
case INFER_MAP_PLM_GAPREDUCE:
algo = PLMNegLogPosteriorGapReduce;
break;
case INFER_MAP_PLM_BLOCK:
algo = PLMNegLogPosteriorBlock;
break;
case INFER_MAP_PLM_DROPOUT:
algo = PLMNegLogPosteriorDO;
break;
default:
algo = PLMNegLogPosterior;
}
if (options->zeroAPC == 1) fprintf(stderr,
"Estimating coupling hyperparameters le = 1/2 inverse variance\n");
/* Problem instance in void array */
void *d[3] = {(void *)ali, (void *)options, (void *)lambdas};
if (options->sgd == 1) {
/* Scale hyperparams for minibatch */
numeric_t scale = (numeric_t) options->sgdBatchSize / ali->nEff;
options->lambdaGroup *= scale;
for (int i = 0; i < ali->nSites; i++) lambdaHi(i) *= scale;
for (int i = 0; i < ali->nSites - 1; i++)
for (int j = i + 1; j < ali->nSites; j++)
lambdaEij(i, j) *= scale;
/* SGD optimization */
numeric_t crit = 0.01;
void *d[4] = {(void *)ali, (void *)options, (void *)lambdas, (void *) algo};
SGDOptimize(SGDWrapperPLM, d, x, ali->nParams, options->maxIter, crit);
/* Unscale hyperparams for minibatch */
numeric_t invScale = ali->nEff / (numeric_t) options->sgdBatchSize;
options->lambdaGroup *= invScale;
for (int i = 0; i < ali->nSites; i++) lambdaHi(i) *= invScale;
for (int i = 0; i < ali->nSites - 1; i++)
for (int j = i + 1; j < ali->nSites; j++)
lambdaEij(i, j) *= invScale;
} else {
/* L-BFGS optimization */
int ret = 0;
lbfgsfloatval_t fx;
ret = lbfgs(ali->nParams, x, &fx, algo, ReportProgresslBFGS,
(void*)d, ¶m);
fprintf(stderr, "Gradient optimization: %s\n", LBFGSErrorString(ret));
}
/* Optionally re-estimate parameters with adjusted hyperparameters */
if (options->zeroAPC == 1) {
/* Form new priors on the variances */
ZeroAPCPriors(ali, options, lambdas, x);
/* Reinitialize coupling parameters */
for (int i = 0; i < ali->nSites - 1; i++)
for (int j = i + 1; j < ali->nSites; j++)
for (int ai = 0; ai < ali->nCodes; ai++)
for (int aj = 0; aj < ali->nCodes; aj++)
xEij(i, j, ai, aj) = 0.0;
/* Iterate estimation with new hyperparameter estimates */
options->zeroAPC = 2;
lbfgsfloatval_t fx2;
int ret2 = lbfgs(ali->nParams, x, &fx2, algo,
ReportProgresslBFGS, (void*)d, ¶m);
fprintf(stderr, "Gradient optimization: %s\n", LBFGSErrorString(ret2));
}
}
void SGDOptimize(gradfun_t grad, void *data, numeric_t *x, const int n,
const int maxIter, const numeric_t crit) {
/* Opitimize an objective function by Stochastic Gradient Descent (Adam)
Arguments:
grad gradient of objective
data pointer to data
x estimated parameters (length n)
n number of parameters
eps learning rate
maxIter maximum number of iterations
crit stop when ||grad|| / ||x|| < crit
*/
// numeric_t ALPHA0 = 0.001;
// numeric_t ALPHAT = 0.00001;
numeric_t BETA1 = 0.9;
numeric_t BETA2 = 0.99;
numeric_t EPSILON = 1E-8;
numeric_t *g = (numeric_t *) malloc(n * sizeof(numeric_t));
numeric_t criterion = crit + 1.0;
/* Begin profiling */
struct timeval start;
gettimeofday(&start, NULL);
/* Initialize estimates of first and second moments of the gradient */
numeric_t *meanX = (numeric_t *) malloc(n * sizeof(numeric_t));
numeric_t *meanG = (numeric_t *) malloc(n * sizeof(numeric_t));
numeric_t *squareG = (numeric_t *) malloc(n * sizeof(numeric_t));
for (int i = 0; i < n; i++) meanX[i] = 0;
for (int i = 0; i < n; i++) meanG[i] = 0;
for (int i = 0; i < n; i++) squareG[i] = 0;
/* Optimization loop */
int t = 1;
do {
/* Estimate the gradient */
for (int i = 0; i < n; i++) g[i] = 0;
numeric_t f = grad(data, x, g, n);
/* Update estimates of moments */
for (int i = 0; i < n; i++)
meanG[i] = BETA1 * meanG[i] + (1.0 - BETA1) * g[i];
for (int i = 0; i < n; i++)
squareG[i] = BETA2 * squareG[i] + (1.0 - BETA2) * g[i] * g[i];
/* Update Q with Adam learning rates */
// numeric_t schedule = ALPHA;
// numeric_t frac = (numeric_t) t / (numeric_t) maxIter;
// frac = floor(frac * 5) / 5.;
// numeric_t schedule = exp((1 - frac) * log(ALPHA0) + frac * log(ALPHAT));
// Anneal strategy #2
numeric_t schedule = 0.01 * pow(0.5, (t / 50));
// numeric_t schedule = 0.01;
numeric_t alpha = schedule
* sqrt(1.0 - pow(BETA2, (numeric_t) t))
/ (1.0 - pow(BETA1, (numeric_t) t));
for (int i = 0; i < n; i++)
x[i] -= meanG[i] * alpha / (sqrt(squareG[i]) + EPSILON);
/* Update Polyak average */
for (int i = 0; i < n; i++)
meanX[i] = BETA1 * meanX[i] + (1 - BETA1) * x[i];
/* Stopping criterion: ||grad(params)|| / ||params|| */
numeric_t paramNorm = 1E-6;
for (int i = 0; i < n; i++) paramNorm += fabs(x[i]) / (numeric_t) n;
numeric_t gradNorm = 1E-6;
for (int i = 0; i < n; i++)
gradNorm += fabs(meanG[i]) / (numeric_t) n;
criterion = gradNorm;
if (t == 1)
fprintf(stderr, "iter\ttime\tobj\t|x|\t|g|\tcrit\n");
fprintf(stderr, "%d\t%.1f\t%.1f\t%.1f\t%.1f\t%.1f\n",
t, ElapsedTime(&start), f, paramNorm, gradNorm, criterion);
t++;
} while (t <= maxIter && criterion > crit);
// for (int i = 0; i < n; i++) x[i] = meanX[i] / ((numeric_t) t - 1);
for (int i = 0; i < n; i++) x[i] = meanX[i];
free(meanX);
free(meanG);
free(squareG);
free(g);
}
numeric_t SGDWrapperPLM(void *data, const numeric_t *x, numeric_t *g,
const int n) {
/* Wrap objective function for L-BFGS to support
minibatched Stochastic Gradient Descent (SGD)
*/
void **d = (void **)data;
alignment_t *ali = (alignment_t *) d[0];
options_t *options = (options_t *) d[1];
numeric_t *lambdas = (numeric_t *) d[2];
lbfgs_evaluate_t lbfgsfun = (lbfgs_evaluate_t) d[3];
/* Shallow copy alignment and options */
alignment_t *aliBatch = (alignment_t *) malloc(sizeof(alignment_t));
options_t *optionsBatch = (options_t *) malloc(sizeof(options_t));
*aliBatch = *ali;
*optionsBatch = *options;
/* Build CDF */
numeric_t *CDF = (numeric_t *) malloc(sizeof(numeric_t) * ali->nSeqs);
numeric_t weightSum = 0;
for (int i = 0; i < ali->nSeqs; i++) weightSum += ali->weights[i];
CDF[0] = ali->weights[0] / weightSum;
for (int i = 1; i < ali->nSeqs; i++) CDF[i] = CDF[i-1] + ali->weights[i] / weightSum;
/* Sample a batch of sequences */
int batchSize = options->sgdBatchSize;
int *indices = (int *) malloc(sizeof(int) * batchSize);
numeric_t *u = (numeric_t *) malloc(sizeof(numeric_t) * batchSize);
for (int i = 0; i < batchSize; i++) indices[i] = -1;
for (int i = 0; i < batchSize; i++) u[i] = (numeric_t) genrand_real3();
for (int s = 0; s < ali->nSeqs; s++)
for (int i = 0; i < batchSize; i++)
if (indices[i] < 0 && u[i] <= CDF[s]) indices[i] = s;
for (int i = 0; i < batchSize; i++)
if (indices[i] < 0) indices[i] = batchSize - 1;
/* Clone mini-alignment and weights */
aliBatch->sequences =
(letter_t *) malloc(sizeof(letter_t) * batchSize * ali->nSites);
aliBatch->weights =
(numeric_t *) malloc(sizeof(numeric_t) * batchSize);
for (int i = 0; i < batchSize; i++)
aliBatch->weights[i] = 1.0;
for (int i = 0; i < batchSize; i++)
for (int j = 0; j < ali->nSites; j++)
aliBatch->sequences[j + i * ali->nSites] = seq(indices[i], j);
free(u);
free(CDF);
free(indices);
aliBatch->nSeqs = batchSize;
/* Run the wrapped objective */
void *instance[3] = {(void *)aliBatch, (void *)optionsBatch, (void *)lambdas};
numeric_t f = lbfgsfun(instance, x, g, n, 0);
/* Rescale */
numeric_t scale = weightSum / (numeric_t) batchSize;
f *= scale;
for (int i = 0; i < n; i++) g[i] *= scale;
/* Clean up */
free(aliBatch->sequences);
free(aliBatch->weights);
free(aliBatch);
free(optionsBatch);
return f;
}
static lbfgsfloatval_t PLMNegLogPosterior(void *instance,
const lbfgsfloatval_t *x, lbfgsfloatval_t *g, const int n,
const lbfgsfloatval_t step) {
/* Compute the the negative log posterior, which is the negative
penalized log-(pseudo)likelihood and the objective for MAP inference
*/
void **d = (void **)instance;
alignment_t *ali = (alignment_t *) d[0];
options_t *options = (options_t *) d[1];
numeric_t *lambdas = (numeric_t *) d[2];
/* Initialize log-likelihood and gradient */
lbfgsfloatval_t fx = 0.0;
for (int i = 0; i < ali->nParams; i++) g[i] = 0;
/* Negative log-pseudolikelihood */
#pragma omp parallel for
for (int i = 0; i < ali->nSites; i++) {
numeric_t *H = (numeric_t *) malloc(ali->nCodes * sizeof(numeric_t));
numeric_t *P = (numeric_t *) malloc(ali->nCodes * sizeof(numeric_t));
numeric_t siteFx = 0.0;
/* Reshape site parameters and gradient into local blocks */
numeric_t *Xi = (numeric_t *) malloc(ali->nCodes * ali->nCodes
* ali->nSites * sizeof(numeric_t));
for (int j = 0; j < i; j++)
for (int a = 0; a < ali->nCodes; a++)
for (int b = 0; b < ali->nCodes; b++)
siteE(j, a, b) = xEij(i, j, a, b);
for (int j = i + 1; j < ali->nSites; j++)
for (int a = 0; a < ali->nCodes; a++)
for (int b = 0; b < ali->nCodes; b++)
siteE(j, a, b) = xEij(i, j, a, b);
for (int a = 0; a < ali->nCodes; a++) siteH(i, a) = xHi(i, a);
numeric_t *Di = (numeric_t *) malloc(ali->nCodes * ali->nCodes
* ali->nSites * sizeof(numeric_t));
for (int d = 0; d < ali->nCodes * ali->nCodes * ali->nSites; d++)
Di[d] = 0.0;
/* Site negative conditional log likelihoods */
for (int s = 0; s < ali->nSeqs; s++) {
/* Compute potentials */
for (int a = 0; a < ali->nCodes; a++) H[a] = siteH(i, a);
for (int j = 0; j < i; j++)
for (int a = 0; a < ali->nCodes; a++)
H[a] += siteE(j, a, seq(s, j));
for (int j = i + 1; j < ali->nSites; j++)
for (int a = 0; a < ali->nCodes; a++)
H[a] += siteE(j, a, seq(s, j));
/* Conditional distribution given sequence background */
numeric_t scale = H[0];
for (int a = 1; a < ali->nCodes; a++)
scale = (scale >= H[a] ? scale : H[a]);
for (int a = 0; a < ali->nCodes; a++) P[a] = exp(H[a] - scale);
numeric_t Z = 0;
for (int a = 0; a < ali->nCodes; a++) Z += P[a];
numeric_t Zinv = 1.0 / Z;
for (int a = 0; a < ali->nCodes; a++) P[a] *= Zinv;
/* Log-likelihood contributions are scaled by sequence weight */
numeric_t w = ali->weights[s];
siteFx -= w * log(P[seq(s, i)]);
/* Field gradient */
siteDH(i, seq(s, i)) -= w;
for (int a = 0; a < ali->nCodes; a++)
siteDH(i, a) -= -w * P[a];
/* Couplings gradient */
int ix = seq(s, i);
for (int j = 0; j < i; j++)
siteDE(j, ix, seq(s, j)) -= w;
for (int j = i + 1; j < ali->nSites; j++)
siteDE(j, ix, seq(s, j)) -= w;
for (int j = 0; j < i; j++)
for (int a = 0; a < ali->nCodes; a++)
siteDE(j, a, seq(s, j)) -= -w * P[a];
for (int j = i + 1; j < ali->nSites; j++)
for (int a = 0; a < ali->nCodes; a++)
siteDE(j, a, seq(s, j)) -= -w * P[a];
}
/* Contribute local loglk and gradient to global */
#pragma omp critical
{
fx += siteFx;
for (int j = 0; j < i; j++)
for (int a = 0; a < ali->nCodes; a++)
for (int b = 0; b < ali->nCodes; b++)
dEij(i, j, a, b) += siteDE(j, a, b);
for (int j = i + 1; j < ali->nSites; j++)
for (int a = 0; a < ali->nCodes; a++)
for (int b = 0; b < ali->nCodes; b++)
dEij(i, j, a, b) += siteDE(j, a, b);
for (int a = 0; a < ali->nCodes; a++) dHi(i, a) += siteDH(i, a);
free(Xi);
free(Di);
}
free(H);
free(P);
}
ali->negLogLk = fx;
/* Gaussian priors */
for (int i = 0; i < ali->nSites; i++)
for (int ai = 0; ai < ali->nCodes; ai++) {
dHi(i, ai) += lambdaHi(i) * 2.0 * xHi(i, ai);
fx += lambdaHi(i) * xHi(i, ai) * xHi(i, ai);
}
for (int i = 0; i < ali->nSites-1; i++)
for (int j = i + 1; j < ali->nSites; j++)
for (int ai = 0; ai < ali->nCodes; ai++)
for (int aj = 0; aj < ali->nCodes; aj++) {
dEij(i, j, ai, aj) += lambdaEij(i, j)
* 2.0 * xEij(i, j, ai, aj);
fx += lambdaEij(i, j)
* xEij(i, j, ai, aj) * xEij(i, j, ai, aj);
}
fx = PostCondition(x, g, fx, ali, options);
return fx;
}
static lbfgsfloatval_t PLMNegLogPosteriorGapReduce(void *instance,
const lbfgsfloatval_t *x, lbfgsfloatval_t *g, const int n,
const lbfgsfloatval_t step) {
/* Compute the the negative log posterior, which is the negative
penalized log-(pseudo)likelihood and the objective for MAP inference
*/
void **d = (void **)instance;
alignment_t *ali = (alignment_t *) d[0];
options_t *options = (options_t *) d[1];
numeric_t *lambdas = (numeric_t *) d[2];
/* Initialize log-likelihood and gradient */
lbfgsfloatval_t fx = 0.0;
for (int i = 0; i < ali->nParams; i++) g[i] = 0;
/* Negative log-pseudolikelihood */
#pragma omp parallel for
for (int i = 0; i < ali->nSites; i++) {
numeric_t *H = (numeric_t *) malloc(ali->nCodes * sizeof(numeric_t));
numeric_t *P = (numeric_t *) malloc(ali->nCodes * sizeof(numeric_t));
numeric_t siteFx = 0.0;
/* Reshape site parameters and gradient into local blocks */
numeric_t *Xi = (numeric_t *) malloc(ali->nCodes * ali->nCodes
* ali->nSites * sizeof(numeric_t));
for (int j = 0; j < i; j++)
for (int a = 0; a < ali->nCodes; a++)
for (int b = 0; b < ali->nCodes; b++)
siteE(j, a, b) = xEij(i, j, a, b);
for (int j = i + 1; j < ali->nSites; j++)
for (int a = 0; a < ali->nCodes; a++)
for (int b = 0; b < ali->nCodes; b++)
siteE(j, a, b) = xEij(i, j, a, b);
for (int a = 0; a < ali->nCodes; a++) siteH(i, a) = xHi(i, a);
numeric_t *Di = (numeric_t *) malloc(ali->nCodes * ali->nCodes
* ali->nSites * sizeof(numeric_t));
for (int d = 0; d < ali->nCodes * ali->nCodes * ali->nSites; d++)
Di[d] = 0.0;
/* Site negative conditional log likelihoods */
for (int s = 0; s < ali->nSeqs; s++) {
/* Only ungapped sites are considered in the model */
if (seq(s, i) >= 0) {
/* Compute potentials */
for (int a = 0; a < ali->nCodes; a++) H[a] = siteH(i, a);
for (int j = 0; j < i; j++)
for (int a = 0; a < ali->nCodes; a++)
if (seq(s, j) >= 0)
H[a] += siteE(j, a, seq(s, j));
for (int j = i + 1; j < ali->nSites; j++)
for (int a = 0; a < ali->nCodes; a++)
if (seq(s, j) >= 0)
H[a] += siteE(j, a, seq(s, j));
/* Conditional distribution given sequence background */
numeric_t scale = H[0];
for (int a = 1; a < ali->nCodes; a++)
scale = (scale >= H[a] ? scale : H[a]);
for (int a = 0; a < ali->nCodes; a++) P[a] = exp(H[a] - scale);
numeric_t Z = 0;
for (int a = 0; a < ali->nCodes; a++) Z += P[a];
numeric_t Zinv = 1.0 / Z;
for (int a = 0; a < ali->nCodes; a++) P[a] *= Zinv;
/* Log-likelihood contributions are scaled by sequence weight */
numeric_t w = ali->weights[s];
siteFx -= w * log(P[seq(s, i)]);
/* Field gradient */
siteDH(i, seq(s, i)) -= w;
for (int a = 0; a < ali->nCodes; a++)
siteDH(i, a) -= -w * P[a];
/* Couplings gradient */
int ix = seq(s, i);
for (int j = 0; j < i; j++)
if (seq(s, j) >= 0)
siteDE(j, ix, seq(s, j)) -= w;
for (int j = i + 1; j < ali->nSites; j++)
if (seq(s, j) >= 0)
siteDE(j, ix, seq(s, j)) -= w;
for (int j = 0; j < i; j++)
if (seq(s, j) >= 0)
for (int a = 0; a < ali->nCodes; a++)
siteDE(j, a, seq(s, j)) -= -w * P[a];
for (int j = i + 1; j < ali->nSites; j++)
if (seq(s, j) >= 0)
for (int a = 0; a < ali->nCodes; a++)
siteDE(j, a, seq(s, j)) -= -w * P[a];
}
}
/* Contribute local loglk and gradient to global */
#pragma omp critical
{
fx += siteFx;
for (int j = 0; j < i; j++)
for (int a = 0; a < ali->nCodes; a++)
for (int b = 0; b < ali->nCodes; b++)
dEij(i, j, a, b) += siteDE(j, a, b);
for (int j = i + 1; j < ali->nSites; j++)
for (int a = 0; a < ali->nCodes; a++)
for (int b = 0; b < ali->nCodes; b++)
dEij(i, j, a, b) += siteDE(j, a, b);
for (int a = 0; a < ali->nCodes; a++) dHi(i, a) += siteDH(i, a);
free(Xi);
free(Di);
}
free(H);
free(P);
}
ali->negLogLk = fx;
/* Gaussian priors */
for (int i = 0; i < ali->nSites; i++)
for (int ai = 0; ai < ali->nCodes; ai++) {
dHi(i, ai) += lambdaHi(i) * 2.0 * xHi(i, ai);
fx += lambdaHi(i) * xHi(i, ai) * xHi(i, ai);
}
for (int i = 0; i < ali->nSites-1; i++)
for (int j = i + 1; j < ali->nSites; j++)
for (int ai = 0; ai < ali->nCodes; ai++)
for (int aj = 0; aj < ali->nCodes; aj++) {
dEij(i, j, ai, aj) += lambdaEij(i, j)
* 2.0 * xEij(i, j, ai, aj);
fx += lambdaEij(i, j)
* xEij(i, j, ai, aj) * xEij(i, j, ai, aj);
}
fx = PostCondition(x, g, fx, ali, options);
return fx;
}
static lbfgsfloatval_t PLMNegLogPosteriorBlock(void *instance,
const lbfgsfloatval_t *x, lbfgsfloatval_t *g, const int n,
const lbfgsfloatval_t step) {
/* Compute the the negative log posterior, which is the negative
penalized log-(pseudo)likelihood and the objective for MAP inference
*/
void **d = (void **)instance;
alignment_t *ali = (alignment_t *) d[0];
options_t *options = (options_t *) d[1];
numeric_t *lambdas = (numeric_t *) d[2];
/* Initialize log-likelihood and gradient */
lbfgsfloatval_t fx = 0.0;
for (int i = 0; i < ali->nParams; i++) g[i] = 0;
/* Block fields hi */
numeric_t *hi = (numeric_t *)
malloc(ali->nSites * ali->nCodes * sizeof(numeric_t));
numeric_t *gHi = (numeric_t *)
malloc(ali->nSites * ali->nCodes * sizeof(numeric_t));
for (int i = 0; i < ali->nSites; i++)
for (int ai = 0; ai < ali->nCodes; ai++) Hi(i, ai) = xHi(i, ai);
for (int i = 0; i < ali->nSites * ali->nCodes; i++) gHi[i] = 0;
/* Block couplings eij */
numeric_t *eij = (numeric_t *) malloc(ali->nSites * ali->nSites
* ali->nCodes * ali->nCodes * sizeof(numeric_t));
numeric_t *gEij = (numeric_t *) malloc(ali->nSites * ali->nSites
* ali->nCodes * ali->nCodes * sizeof(numeric_t));
for (int i = 0; i < ali->nSites * ali->nSites * ali->nCodes * ali->nCodes;
i++) eij[i] = 0.0;
for (int i = 0; i < ali->nSites * ali->nSites * ali->nCodes * ali->nCodes;
i++) gEij[i] = 0.0;
for (int i = 0; i < ali->nSites - 1; i++)
for (int j = i + 1; j < ali->nSites; j++)
for (int ai = 0; ai < ali->nCodes; ai++)
for (int aj = 0; aj < ali->nCodes; aj++)
Eij(j, aj, i, ai) = Eij(i, ai, j, aj) = xEij(i, j, ai, aj);
/* Negative log-pseudolikelihood */
for (int s = 0; s < ali->nSeqs; s++) {
/* Form potential for conditional log likelihoods at every site */
numeric_t *H = (numeric_t *)
malloc(ali->nCodes * ali->nSites * sizeof(numeric_t));
numeric_t *Z = (numeric_t *) malloc(ali->nSites * sizeof(numeric_t));
/* Initialize potentials with fields */
// memcpy(H, hi, ali->nSites * ali->nCodes * sizeof(numeric_t));
for(int jx = 0; jx < ali->nSites * ali->nCodes; jx++) H[jx] = hi[jx];
/* Contribute coupling block due to i, ai */
for (int i = 0; i < ali->nSites; i++) {
const letter_t ai = seq(s, i);
const numeric_t *jB = &(Eij(i, ai, 0, 0));
for(int jx = 0; jx < ali->nSites * ali->nCodes; jx++)
H[jx] += jB[jx];
}
/* Conditional log likelihoods */
for (int i = 0; i < ali->nSites * ali->nCodes; i++) H[i] = exp(H[i]);
for (int i = 0; i < ali->nSites; i++) Z[i] = 0;
for (int i = 0; i < ali->nSites; i++)
for (int ai = 0; ai < ali->nSites; ai++) Z[i] += Hp(i, ai);
for (int i = 0; i < ali->nSites; i++)
for (int ai = 0; ai < ali->nSites; ai++) Hp(i, ai) /= Z[i];
numeric_t seqFx = 0;
for (int i = 0; i < ali->nSites; i++)
seqFx -= ali->weights[s] * log(Hp(i, seq(s, i)));
for(int jx = 0; jx < ali->nSites * ali->nCodes; jx++)
H[jx] *= -ali->weights[s];
for (int i = 0; i < ali->nSites; i++)
gHi(i, seq(s, i)) -= ali->weights[s];
for(int jx = 0; jx < ali->nSites * ali->nCodes; jx++) gHi[jx] -= H[jx];
for (int i = 0; i < ali->nSites - 1; i++)
for (int j = i; j < ali->nSites; j++)
gEij(i, seq(s, i), j, seq(s, j)) -= ali->weights[s];
for (int i = 0; i < ali->nSites; i++) {
const letter_t ai = seq(s, i);
numeric_t *jgBlock = &(gEij(i, ai, 0, 0));
for (int jx = 0; jx < ali->nSites * ali->nCodes; jx++)
jgBlock[jx] -= H[jx];
}
free(H);
free(Z);
fx += seqFx;
}
for (int i = 0; i < ali->nSites; i++)
for (int ai = 0; ai < ali->nCodes; ai++)
dHi(i, ai) += gHi(i, ai);
for (int i = 0; i < ali->nSites - 1; i++)
for (int j = i + 1; j < ali->nSites; j++)
for (int ai = 0; ai < ali->nCodes; ai++)
for (int aj = 0; aj < ali->nCodes; aj++)
dEij(i, j, ai, aj) += gEij(j, aj, i, ai) + gEij(i, ai, j, aj);
free(hi);
free(gHi);
free(eij);
free(gEij);
ali->negLogLk = fx;
/* Gaussian priors */
for (int i = 0; i < ali->nSites; i++)
for (int ai = 0; ai < ali->nCodes; ai++) {
dHi(i, ai) += lambdaHi(i) * 2.0 * xHi(i, ai);
fx += lambdaHi(i) * xHi(i, ai) * xHi(i, ai);
}
for (int i = 0; i < ali->nSites-1; i++)
for (int j = i + 1; j < ali->nSites; j++)
for (int ai = 0; ai < ali->nCodes; ai++)
for (int aj = 0; aj < ali->nCodes; aj++) {
dEij(i, j, ai, aj) += lambdaEij(i, j)
* 2.0 * xEij(i, j, ai, aj);
fx += lambdaEij(i, j)
* xEij(i, j, ai, aj) * xEij(i, j, ai, aj);
}
fx = PostCondition(x, g, fx, ali, options);
return fx;
}
static lbfgsfloatval_t PLMNegLogPosteriorDO(void *instance,
const lbfgsfloatval_t *x, lbfgsfloatval_t *g, const int n,
const lbfgsfloatval_t step) {
/* Compute the the negative log posterior, which is the negative
penalized log-(pseudo)likelihood and the objective for MAP inference
*/
void **d = (void **)instance;
alignment_t *ali = (alignment_t *) d[0];
options_t *options = (options_t *) d[1];
numeric_t *lambdas = (numeric_t *) d[2];
/* Initialize log-likelihood and gradient */
lbfgsfloatval_t fx = 0.0;
for (int i = 0; i < ali->nParams; i++) g[i] = 0;
numeric_t *H = (numeric_t *) malloc(ali->nCodes * sizeof(numeric_t));
numeric_t *P = (numeric_t *) malloc(ali->nCodes * sizeof(numeric_t));
int *drop_mask = (int *) malloc(ali->nParams * sizeof(int));
for (int s = 0; s < ali->nSeqs; s++) {
/* Generate random bit mask over parameters */
for (int p = 0; p < ali->nParams; p ++)
drop_mask[p] = (int) rand() % 2;
/* Pseudolikelihood objective */
for (int i = 0; i < ali->nSites; i++) {
for (int a = 0; a < ali->nCodes; a++) H[a] = bitHi(i, a)
* xHi(i, a);
for (int a = 0; a < ali->nCodes; a++)
for (int j = 0; j < i; j++)
H[a] += bitEij(i, j, a, seq(s, j))
* xEij(i, j, a, seq(s, j));
for (int a = 0; a < ali->nCodes; a++)
for (int j = i + 1; j < ali->nSites; j++)
H[a] += bitEij(i, j, a, seq(s, j))
* xEij(i, j, a, seq(s, j));
/* Compute distribution from potential */
for (int a = 0; a < ali->nCodes; a++) P[a] = exp(H[a]);
numeric_t Z = 0;
for (int a = 0; a < ali->nCodes; a++) Z += P[a];
numeric_t Zinv = 1.0 / Z;
for (int a = 0; a < ali->nCodes; a++) P[a] *= Zinv;
/* Log-likelihood contributions */
fx -= ali->weights[s] * log(P[seq(s, i)]);
/* Field gradient */
dHi(i, seq(s, i)) -= bitHi(i, seq(s, i)) * ali->weights[s];
for (int a = 0; a < ali->nCodes; a++)
dHi(i, a) -= -bitHi(i, a) * ali->weights[s] * P[a];
/* Couplings gradient */
for (int j = 0; j < i; j++)
dEij(i, j, seq(s, i), seq(s, j)) -=
bitEij(i, j, seq(s, i), seq(s, j)) * ali->weights[s];
for (int j = i + 1; j < ali->nSites; j++)
dEij(i, j, seq(s, i), seq(s, j)) -=
bitEij(i, j, seq(s, i), seq(s, j)) * ali->weights[s];
for (int j = 0; j < i; j++)
for (int a = 0; a < ali->nCodes; a++)
dEij(i, j, a, seq(s, j)) -=
-bitEij(i, j, a, seq(s, j)) * ali->weights[s] * P[a];
for (int j = i + 1; j < ali->nSites; j++)
for (int a = 0; a < ali->nCodes; a++)
dEij(i, j, a, seq(s, j)) -=
-bitEij(i, j, a, seq(s, j)) * ali->weights[s] * P[a];
}
}
free(H);
free(P);
free(drop_mask);
ali->negLogLk = fx;
/* Gaussian priors */
for (int i = 0; i < ali->nSites; i++)
for (int ai = 0; ai < ali->nCodes; ai++) {
dHi(i, ai) += lambdaHi(i) * 2.0 * xHi(i, ai);
fx += lambdaHi(i) * xHi(i, ai) * xHi(i, ai);
}
for (int i = 0; i < ali->nSites-1; i++)
for (int j = i + 1; j < ali->nSites; j++)
for (int ai = 0; ai < ali->nCodes; ai++)
for (int aj = 0; aj < ali->nCodes; aj++) {
dEij(i, j, ai, aj) += lambdaEij(i, j)
* 2.0 * xEij(i, j, ai, aj);
fx += lambdaEij(i, j)
* xEij(i, j, ai, aj) * xEij(i, j, ai, aj);
}
fx = PostCondition(x, g, fx, ali, options);
return fx;
}
static int ReportProgresslBFGS(void *instance, const lbfgsfloatval_t *x,
const lbfgsfloatval_t *g, const lbfgsfloatval_t fx,
const lbfgsfloatval_t xnorm, const lbfgsfloatval_t gnorm,
const lbfgsfloatval_t step, int n, int k, int ls) {
void **d = (void **)instance;
alignment_t *ali = (alignment_t *)d[0];
/* Compute norms of relevant parameters */
lbfgsfloatval_t hNorm = 0.0, eNorm = 0.0, hGNorm = 0.0, eGNorm = 0.0;
for (int i = 0; i < ali->nSites * ali->nCodes; i++)
hNorm += x[i]*x[i];
for (int i = 0; i < ali->nSites * ali->nCodes; i++)
hGNorm += g[i]*g[i];
for (int i = ali->nSites * ali->nCodes; i < ali->nParams; i++)
eNorm += x[i]*x[i];
for (int i = ali->nSites * ali->nCodes; i < ali->nParams; i++)
eGNorm += g[i]*g[i];
hNorm = sqrt(hNorm);
hGNorm = sqrt(hGNorm);
eNorm = sqrt(eNorm);
eGNorm = sqrt(eGNorm);
/* Retrieve elapsed time */
static struct timeval now;
gettimeofday(&now, NULL);
if (now.tv_usec < ali->start.tv_usec) {
int nsec = (ali->start.tv_usec - now.tv_usec) / 1000000 + 1;
ali->start.tv_usec -= 1000000 * nsec;
ali->start.tv_sec += nsec;
}
if (now.tv_usec - ali->start.tv_usec > 1000000) {
int nsec = (now.tv_usec - ali->start.tv_usec) / 1000000;
ali->start.tv_usec += 1000000 * nsec;
ali->start.tv_sec -= nsec;
}
numeric_t elapsed = (numeric_t) (now.tv_sec - ali->start.tv_sec)
+ ((numeric_t) (now.tv_usec - ali->start.tv_usec)) / 1E6;
if (k == 1) fprintf(stderr,
"iter\ttime\tcond\tfx\t-loglk"
"\t||h||\t||e||\n");
fprintf(stderr, "%d\t%.1f\t%.2f\t%.1f\t%.1f\t%.1f\t%.1f\n",
k, elapsed, gnorm / xnorm, fx, ali->negLogLk, hNorm, eNorm);
return 0;
}
void PreCondition(const lbfgsfloatval_t *x, lbfgsfloatval_t *g, alignment_t *ali, options_t *options) {
/* Currently empty */
}
lbfgsfloatval_t PostCondition(const lbfgsfloatval_t *x, lbfgsfloatval_t *g, lbfgsfloatval_t fx, alignment_t *ali, options_t *options) {
if (options->zeroAPC == 1)
for (int i = 0; i < ali->nSites; i++)
for (int ai = 0; ai < ali->nCodes; ai++)
dHi(i, ai) = 0.0;
/* Group (L1/L2) regularization */
if (options->lambdaGroup > 0)
for (int i = 0; i < ali->nSites - 1; i++)
for (int j = i + 1; j < ali->nSites; j++) {
double l2 = REGULARIZATION_GROUP_EPS;
for (int ai = 0; ai < ali->nCodes; ai++)
for (int aj = 0; aj < ali->nCodes; aj++)
l2 += xEij(i, j, ai, aj) * xEij(i, j, ai, aj);
double l1 = sqrt(l2);
fx += options->lambdaGroup * l1;
for (int ai = 0; ai < ali->nCodes; ai++)
for (int aj = 0; aj < ali->nCodes; aj++)
dEij(i, j, ai, aj) += options->lambdaGroup * xEij(i, j, ai, aj) / l1;
}
return fx;
}
void ZeroAPCPriors(alignment_t *ali, options_t *options, numeric_t *lambdas,
lbfgsfloatval_t *x) {
/* Compute the variances of the couplings for each pair */
for (int i = 0; i < ali->nSites - 1; i++)
for (int j = i + 1; j < ali->nSites; j++) {
/* Mean(eij) over ai, aj */
numeric_t mean = 0.0;
for (int ai = 0; ai < ali->nCodes; ai++)
for (int aj = 0; aj < ali->nCodes; aj++)
mean += xEij(i, j, ai, aj);
mean *= 1.0 / ((numeric_t) ali->nCodes * ali->nCodes);
/* Var(eij) over ai, aj */
numeric_t ssq = 0.0;
for (int ai = 0; ai < ali->nCodes; ai++)
for (int aj = 0; aj < ali->nCodes; aj++)
ssq += (xEij(i, j, ai, aj) - mean)
* (xEij(i, j, ai, aj) - mean);
/* Use N rather than N-1 since N has better MSE */
numeric_t var = ssq / ((numeric_t) (ali->nCodes * ali->nCodes));
lambdaEij(i, j) = var;
}
/* Determine the site-wise statistics of the variances */
numeric_t nPairs = ((numeric_t) ((ali->nSites) * (ali->nSites - 1))) / 2.0;
numeric_t V_avg = 0.0;
numeric_t *V_pos_avg = (numeric_t *) malloc(ali->nSites * sizeof(numeric_t));
for (int i = 0; i < ali->nSites; i++) {
V_pos_avg[i] = 0.0;
}
for (int i = 0; i < ali->nSites - 1; i++) {
for (int j = i + 1; j < ali->nSites; j++) {
V_pos_avg[i] += lambdaEij(i, j) / (numeric_t) (ali->nSites - 1);
V_pos_avg[j] += lambdaEij(i, j) / (numeric_t) (ali->nSites - 1);
V_avg += lambdaEij(i, j) / nPairs;
}
}
/* Remove the first component of the variances */
for (int i = 0; i < ali->nSites - 1; i++)
for (int j = i + 1; j < ali->nSites; j++)
lambdaEij(i, j) =
lambdaEij(i, j) - V_pos_avg[i] * V_pos_avg[j] / V_avg;
/* Transform and truncate variances into lambda hyperparameters */
numeric_t pcount = 0.0;
numeric_t psum = 0.0;
numeric_t inbounds = 0;
numeric_t min = LAMBDA_J_MAX;
numeric_t max = LAMBDA_J_MIN;
for (int i = 0; i < ali->nSites - 1; i++) {
for (int j = i + 1; j < ali->nSites; j++) {
/* Lambda coefficients are 1/2 the inverse variance */
if (lambdaEij(i, j) > 0) {
lambdaEij(i, j) = 1.0 / (2.0 * lambdaEij(i, j));
psum += lambdaEij(i, j);
pcount += 1.0;
} else {
lambdaEij(i, j) = LAMBDA_J_MAX + 1.0;
}
/* Truncate lambda for numerical stability */
if (lambdaEij(i, j) >= LAMBDA_J_MIN && lambdaEij(i, j) <= LAMBDA_J_MAX)
inbounds += 1.0 / (numeric_t) ((ali->nSites)*(ali->nSites - 1) / 2.0);
if (lambdaEij(i, j) < 0 || !isfinite(lambdaEij(i, j)))
lambdaEij(i, j) = LAMBDA_J_MAX;
if (lambdaEij(i, j) < LAMBDA_J_MIN) lambdaEij(i, j) = LAMBDA_J_MIN;
if (lambdaEij(i, j) > LAMBDA_J_MAX) lambdaEij(i, j) = LAMBDA_J_MAX;
/* Track extremes */
if (lambdaEij(i, j) > max) max = lambdaEij(i, j);
if (lambdaEij(i, j) < min) min = lambdaEij(i, j);
}
}
fprintf(stderr, "Raw coupling hyperparameter statistics:\n"
"\tMean positive lambda: %f\n"
"\tPercent of ij's positive: %f\n"
"\tPercent in bounds (%f < L < %f): %f\n",
psum / pcount,
pcount / nPairs,
min, max, inbounds);
}
const char *LBFGSErrorString(int ret) {
const char *p;
switch(ret) {
case LBFGSERR_UNKNOWNERROR:
p = "UNKNOWNERROR";
break;
/** Logic error. */
case LBFGSERR_LOGICERROR:
p = "LOGICERROR";
break;
/** Insufficient memory. */
case LBFGSERR_OUTOFMEMORY:
p = "OUTOFMEMORY";
break;
/** The minimization process has been canceled. */
case LBFGSERR_CANCELED:
p = "CANCELED";
break;
/** Invalid number of variables specified. */
case LBFGSERR_INVALID_N:
p = "INVALID_N";
break;
/** Invalid number of variables (for SSE) specified. */
case LBFGSERR_INVALID_N_SSE:
p = "INVALID_N_SSE";
break;
/** The array x must be aligned to 16 (for SSE). */
case LBFGSERR_INVALID_X_SSE:
p = "INVALID_X_SSE";
break;
/** Invalid parameter lbfgs_parameter_t::epsilon specified. */
case LBFGSERR_INVALID_EPSILON:
p = "INVALID_EPSILON";
break;
/** Invalid parameter lbfgs_parameter_t::past specified. */
case LBFGSERR_INVALID_TESTPERIOD:
p = "INVALID_TESTPERIOD";
break;
/** Invalid parameter lbfgs_parameter_t::delta specified. */
case LBFGSERR_INVALID_DELTA:
p = "INVALID_DELTA";
break;
/** Invalid parameter lbfgs_parameter_t::linesearch specified. */
case LBFGSERR_INVALID_LINESEARCH:
p = "INVALID_LINESEARCH";
break;
/** Invalid parameter lbfgs_parameter_t::max_step specified. */
case LBFGSERR_INVALID_MINSTEP:
p = "INVALID_MINSTEP";
break;
/** Invalid parameter lbfgs_parameter_t::max_step specified. */
case LBFGSERR_INVALID_MAXSTEP:
p = "INVALID_MAXSTEP";
break;
/** Invalid parameter lbfgs_parameter_t::ftol specified. */
case LBFGSERR_INVALID_FTOL:
p = "INVALID_FTOL";
break;
/** Invalid parameter lbfgs_parameter_t::wolfe specified. */
case LBFGSERR_INVALID_WOLFE:
p = "INVALID_WOLFE";
break;
/** Invalid parameter lbfgs_parameter_t::gtol specified. */
case LBFGSERR_INVALID_GTOL:
p = "INVALID_GTOL";
break;
/** Invalid parameter lbfgs_parameter_t::xtol specified. */
case LBFGSERR_INVALID_XTOL:
p = "INVALID_XTOL";
break;
/** Invalid parameter lbfgs_parameter_t::max_linesearch specified. */
case LBFGSERR_INVALID_MAXLINESEARCH:
p = "INVALID_MAXLINESEARCH";
break;
/** Invalid parameter lbfgs_parameter_t::orthantwise_c specified. */
case LBFGSERR_INVALID_ORTHANTWISE:
p = "INVALID_ORTHANTWISE";
break;
/** Invalid parameter lbfgs_parameter_t::orthantwise_start specified. */
case LBFGSERR_INVALID_ORTHANTWISE_START:
p = "INVALID_ORTHANTWISE_START";
break;
/** Invalid parameter lbfgs_parameter_t::orthantwise_end specified. */
case LBFGSERR_INVALID_ORTHANTWISE_END:
p = "ORTHANTWISE_END";
break;
/** The line-search step went out of the interval of uncertainty. */
case LBFGSERR_OUTOFINTERVAL:
p = "OUTOFINTERVAL";
break;
/** A logic error occurred; alternatively: the interval of uncertainty
became too small. */
case LBFGSERR_INCORRECT_TMINMAX:
p = "INCORRECT_TMINMAX";
break;
/** A rounding error occurred; alternatively: no line-search step
satisfies the sufficient decrease and curvature conditions. */
case LBFGSERR_ROUNDING_ERROR:
p = "ROUNDING_ERROR";
break;
/** The line-search step became smaller than lbfgs_parameter_t::min_step. */
case LBFGSERR_MINIMUMSTEP:
p = "MINIMUMSTEP";
break;
/** The line-search step became larger than lbfgs_parameter_t::max_step. */
case LBFGSERR_MAXIMUMSTEP:
p = "MAXILBFGSERR_MUMSTEP";
break;
/** The line-search routine reaches the maximum number of evaluations. */
case LBFGSERR_MAXIMUMLINESEARCH:
p = "MAXIMUMLINESEARCH";
break;
/** The algorithm routine reaches the maximum number of iterations. */
case LBFGSERR_MAXIMUMITERATION:
p = "MAXIMUMITERATION";
break;
/** Relative width of the interval of uncertainty is at most
lbfgs_parameter_t::xtol. */
case LBFGSERR_WIDTHTOOSMALL:
p = "WIDTHTOOSMALL";
break;
/** A logic error (negative line-search step) occurred. */
case LBFGSERR_INVALIDPARAMETERS:
p = "INVALIDPARAMETERS";
break;
/** The current search direction increases the objective function value. */
case LBFGSERR_INCREASEGRADIENT:
p = "INCREASEGRADIENT";
break;
case 0:
p = "Minimization success";
break;
default:
p = "No detected error";
break;
}
return p;
}
numeric_t ElapsedTime(struct timeval *start) {
/* Computes the elapsed time from START to NOW in seconds */
struct timeval now;
gettimeofday(&now, NULL);
if (now.tv_usec < start->tv_usec) {
int nsec = (start->tv_usec - now.tv_usec) / 1000000 + 1;
start->tv_usec -= 1000000 * nsec;
start->tv_sec += nsec;
}
if (now.tv_usec - start->tv_usec > 1000000) {
int nsec = (now.tv_usec - start->tv_usec) / 1000000;
start->tv_usec += 1000000 * nsec;
start->tv_sec -= nsec;
}
return (numeric_t) (now.tv_sec - start->tv_sec)
+ ((numeric_t) (now.tv_usec - start->tv_usec)) / 1E6;
} |
ieee_pk.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#include "grb2.h"
#include "wgrib2.h"
#include "fnlist.h"
/*
* write grib-2 ieee file
* public domain 2008 Wesley Ebisuzaki
*/
int ieee_grib_out(unsigned char **sec, float *data, unsigned int ndata, struct seq_file *out) {
unsigned int n_defined, i;
int j;
unsigned char *p, *sec0, *sec1, *sec2, *sec3, *sec4, *sec5, *sec6, *sec7;
#ifdef IEEE_BITMAP
float *data_tmp;
#endif
/* required passed sections */
sec0 = sec[0];
sec1 = sec[1];
sec2 = sec[2];
sec3 = sec[3];
sec4 = sec[4];
/* make a new section 6 */
#ifdef IEEE_BITMAP
data_tmp = (float *) malloc(((size_t) ndata) * sizeof(float));
for (i = 0; i < ndata; i++) {
data_tmp[i] = data[i];
}
n_defined = ndata;
sec6 = mk_bms(data_tmp, &n_defined); // make bitmap section
if (sec6 == NULL) fatal_error("grib_out ieee memory allocation sec6","");
#else
n_defined = ndata;
sec6 = (unsigned char *) malloc(6);
if (sec6 == NULL) fatal_error("grib_out ieee memory allocation sec6","");
uint_char(6 * sizeof (unsigned char), sec6);
sec6[4] = 6; // section 5
sec6[5] = 255; // no bitmap
#endif
/* data representation section */
sec5 = (unsigned char *) malloc(12 * sizeof(unsigned char));
if (sec5 == NULL) fatal_error("grib_out ieee memory allocation sec5","");
uint_char(12 * sizeof (unsigned char), sec5);
sec5[4] = 5; // section 5
uint_char(ndata, sec5+5); // number of points
uint2_char(4,sec5+9); // data template 4
sec5[11] = 1; // precision: ieee 32-bit
/* data section */
i = (unsigned int) (4 * (size_t) n_defined);
if (i != (4 * (size_t) n_defined))
fatal_error("ieee_pk: grib2 data section is limited to 4G bytes","");
sec7 = (unsigned char *) malloc(5 + ((size_t) n_defined) * 4);
if (sec7 == NULL) fatal_error("ieee_pk: memory allocation sec7","");
uint_char(5 + 4 * (size_t) n_defined, sec7);
sec7[4] = 7;
p = sec7 + 5;
j = 0;
#pragma omp parallel for private(i) schedule(static)
for (i = 0; i < n_defined; i++) {
#ifdef IEEE_BITMAP
flt2ieee_nan(data_tmp[i], p + (i<<2) );
#else
flt2ieee_nan(data[i], p + (i<<2) );
#endif
}
#ifdef IEEE_BITMAP
free(data_tmp);
#endif
j = wrt_sec(sec0, sec1, sec2, sec3, sec4, sec5, sec6, sec7, out);
free(sec5);
free(sec6);
free(sec7);
return j;
}
|
omp4_hello.c | #include <stdio.h>
#include <omp.h>
int main()
{
int nthreads, tid;
int ndevices;
#pragma omp parallel private(nthreads, tid)
{
tid = omp_get_thread_num();
printf("Hello, world! I am thread %d on host\n", tid);
#pragma omp barrier
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Number of threads = %d on host\n\n", nthreads);
}
}
#pragma omp declare target
{
ndevices = omp_get_num_devices();
printf("Number of devices = %d\n\n", ndevices);
#pragma omp target device(1)
{
#pragma omp parallel private(nthreads, tid)
{
tid = omp_get_thread_num();
printf("Hello, world! I am thread %d on mic0\n", tid);
#pragma omp barrier
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Number of threads = %d on mic0\n\n", nthreads);
}
}
}
#pragma omp target device(2)
{
#pragma omp parallel private(nthreads, tid)
{
tid = omp_get_thread_num();
printf("Hello, world! I am thread %d on mic1\n", tid);
#pragma omp barrier
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Number of threads = %d on mic1\n", nthreads);
}
}
}
}
}
|
outeronly2-orig-no.c | /*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov,
schordan1@llnl.gov, karlin1@llnl.gov)
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https://github.com/LLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
/* Only the outmost loop can be parallelized.
The inner loop has loop carried anti data dependence.
However, the loop is not parallelized so no race condition.
Source: based on AutoPar's regression test.
*/
int n=100, m=100;
double b[100][100];
void foo()
{
int i,j;
#pragma omp parallel for private(j)
for (i=0;i<n;i++)
for (j=1;j<m;j++) // Be careful about bounds of j
b[i][j]=b[i][j-1];
}
int main()
{
foo();
return 0;
}
|
Parser.h | //===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the Parser interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_PARSE_PARSER_H
#define LLVM_CLANG_PARSE_PARSER_H
#include "clang/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/LoopHint.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SaveAndRestore.h"
#include <memory>
#include <stack>
namespace clang {
class PragmaHandler;
class Scope;
class BalancedDelimiterTracker;
class CorrectionCandidateCallback;
class DeclGroupRef;
class DiagnosticBuilder;
class Parser;
class ParsingDeclRAIIObject;
class ParsingDeclSpec;
class ParsingDeclarator;
class ParsingFieldDeclarator;
class ColonProtectionRAIIObject;
class InMessageExpressionRAIIObject;
class PoisonSEHIdentifiersRAIIObject;
class OMPClause;
class ObjCTypeParamList;
class ObjCTypeParameter;
/// Parser - This implements a parser for the C family of languages. After
/// parsing units of the grammar, productions are invoked to handle whatever has
/// been read.
///
class Parser : public CodeCompletionHandler {
friend class ColonProtectionRAIIObject;
friend class InMessageExpressionRAIIObject;
friend class PoisonSEHIdentifiersRAIIObject;
friend class ObjCDeclContextSwitch;
friend class ParenBraceBracketBalancer;
friend class BalancedDelimiterTracker;
Preprocessor &PP;
/// Tok - The current token we are peeking ahead. All parsing methods assume
/// that this is valid.
Token Tok;
// PrevTokLocation - The location of the token we previously
// consumed. This token is used for diagnostics where we expected to
// see a token following another token (e.g., the ';' at the end of
// a statement).
SourceLocation PrevTokLocation;
unsigned short ParenCount = 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++0x contextual keywords.
mutable IdentifierInfo *Ident_final;
mutable IdentifierInfo *Ident_GNU_final;
mutable IdentifierInfo *Ident_override;
// C++ type trait keywords that can be reverted to identifiers and still be
// used as type traits.
llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits;
std::unique_ptr<PragmaHandler> AlignHandler;
std::unique_ptr<PragmaHandler> GCCVisibilityHandler;
std::unique_ptr<PragmaHandler> OptionsHandler;
std::unique_ptr<PragmaHandler> PackHandler;
std::unique_ptr<PragmaHandler> MSStructHandler;
std::unique_ptr<PragmaHandler> UnusedHandler;
std::unique_ptr<PragmaHandler> WeakHandler;
std::unique_ptr<PragmaHandler> RedefineExtnameHandler;
std::unique_ptr<PragmaHandler> FPContractHandler;
std::unique_ptr<PragmaHandler> OpenCLExtensionHandler;
std::unique_ptr<PragmaHandler> OpenMPHandler;
std::unique_ptr<PragmaHandler> PCSectionHandler;
std::unique_ptr<PragmaHandler> MSCommentHandler;
std::unique_ptr<PragmaHandler> MSDetectMismatchHandler;
std::unique_ptr<PragmaHandler> MSPointersToMembers;
std::unique_ptr<PragmaHandler> MSVtorDisp;
std::unique_ptr<PragmaHandler> MSInitSeg;
std::unique_ptr<PragmaHandler> MSDataSeg;
std::unique_ptr<PragmaHandler> MSBSSSeg;
std::unique_ptr<PragmaHandler> MSConstSeg;
std::unique_ptr<PragmaHandler> MSCodeSeg;
std::unique_ptr<PragmaHandler> MSSection;
std::unique_ptr<PragmaHandler> MSRuntimeChecks;
std::unique_ptr<PragmaHandler> MSIntrinsic;
std::unique_ptr<PragmaHandler> MSOptimize;
std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler;
std::unique_ptr<PragmaHandler> OptimizeHandler;
std::unique_ptr<PragmaHandler> LoopHintHandler;
std::unique_ptr<PragmaHandler> UnrollHintHandler;
std::unique_ptr<PragmaHandler> NoUnrollHintHandler;
std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler;
std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler;
std::unique_ptr<PragmaHandler> FPHandler;
std::unique_ptr<PragmaHandler> STDCFENVHandler;
std::unique_ptr<PragmaHandler> STDCCXLIMITHandler;
std::unique_ptr<PragmaHandler> STDCUnknownHandler;
std::unique_ptr<PragmaHandler> AttributePragmaHandler;
std::unique_ptr<PragmaHandler> DefaultASHandler;
std::unique_ptr<PragmaHandler> StorageASHandler;
std::unique_ptr<PragmaHandler> Ptr32ThunkPrefixHandler;
std::unique_ptr<PragmaHandler> Ptr32CS32NameHandler;
std::unique_ptr<PragmaHandler> Ptr32CS64NameHandler;
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;
/// 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;
/// RAII class that manages the template parameter depth.
class TemplateParameterDepthRAII {
unsigned &Depth;
unsigned AddedLevels;
public:
explicit TemplateParameterDepthRAII(unsigned &Depth)
: Depth(Depth), AddedLevels(0) {}
~TemplateParameterDepthRAII() {
Depth -= AddedLevels;
}
void operator++() {
++Depth;
++AddedLevels;
}
void addDepth(unsigned D) {
Depth += D;
AddedLevels += D;
}
unsigned getDepth() const { return Depth; }
};
/// Factory object for creating ParsedAttr objects.
AttributeFactory AttrFactory;
/// Gathers and cleans up TemplateIdAnnotations when parsing of a
/// top-level declaration is finished.
SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
/// 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;
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 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);
PP.Lex(Tok);
PP.EnterToken(Next);
}
SourceLocation ConsumeAnnotationToken() {
assert(Tok.isAnnotation() && "wrong consume method");
SourceLocation Loc = Tok.getLocation();
PrevTokLocation = Tok.getAnnotationEndLoc();
PP.Lex(Tok);
return Loc;
}
/// ConsumeParen - This consume method keeps the paren count up-to-date.
///
SourceLocation ConsumeParen() {
assert(isTokenParen() && "wrong consume method");
if (Tok.getKind() == tok::l_paren)
++ParenCount;
else if (ParenCount) {
AngleBrackets.clear(*this);
--ParenCount; // Don't let unbalanced )'s drive the count negative.
}
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeBracket - This consume method keeps the bracket count up-to-date.
///
SourceLocation ConsumeBracket() {
assert(isTokenBracket() && "wrong consume method");
if (Tok.getKind() == tok::l_square)
++BracketCount;
else if (BracketCount) {
AngleBrackets.clear(*this);
--BracketCount; // Don't let unbalanced ]'s drive the count negative.
}
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeBrace - This consume method keeps the brace count up-to-date.
///
SourceLocation ConsumeBrace() {
assert(isTokenBrace() && "wrong consume method");
if (Tok.getKind() == tok::l_brace)
++BraceCount;
else if (BraceCount) {
AngleBrackets.clear(*this);
--BraceCount; // Don't let unbalanced }'s drive the count negative.
}
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// ConsumeStringToken - Consume the current 'peek token', lexing a new one
/// and returning the token kind. This method is specific to strings, as it
/// handles string literal concatenation, as per C99 5.1.1.2, translation
/// phase #6.
SourceLocation ConsumeStringToken() {
assert(isTokenStringLiteral() &&
"Should only consume string literals with this method");
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
/// Consume the current code-completion token.
///
/// This routine can be called to consume the code-completion token and
/// continue processing in special cases where \c cutOffParsing() isn't
/// desired, such as token caching or completion with lookahead.
SourceLocation ConsumeCodeCompletionToken() {
assert(Tok.is(tok::code_completion));
PrevTokLocation = Tok.getLocation();
PP.Lex(Tok);
return PrevTokLocation;
}
///\ brief When we are consuming a code-completion token without having
/// matched specific position in the grammar, provide code-completion results
/// based on context.
///
/// \returns the source location of the code-completion token.
SourceLocation handleUnexpectedCodeCompletionToken();
/// Abruptly cut off parsing; mainly used when we have reached the
/// code-completion point.
void cutOffParsing() {
if (PP.isCodeCompletionEnabled())
PP.setCodeCompletionReached();
// Cut off parsing by acting as if we reached the end-of-file.
Tok.setKind(tok::eof);
}
/// Determine if we're at the end of the file or at a transition
/// between modules.
bool isEofOrEom() {
tok::TokenKind Kind = Tok.getKind();
return Kind == tok::eof || Kind == tok::annot_module_begin ||
Kind == tok::annot_module_end || Kind == tok::annot_module_include;
}
/// Checks if the \p Level is valid for use in a fold expression.
bool isFoldOperator(prec::Level Level) const;
/// Checks if the \p Kind is a valid operator for fold expressions.
bool isFoldOperator(tok::TokenKind Kind) const;
/// Initialize all pragma handlers.
void initializePragmaHandlers();
/// Destroy and reset all pragma handlers.
void resetPragmaHandlers();
/// Handle the annotation token produced for #pragma unused(...)
void HandlePragmaUnused();
/// Handle the annotation token produced for
/// #pragma GCC visibility...
void HandlePragmaVisibility();
/// Handle the annotation token produced for
/// #pragma pack...
void HandlePragmaPack();
/// Handle the annotation token produced for
/// #pragma ms_struct...
void HandlePragmaMSStruct();
/// Handle the annotation token produced for
/// #pragma comment...
void HandlePragmaMSComment();
void HandlePragmaMSPointersToMembers();
void HandlePragmaMSVtorDisp();
void HandlePragmaMSPragma();
bool HandlePragmaMSSection(StringRef PragmaName,
SourceLocation PragmaLocation);
bool HandlePragmaMSSegment(StringRef PragmaName,
SourceLocation PragmaLocation);
bool HandlePragmaMSInitSeg(StringRef PragmaName,
SourceLocation PragmaLocation);
/// Handle the annotation token produced for
/// #pragma align...
void HandlePragmaAlign();
/// Handle the annotation token produced for
/// #pragma clang __debug dump...
void HandlePragmaDump();
/// Handle the annotation token produced for
/// #pragma weak id...
void HandlePragmaWeak();
/// Handle the annotation token produced for
/// #pragma weak id = id...
void HandlePragmaWeakAlias();
/// Handle the annotation token produced for
/// #pragma redefine_extname...
void HandlePragmaRedefineExtname();
/// Handle the annotation token produced for
/// #pragma STDC FP_CONTRACT...
void HandlePragmaFPContract();
/// Handle the annotation token produced for
/// #pragma STDC FENV_ACCESS...
void HandlePragmaFEnvAccess();
/// \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();
void HandlePragmaDefaultAS();
void HandlePragmaStorageAS();
bool HandlePragmaPtr32ThunkPrefix(StringRef PragmaName,
SourceLocation PragmaLocation);
bool HandlePragmaPtr32CS32Name(StringRef PragmaName,
SourceLocation PragmaLocation);
bool HandlePragmaPtr32CS64Name(StringRef PragmaName,
SourceLocation PragmaLocation);
/// GetLookAheadToken - This peeks ahead N tokens and returns that token
/// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1)
/// returns the token after Tok, etc.
///
/// Note that this differs from the Preprocessor's LookAhead method, because
/// the Parser always has one token lexed that the preprocessor doesn't.
///
const Token &GetLookAheadToken(unsigned N) {
if (N == 0 || Tok.is(tok::eof)) return Tok;
return PP.LookAhead(N-1);
}
public:
/// NextToken - This peeks ahead one token and returns it without
/// consuming it.
const Token &NextToken() {
return PP.LookAhead(0);
}
/// getTypeAnnotation - Read a parsed type out of an annotation token.
static ParsedType getTypeAnnotation(const Token &Tok) {
return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
}
private:
static void setTypeAnnotation(Token &Tok, ParsedType T) {
Tok.setAnnotationValue(T.getAsOpaquePtr());
}
/// 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);
private:
enum AnnotatedNameKind {
/// Annotation has failed and emitted an error.
ANK_Error,
/// The identifier is a tentatively-declared name.
ANK_TentativeDecl,
/// The identifier is a template name. FIXME: Add an annotation for that.
ANK_TemplateName,
/// The identifier can't be resolved.
ANK_Unresolved,
/// Annotation was successful.
ANK_Success
};
AnnotatedNameKind
TryAnnotateName(bool IsAddressOfOperand,
std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
/// Push a tok::annot_cxxscope token onto the token stream.
void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
/// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
/// replacing them with the non-context-sensitive keywords. This returns
/// true if the token was replaced.
bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid) {
if (!getLangOpts().AltiVec && !getLangOpts().ZVector)
return false;
if (Tok.getIdentifierInfo() != Ident_vector &&
Tok.getIdentifierInfo() != Ident_bool &&
(!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel))
return false;
return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
}
/// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
/// identifier token, replacing it with the non-context-sensitive __vector.
/// This returns true if the token was replaced.
bool TryAltiVecVectorToken() {
if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) ||
Tok.getIdentifierInfo() != Ident_vector) return false;
return TryAltiVecVectorTokenOutOfLine();
}
bool TryAltiVecVectorTokenOutOfLine();
bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
bool &isInvalid);
/// Returns true if the current token is the identifier 'instancetype'.
///
/// Should only be used in Objective-C language modes.
bool isObjCInstancetype() {
assert(getLangOpts().ObjC1);
if (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;
Token PrevTok;
size_t PrevTentativelyDeclaredIdentifierCount;
unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
bool isActive;
public:
explicit TentativeParsingAction(Parser& p) : P(p) {
PrevTok = P.Tok;
PrevTentativelyDeclaredIdentifierCount =
P.TentativelyDeclaredIdentifiers.size();
PrevParenCount = P.ParenCount;
PrevBracketCount = P.BracketCount;
PrevBraceCount = P.BraceCount;
P.PP.EnableBacktrackAtThisPos();
isActive = true;
}
void Commit() {
assert(isActive && "Parsing action was finished!");
P.TentativelyDeclaredIdentifiers.resize(
PrevTentativelyDeclaredIdentifierCount);
P.PP.CommitBacktrackedTokens();
isActive = false;
}
void Revert() {
assert(isActive && "Parsing action was finished!");
P.PP.Backtrack();
P.Tok = PrevTok;
P.TentativelyDeclaredIdentifiers.resize(
PrevTentativelyDeclaredIdentifierCount);
P.ParenCount = PrevParenCount;
P.BracketCount = PrevBracketCount;
P.BraceCount = PrevBraceCount;
isActive = false;
}
~TentativeParsingAction() {
assert(!isActive && "Forgot to call Commit or Revert!");
}
};
/// 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, unsigned TST = TST_unspecified);
/// Return false if the next token is an identifier. An 'expected identifier'
/// error is emitted otherwise.
///
/// The parser tries to recover from the error by checking if the next token
/// is a C++ keyword when parsing Objective-C++. Return false if the recovery
/// was successful.
bool expectIdentifier();
public:
//===--------------------------------------------------------------------===//
// Scope manipulation
/// ParseScope - Introduces a new scope for parsing. The kind of
/// scope is determined by ScopeFlags. Objects of this type should
/// be created on the stack to coincide with the position where the
/// parser enters the new scope, and this object's constructor will
/// create that new scope. Similarly, once the object is destroyed
/// the parser will exit the scope.
class ParseScope {
Parser *Self;
ParseScope(const ParseScope &) = delete;
void operator=(const ParseScope &) = delete;
public:
// ParseScope - Construct a new object to manage a scope in the
// parser Self where the new Scope is created with the flags
// ScopeFlags, but only when we aren't about to enter a compound statement.
ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true,
bool BeforeCompoundStmt = false)
: Self(Self) {
if (EnteredScope && !BeforeCompoundStmt)
Self->EnterScope(ScopeFlags);
else {
if (BeforeCompoundStmt)
Self->incrementMSManglingNumber();
this->Self = nullptr;
}
}
// Exit - Exit the scope associated with this object now, rather
// than waiting until the object is destroyed.
void Exit() {
if (Self) {
Self->ExitScope();
Self = nullptr;
}
}
~ParseScope() {
Exit();
}
};
/// EnterScope - Start a new scope.
void EnterScope(unsigned ScopeFlags);
/// ExitScope - Pop a scope off the scope stack.
void ExitScope();
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.
///
/// If SkipUntil finds the specified token, it returns true, otherwise it
/// returns false.
bool SkipUntil(tok::TokenKind T,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
return SkipUntil(llvm::makeArrayRef(T), Flags);
}
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
tok::TokenKind TokArray[] = {T1, T2};
return SkipUntil(TokArray, Flags);
}
bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) {
tok::TokenKind TokArray[] = {T1, T2, T3};
return SkipUntil(TokArray, Flags);
}
bool SkipUntil(ArrayRef<tok::TokenKind> Toks,
SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0));
/// SkipMalformedDecl - Read tokens until we get to some likely good stopping
/// point for skipping past a simple-declaration.
void SkipMalformedDecl();
private:
//===--------------------------------------------------------------------===//
// Lexing and parsing of C++ inline methods.
struct ParsingClass;
/// [class.mem]p1: "... the class is regarded as complete within
/// - function bodies
/// - default arguments
/// - exception-specifications (TODO: C++0x)
/// - and brace-or-equal-initializers for non-static data members
/// (including such things in nested classes)."
/// LateParsedDeclarations build the tree of those elements so they can
/// be parsed after parsing the top-level class.
class LateParsedDeclaration {
public:
virtual ~LateParsedDeclaration();
virtual void ParseLexedMethodDeclarations();
virtual void ParseLexedMemberInitializers();
virtual void ParseLexedMethodDefs();
virtual void ParseLexedAttributes();
};
/// Inner node of the LateParsedDeclaration tree that parses
/// all its members recursively.
class LateParsedClass : public LateParsedDeclaration {
public:
LateParsedClass(Parser *P, ParsingClass *C);
~LateParsedClass() override;
void ParseLexedMethodDeclarations() override;
void ParseLexedMemberInitializers() override;
void ParseLexedMethodDefs() override;
void ParseLexedAttributes() override;
private:
Parser *Self;
ParsingClass *Class;
};
/// Contains the lexed tokens of an attribute with arguments that
/// may reference member variables and so need to be parsed at the
/// end of the class declaration after parsing all other member
/// member declarations.
/// FIXME: Perhaps we should change the name of LateParsedDeclaration to
/// LateParsedTokens.
struct LateParsedAttribute : public LateParsedDeclaration {
Parser *Self;
CachedTokens Toks;
IdentifierInfo &AttrName;
SourceLocation AttrNameLoc;
SmallVector<Decl*, 2> Decls;
explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
SourceLocation Loc)
: Self(P), AttrName(Name), AttrNameLoc(Loc) {}
void ParseLexedAttributes() override;
void addDecl(Decl *D) { Decls.push_back(D); }
};
// A list of late-parsed attributes. Used by ParseGNUAttributes.
class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
public:
LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
bool parseSoon() { return ParseSoon; }
private:
bool ParseSoon; // Are we planning to parse these shortly after creation?
};
/// Contains the lexed tokens of a member function definition
/// which needs to be parsed at the end of the class declaration
/// after parsing all other member declarations.
struct LexedMethod : public LateParsedDeclaration {
Parser *Self;
Decl *D;
CachedTokens Toks;
/// Whether this member function had an associated template
/// scope. When true, D is a template declaration.
/// otherwise, it is a member function declaration.
bool TemplateScope;
explicit LexedMethod(Parser* P, Decl *MD)
: Self(P), D(MD), TemplateScope(false) {}
void ParseLexedMethodDefs() override;
};
/// LateParsedDefaultArgument - Keeps track of a parameter that may
/// have a default argument that cannot be parsed yet because it
/// occurs within a member function declaration inside the class
/// (C++ [class.mem]p2).
struct LateParsedDefaultArgument {
explicit LateParsedDefaultArgument(Decl *P,
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), TemplateScope(false),
ExceptionSpecTokens(nullptr) {}
void ParseLexedMethodDeclarations() override;
Parser* Self;
/// Method - The method declaration.
Decl *Method;
/// Whether this member function had an associated template
/// scope. When true, D is a template declaration.
/// otherwise, it is a member function declaration.
bool TemplateScope;
/// 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), TemplateScope(false),
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 had an associated template
/// scope. When true, TagOrTemplate is a template declaration;
/// otherwise, it is a tag declaration.
bool TemplateScope : 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;
};
void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
static void LateTemplateParserCleanupCallback(void *P);
Sema::ParsingClassState
PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
void DeallocateParsedClasses(ParsingClass *Class);
void PopParsingClass(Sema::ParsingClassState);
enum CachedInitKind {
CIK_DefaultArgument,
CIK_DefaultInitializer
};
NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
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);
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, if non-NULL, is filled with the location of the last token of
// the simple-asm.
ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr);
ExprResult ParseAsmStringLiteral();
// Objective-C External Declarations
void MaybeSkipAttributes(tok::ObjCKeywordKind Kind);
DeclGroupPtrTy ParseObjCAtDirectives(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);
DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
// Definitions for Objective-c context sensitive keywords recognition.
enum ObjCTypeQual {
objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
objc_nonnull, objc_nullable, objc_null_unspecified,
objc_NumQuals
};
IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
bool isTokIdentifier_in() const;
ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx,
ParsedAttributes *ParamAttrs);
void ParseObjCMethodRequirement();
Decl *ParseObjCMethodPrototype(
tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
bool MethodDefinition = true);
Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
bool MethodDefinition=true);
void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
Decl *ParseObjCMethodDefinition();
public:
//===--------------------------------------------------------------------===//
// C99 6.5: Expressions.
/// TypeCastState - State whether an expression is or may be a type cast.
enum TypeCastState {
NotTypeCast = 0,
MaybeTypeCast,
IsTypeCast
};
ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseConstantExpressionInExprEvalContext(
TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseCaseExpression(SourceLocation CaseLoc);
ExprResult ParseConstraintExpression();
// Expr that doesn't include commas.
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
unsigned &NumLineToksConsumed,
bool IsUnevaluated);
private:
ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
prec::Level MinPrec);
ExprResult ParseCastExpression(bool isUnaryExpression,
bool isAddressOfOperand,
bool &NotCastExpr,
TypeCastState isTypeCast,
bool isVectorLiteral = false);
ExprResult ParseCastExpression(bool isUnaryExpression,
bool isAddressOfOperand = false,
TypeCastState isTypeCast = NotTypeCast,
bool isVectorLiteral = false);
/// 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<Expr*, 20> ExprListTy;
typedef SmallVector<SourceLocation, 20> CommaLocsTy;
/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
bool ParseExpressionList(
SmallVectorImpl<Expr *> &Exprs,
SmallVectorImpl<SourceLocation> &CommaLocs,
llvm::function_ref<void()> Completer = 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 ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
ExprResult ParseGenericSelectionExpression();
ExprResult ParseObjCBoolLiteral();
ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T);
//===--------------------------------------------------------------------===//
// C++ Expressions
ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
Token &Replacement);
ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
bool areTokensAdjacent(const Token &A, const Token &B);
void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
bool EnteringContext, IdentifierInfo &II,
CXXScopeSpec &SS);
bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext,
bool *MayBePseudoDestructor = nullptr,
bool IsTypename = false,
IdentifierInfo **LastII = nullptr,
bool OnlyNamespace = false);
//===--------------------------------------------------------------------===//
// C++0x 5.1.2: Lambda expressions
// [...] () -> type {...}
ExprResult ParseLambdaExpression();
ExprResult TryParseLambdaExpression();
Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro,
bool *SkippedInits = nullptr);
bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
ExprResult ParseLambdaExpressionAfterIntroducer(
LambdaIntroducer &Intro);
//===--------------------------------------------------------------------===//
// C++ 5.2p1: C++ Casts
ExprResult ParseCXXCasts();
//===--------------------------------------------------------------------===//
// C++ 5.2p1: C++ Type Identification
ExprResult ParseCXXTypeid();
//===--------------------------------------------------------------------===//
// C++ : Microsoft __uuidof Expression
ExprResult ParseCXXUuidof();
//===--------------------------------------------------------------------===//
// C++ 5.2.4: C++ Pseudo-Destructor Expressions
ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
ParsedType ObjectType);
//===--------------------------------------------------------------------===//
// C++ 9.3.2: C++ 'this' pointer
ExprResult ParseCXXThis();
//===--------------------------------------------------------------------===//
// C++ 15: C++ Throw Expression
ExprResult ParseThrowExpression();
ExceptionSpecificationType tryParseExceptionSpecification(
bool Delayed,
SourceRange &SpecificationRange,
SmallVectorImpl<ParsedType> &DynamicExceptions,
SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
ExprResult &NoexceptExpr,
CachedTokens *&ExceptionSpecTokens);
// EndLoc is filled with the location of the last token of the specification.
ExceptionSpecificationType ParseDynamicExceptionSpecification(
SourceRange &SpecificationRange,
SmallVectorImpl<ParsedType> &Exceptions,
SmallVectorImpl<SourceRange> &Ranges);
//===--------------------------------------------------------------------===//
// C++0x 8: Function declaration trailing-return-type
TypeResult ParseTrailingReturnType(SourceRange &Range,
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();
//===--------------------------------------------------------------------===//
// C99 6.7.8: Initialization.
/// ParseInitializer
/// initializer: [C99 6.7.8]
/// assignment-expression
/// '{' ...
ExprResult ParseInitializer() {
if (Tok.isNot(tok::l_brace))
return ParseAssignmentExpression();
return ParseBraceInitializer();
}
bool MayBeDesignationStart();
ExprResult ParseBraceInitializer();
ExprResult ParseInitializerWithPotentialDesignator();
//===--------------------------------------------------------------------===//
// clang Expressions
ExprResult ParseBlockLiteralExpression(); // ^{...}
//===--------------------------------------------------------------------===//
// Objective-C Expressions
ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
bool isSimpleObjCMessageExpression();
ExprResult ParseObjCMessageExpression();
ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
SourceLocation SuperLoc,
ParsedType ReceiverType,
Expr *ReceiverExpr);
ExprResult ParseAssignmentExprWithObjCMessageExprStart(
SourceLocation LBracloc, SourceLocation SuperLoc,
ParsedType ReceiverType, Expr *ReceiverExpr);
bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
//===--------------------------------------------------------------------===//
// C99 6.8: Statements and Blocks.
/// A SmallVector of statements, with stack size 32 (as that is the only one
/// used.)
typedef SmallVector<Stmt*, 32> StmtVector;
/// A SmallVector of expressions, with stack size 12 (the maximum used.)
typedef SmallVector<Expr*, 12> ExprVector;
/// A SmallVector of types.
typedef SmallVector<ParsedType, 12> TypeVector;
StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr,
bool AllowOpenMPStandalone = false);
enum AllowedConstructsKind {
/// Allow any declarations, statements, OpenMP directives.
ACK_Any,
/// Allow only statements and non-standalone OpenMP directives.
ACK_StatementsOpenMPNonStandalone,
/// Allow statements and all executable OpenMP directives
ACK_StatementsOpenMPAnyExecutable
};
StmtResult
ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed,
SourceLocation *TrailingElseLoc = nullptr);
StmtResult ParseStatementOrDeclarationAfterAttributes(
StmtVector &Stmts,
AllowedConstructsKind Allowed,
SourceLocation *TrailingElseLoc,
ParsedAttributesWithRange &Attrs);
StmtResult ParseExprStatement();
StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
StmtResult ParseCaseStatement(bool MissingCase = false,
ExprResult Expr = ExprResult());
StmtResult ParseDefaultStatement();
StmtResult ParseCompoundStatement(bool isStmtExpr = false);
StmtResult ParseCompoundStatement(bool isStmtExpr,
unsigned ScopeFlags);
void ParseCompoundStatementLeadingPragmas();
StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
bool ParseParenExprOrCondition(StmtResult *InitStmt,
Sema::ConditionResult &CondResult,
SourceLocation Loc,
Sema::ConditionKind CK);
StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseDoStatement();
StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseGotoStatement();
StmtResult ParseContinueStatement();
StmtResult ParseBreakStatement();
StmtResult ParseReturnStatement();
StmtResult ParseAsmStatement(bool &msAsm);
StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
StmtResult ParsePragmaLoopHint(StmtVector &Stmts,
AllowedConstructsKind Allowed,
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);
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");
}
/// 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);
DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context,
SourceLocation &DeclEnd,
ParsedAttributesWithRange &attrs,
bool RequireSemi,
ForRangeInit *FRI = 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, unsigned TagType,
Decl *TagDecl);
void ParseStructDeclaration(
ParsingDeclSpec &DS,
llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback);
bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
bool isTypeSpecifierQualifier();
/// isKnownToBeTypeSpecifier - Return true if we know that the specified token
/// is definitely a type-specifier. Return false if it isn't part of a type
/// specifier or if we're not sure.
bool isKnownToBeTypeSpecifier(const Token &Tok) const;
/// Return true if we know that we are definitely looking at a
/// decl-specifier, and isn't part of an expression such as a function-style
/// cast. Return false if it's no a decl-specifier, or we're not sure.
bool isKnownToBeDeclarationSpecifier() {
if (getLangOpts().CPlusPlus)
return isCXXDeclarationSpecifier() == TPResult::True;
return isDeclarationSpecifier(true);
}
/// isDeclarationStatement - Disambiguates between a declaration or an
/// expression statement, when parsing function bodies.
/// Returns true for declaration, false for expression.
bool isDeclarationStatement() {
if (getLangOpts().CPlusPlus)
return isCXXDeclarationStatement();
return isDeclarationSpecifier(true);
}
/// isForInitDeclaration - Disambiguates between a declaration or an
/// expression in the context of the C 'clause-1' or the C++
// 'for-init-statement' part of a 'for' statement.
/// Returns true for declaration, false for expression.
bool isForInitDeclaration() {
if (getLangOpts().CPlusPlus)
return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
return isDeclarationSpecifier(true);
}
/// 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
};
/// Based only on the given token kind, determine whether we know that
/// we're at the start of an expression or a type-specifier-seq (which may
/// be an expression, in C++).
///
/// This routine does not attempt to resolve any of the trick cases, e.g.,
/// those involving lookup of identifiers.
///
/// \returns \c TPR_true if this token starts an expression, \c TPR_false if
/// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
/// tell.
TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
/// isCXXDeclarationSpecifier - Returns TPResult::True if it is a
/// declaration specifier, TPResult::False if it is not,
/// TPResult::Ambiguous if it could be either a decl-specifier or a
/// function-style cast, and TPResult::Error if a parsing error was
/// encountered. If it could be a braced C++11 function-style cast, returns
/// BracedCastResult.
/// Doesn't consume tokens.
TPResult
isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False,
bool *HasMissingTypename = nullptr);
/// Given that isCXXDeclarationSpecifier returns \c TPResult::True or
/// \c TPResult::Ambiguous, determine whether the decl-specifier would be
/// a type-specifier other than a cv-qualifier.
bool isCXXDeclarationSpecifierAType();
/// 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();
public:
TypeResult ParseTypeName(SourceRange *Range = nullptr,
DeclaratorContext Context
= DeclaratorContext::TypeNameContext,
AccessSpecifier AS = AS_none,
Decl **OwnedType = nullptr,
ParsedAttributes *Attrs = nullptr);
private:
void ParseBlockId(SourceLocation CaretLoc);
/// Are [[]] attributes enabled?
bool standardAttributesAllowed() const {
const LangOptions &LO = getLangOpts();
return LO.DoubleSquareBracketAttributes;
}
// Check for the start of an attribute-specifier-seq in a context where an
// attribute is not allowed.
bool CheckProhibitedCXX11Attribute() {
assert(Tok.is(tok::l_square));
if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square))
return false;
return DiagnoseProhibitedCXX11Attribute();
}
bool DiagnoseProhibitedCXX11Attribute();
void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
SourceLocation CorrectLocation) {
if (!standardAttributesAllowed())
return;
if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
Tok.isNot(tok::kw_alignas))
return;
DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
}
void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
SourceLocation CorrectLocation);
void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs,
DeclSpec &DS, Sema::TagUseKind TUK);
// FixItLoc = possible correct location for the attributes
void ProhibitAttributes(ParsedAttributesWithRange &Attrs,
SourceLocation FixItLoc = SourceLocation()) {
if (Attrs.Range.isInvalid())
return;
DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
Attrs.clear();
}
void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs,
SourceLocation FixItLoc = SourceLocation()) {
if (Attrs.Range.isInvalid())
return;
DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc);
Attrs.clearListOnly();
}
void DiagnoseProhibitedAttributes(const SourceRange &Range,
SourceLocation FixItLoc);
// Forbid C++11 and C2x attributes that appear on certain syntactic locations
// which standard permits but we don't supported yet, for example, attributes
// appertain to decl specifiers.
void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs,
unsigned DiagID);
/// Skip C++11 and C2x attributes and return the end location of the
/// last one.
/// \returns SourceLocation() if there are no attributes.
SourceLocation SkipCXX11Attributes();
/// Diagnose and skip C++11 and C2x attributes that appear in syntactic
/// locations where attributes are not allowed.
void DiagnoseAndSkipCXX11Attributes();
/// Parses syntax-generic attribute arguments for attributes which are
/// known to the implementation, and adds them to the given ParsedAttributes
/// list with the given attribute syntax. Returns the number of arguments
/// parsed for the attribute.
unsigned
ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void MaybeParseGNUAttributes(Declarator &D,
LateParsedAttrList *LateAttrs = nullptr) {
if (Tok.is(tok::kw___attribute)) {
ParsedAttributes attrs(AttrFactory);
SourceLocation endLoc;
ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D);
D.takeAttributes(attrs, endLoc);
}
}
void MaybeParseGNUAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr,
LateParsedAttrList *LateAttrs = nullptr) {
if (Tok.is(tok::kw___attribute))
ParseGNUAttributes(attrs, endLoc, LateAttrs);
}
void ParseGNUAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr,
LateParsedAttrList *LateAttrs = nullptr,
Declarator *D = nullptr);
void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax, Declarator *D);
IdentifierLoc *ParseIdentifierLoc();
unsigned
ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName, SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void MaybeParseCXX11Attributes(Declarator &D) {
if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
ParsedAttributesWithRange attrs(AttrFactory);
SourceLocation endLoc;
ParseCXX11Attributes(attrs, &endLoc);
D.takeAttributes(attrs, endLoc);
}
}
void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr) {
if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
ParsedAttributesWithRange attrsWithRange(AttrFactory);
ParseCXX11Attributes(attrsWithRange, endLoc);
attrs.takeAllFrom(attrsWithRange);
}
}
void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
SourceLocation *endLoc = nullptr,
bool OuterMightBeMessageSend = false) {
if (standardAttributesAllowed() &&
isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
ParseCXX11Attributes(attrs, endLoc);
}
void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
SourceLocation *EndLoc = nullptr);
void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
SourceLocation *EndLoc = nullptr);
/// Parses a C++11 (or C2x)-style attribute argument list. Returns true
/// if this results in adding an attribute to the ParsedAttributes list.
bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs, SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc);
IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr) {
if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
ParseMicrosoftAttributes(attrs, endLoc);
}
void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs);
void ParseMicrosoftAttributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr);
void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
SourceLocation *End = nullptr) {
const auto &LO = getLangOpts();
if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec))
ParseMicrosoftDeclSpecs(Attrs, End);
}
void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs,
SourceLocation *End = nullptr);
bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs);
void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
void DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
SourceLocation SkipExtendedMicrosoftTypeAttributes();
void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
void ParseOpenCLKernelAttributes(ParsedAttributes &attrs);
void ParseOpenCLQualifiers(ParsedAttributes &Attrs);
/// Parses opencl_unroll_hint attribute if language is OpenCL v2.0
/// or higher.
/// \return false if error happens.
bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
if (getLangOpts().OpenCL)
return ParseOpenCLUnrollHintAttribute(Attrs);
return true;
}
/// Parses opencl_unroll_hint attribute.
/// \return false if error happens.
bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs);
void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs);
VersionTuple ParseVersionTuple(SourceRange &Range);
void ParseAvailabilityAttribute(IdentifierInfo &Availability,
SourceLocation AvailabilityLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
Optional<AvailabilitySpec> ParseAvailabilitySpec();
ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc);
void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol,
SourceLocation Loc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated,
SourceLocation ObjCBridgeRelatedLoc,
ParsedAttributes &attrs,
SourceLocation *endLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc,
ParsedAttributes &Attrs,
SourceLocation *EndLoc,
IdentifierInfo *ScopeName,
SourceLocation ScopeLoc,
ParsedAttr::Syntax Syntax);
void
ParseAttributeWithTypeArg(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc, ParsedAttributes &Attrs,
SourceLocation *EndLoc, IdentifierInfo *ScopeName,
SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax);
void ParseTypeofSpecifier(DeclSpec &DS);
SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
void ParseAtomicSpecifier(DeclSpec &DS);
ExprResult ParseAlignArgument(SourceLocation Start,
SourceLocation &EllipsisLoc);
void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
SourceLocation *endLoc = nullptr);
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);
bool ParseRefQualifier(bool &RefQualifierIsLValueRef,
SourceLocation &RefQualifierLoc);
bool isFunctionDeclaratorIdentifierList();
void ParseFunctionDeclaratorIdentifierList(
Declarator &D,
SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo);
void ParseParameterDeclarationClause(
Declarator &D,
ParsedAttributes &attrs,
SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo,
SourceLocation &EllipsisLoc);
void ParseBracketDeclarator(Declarator &D);
void ParseMisplacedBracketDeclarator(Declarator &D);
//===--------------------------------------------------------------------===//
// C++ 7: Declarations [dcl.dcl]
/// The kind of attribute specifier we have found.
enum CXX11AttributeKind {
/// This is not an attribute specifier.
CAK_NotAttributeSpecifier,
/// This should be treated as an attribute-specifier.
CAK_AttributeSpecifier,
/// The next tokens are '[[', but this is not an attribute-specifier. This
/// is ill-formed by C++11 [dcl.attr.grammar]p6.
CAK_InvalidAttributeSpecifier
};
CXX11AttributeKind
isCXX11AttributeSpecifier(bool Disambiguate = false,
bool OuterMightBeMessageSend = false);
void DiagnoseUnexpectedNamespace(NamedDecl *Context);
DeclGroupPtrTy ParseNamespace(DeclaratorContext Context,
SourceLocation &DeclEnd,
SourceLocation InlineLoc = SourceLocation());
void ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc,
std::vector<IdentifierInfo *> &Ident,
std::vector<SourceLocation> &NamespaceLoc,
unsigned int index, SourceLocation &InlineLoc,
ParsedAttributes &attrs,
BalancedDelimiterTracker &Tracker);
Decl *ParseLinkage(ParsingDeclSpec &DS, 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,
SourceLocation TemplateKWLoc,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool EnteringContext,
ParsedType ObjectType,
UnqualifiedId &Id,
bool AssumeTemplateId);
bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
ParsedType ObjectType,
UnqualifiedId &Result);
//===--------------------------------------------------------------------===//
// OpenMP: Directives and clauses.
/// Parse clauses for '#pragma omp declare simd'.
DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr,
CachedTokens &Toks,
SourceLocation Loc);
/// Parses declarative OpenMP directives.
DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl(
AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
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 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 Allowed ACK_Any, if any directives are allowed,
/// ACK_StatementsOpenMPAnyExecutable - if any executable directives are
/// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone
/// executable directives are allowed.
///
StmtResult
ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed);
/// 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 Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSingleExprWithArgClause(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);
public:
/// Parses simple expression in parens for single-expression clauses of OpenMP
/// constructs.
/// \param RLoc Returned location of right paren.
ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc);
/// Data used for parsing list of variables in OpenMP clauses.
struct OpenMPVarListDataTy {
Expr *TailExpr = nullptr;
SourceLocation ColonLoc;
SourceLocation RLoc;
CXXScopeSpec ReductionIdScopeSpec;
DeclarationNameInfo ReductionId;
OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown;
OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val;
OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
bool IsMapTypeImplicit = false;
SourceLocation DepLinMapLoc;
};
/// Parses clauses with list.
bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
SmallVectorImpl<Expr *> &Vars,
OpenMPVarListDataTy &Data);
bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
bool AllowDestructorName,
bool AllowConstructorName,
bool AllowDeductionGuide,
ParsedType ObjectType,
SourceLocation *TemplateKWLoc,
UnqualifiedId &Result);
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(unsigned Depth,
SmallVectorImpl<NamedDecl *> &TemplateParams,
SourceLocation &LAngleLoc,
SourceLocation &RAngleLoc);
bool ParseTemplateParameterList(unsigned Depth,
SmallVectorImpl<NamedDecl*> &TemplateParams);
bool 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);
void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
SourceLocation CorrectLoc,
bool AlreadyHasEllipsis,
bool IdentifierHasName);
void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
Declarator &D);
// C++ 14.3: Template arguments [temp.arg]
typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
bool ConsumeLastToken,
bool ObjCGenericList);
bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
SourceLocation &LAngleLoc,
TemplateArgList &TemplateArgs,
SourceLocation &RAngleLoc);
bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &TemplateName,
bool AllowTypeAnnotation = true);
void AnnotateTemplateIdTokenAsType(bool IsClassName = false);
bool IsTemplateArgumentList(unsigned Skip = 0);
bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
ParsedTemplateArgument ParseTemplateTemplateArgument();
ParsedTemplateArgument ParseTemplateArgument();
Decl *ParseExplicitInstantiation(DeclaratorContext Context,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
SourceLocation &DeclEnd,
ParsedAttributes &AccessAttrs,
AccessSpecifier AS = AS_none);
//===--------------------------------------------------------------------===//
// Modules
DeclGroupPtrTy ParseModuleDecl();
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;
};
} // end namespace clang
#endif
|
GB_binop__ge_fp64.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_mkl.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB_AaddB__ge_fp64
// A.*B function (eWiseMult): GB_AemultB__ge_fp64
// A*D function (colscale): GB_AxD__ge_fp64
// D*A function (rowscale): GB_DxB__ge_fp64
// C+=B function (dense accum): GB_Cdense_accumB__ge_fp64
// C+=b function (dense accum): GB_Cdense_accumb__ge_fp64
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__ge_fp64
// C=scalar+B GB_bind1st__ge_fp64
// C=scalar+B' GB_bind1st_tran__ge_fp64
// C=A+scalar GB_bind2nd__ge_fp64
// C=A'+scalar GB_bind2nd_tran__ge_fp64
// C type: bool
// A type: double
// B,b type: double
// BinaryOp: cij = (aij >= bij)
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#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) \
double aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
double bij = Bx [pB]
// 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) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y) \
z = (x >= y) ;
// op is second
#define GB_OP_IS_SECOND \
0
// op is plus_fp32 or plus_fp64
#define GB_OP_IS_PLUS_REAL \
0
// op is minus_fp32 or minus_fp64
#define GB_OP_IS_MINUS_REAL \
0
// GB_cblas_*axpy gateway routine, if it exists for this operator and type:
#define GB_CBLAS_AXPY \
(none)
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_GE || GxB_NO_FP64 || GxB_NO_GE_FP64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void (none)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_ewise3_noaccum__ge_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__ge_fp64
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *GB_RESTRICT kfirst_slice,
const int64_t *GB_RESTRICT klast_slice,
const int64_t *GB_RESTRICT pstart_slice,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
#include "GB_dense_subassign_23_template.c"
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__ge_fp64
(
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 double
double bwork = (*((double *) 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__ge_fp64
(
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
bool *GB_RESTRICT Cx = (bool *) 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__ge_fp64
(
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
bool *GB_RESTRICT Cx = (bool *) 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__ge_fp64
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_add_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB_AemultB__ge_fp64
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *GB_RESTRICT C_to_M,
const int64_t *GB_RESTRICT C_to_A,
const int64_t *GB_RESTRICT C_to_B,
const GB_task_struct *GB_RESTRICT TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB_bind1st__ge_fp64
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *Cx = (bool *) 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 < anz ; p++)
{
double 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__ge_fp64
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
bool *Cx = (bool *) 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++)
{
double aij = Ax [p] ;
Cx [p] = (aij >= y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
double aij = Ax [pA] ; \
Cx [pC] = (x >= aij) ; \
}
GrB_Info GB_bind1st_tran__ge_fp64
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#define GB_PHASE_2_OF_2
#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 typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
double aij = Ax [pA] ; \
Cx [pC] = (aij >= y) ; \
}
GrB_Info GB_bind2nd_tran__ge_fp64
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double y = (*((const double *) y_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
Kernel_3d_ZDG.h | #ifndef KRIPKE_KERNEL_3D_ZDG_H__
#define KRIPKE_KERNEL_3D_ZDG_H__
#include<Kripke/Kernel.h>
#include<Grid.h>
class Kernel_3d_ZDG : public Kernel {
public:
typedef std::vector<std::vector<double>> result_type;
// Grid is needed to access metadata (e.g. gd_sets) stored on it.
Grid_Data* grid_data;
int group_set;
int direction_set;
Kernel_3d_ZDG(Grid_Data*);
virtual ~Kernel_3d_ZDG();
virtual Nesting_Order nestingPsi(void) const;
virtual Nesting_Order nestingPhi(void) const;
virtual void LTimes(Grid_Data *grid_data);
virtual void LPlusTimes(Grid_Data *grid_data);
template<typename GridView, typename IPlane, typename JPlane, typename KPlane>
result_type
operator()(GridView& grid_view, IPlane const& i_plane, JPlane const& j_plane,
KPlane const& k_plane);
void define_type(stapl::typer& t)
{
t.member(grid_data);
t.member(group_set);
t.member(direction_set);
}
};
/* Sweep routine for Diamond-Difference */
/* Macros for offsets with fluxes on cell faces */
#define I_PLANE_INDEX(j, k) (k)*(local_jmax) + (j)
#define J_PLANE_INDEX(i, k) (k)*(local_imax) + (i)
#define K_PLANE_INDEX(i, j) (j)*(local_imax) + (i)
#define Zonal_INDEX(i, j, k) (i) + (local_imax)*(j) \
+ (local_imax)*(local_jmax)*(k)
template<typename GridView, typename IPlane, typename JPlane, typename KPlane>
std::vector<std::vector<double>>
Kernel_3d_ZDG::operator()(GridView& grid_view, IPlane const& i_plane_in,
JPlane const& j_plane_in, KPlane const& k_plane_in)
{
typedef std::array<typename GridView::value_type::property_type::
storage_type::index, 2> index_type;
result_type result(3);
std::vector<double> i_plane = i_plane_in[0];
std::vector<double> j_plane = j_plane_in[0];
std::vector<double> k_plane = k_plane_in[0];
// grid_data, group_set, and direction_set are data members of the Kernel.
Group_Dir_Set& gd_set = grid_data->gd_sets()[group_set][direction_set];
int num_directions = gd_set.num_directions;
int num_groups = gd_set.num_groups;
Directions *direction = gd_set.directions;
int local_imax = grid_data->nzones()[0];
int local_jmax = grid_data->nzones()[1];
// TGS : compiler detects unused variable. Are the macros correct?
// int local_kmax = grid_data->nzones()[2];
auto dx = grid_data->deltas(0);
auto dy = grid_data->deltas(1);
auto dz = grid_data->deltas(2);
// All directions have same id,jd,kd, since these are all one Direction Set
// So pull that information out now
int octant = direction[0].octant;
Grid_Sweep_Block const &extent = grid_data->octant_extent()[octant];
for (int k = extent.start_k; k != extent.end_k; k += extent.inc_k) {
double dzk = dz[k + 1];
for (int j = extent.start_j; j != extent.end_j; j += extent.inc_j) {
double dyj = dy[j + 1];
for (int i = extent.start_i; i != extent.end_i; i += extent.inc_i) {
double dxi = dx[i + 1];
// get a reference to the vertex being processed.
int z = Zonal_INDEX(i, j, k);
auto v = (*grid_view.find_vertex(z)).property();
#ifdef KRIPKE_USE_OPENMP
#pragma omp parallel for
#endif
for (int d = 0; d < num_directions; ++d) {
double xcos = direction[d].xcos;
double ycos = direction[d].ycos;
double zcos = direction[d].zcos;
double zcos_dzk = 2.0 * zcos / dzk;
double ycos_dyj = 2.0 * ycos / dyj;
double xcos_dxi = 2.0 * xcos / dxi;
auto psi_z = v.psi()[group_set][direction_set];
index_type psi_z_idx{{0, d}};
auto rhs_z = v.rhs()[group_set][direction_set];
index_type rhs_z_idx{{0, d}};
int i_plane_idx = I_PLANE_INDEX(j, k)*num_directions*num_groups +
d*num_groups;
double * psi_lf_z_d = &i_plane[i_plane_idx];
int j_plane_idx = J_PLANE_INDEX(i, k)*num_directions*num_groups +
d*num_groups;
double * psi_fr_z_d = &j_plane[j_plane_idx];
int k_plane_idx = K_PLANE_INDEX(i, j)*num_directions*num_groups +
d*num_groups;
double * psi_bo_z_d = &k_plane[k_plane_idx];
for (int group = 0; group < num_groups; ++group) {
/* Calculate new zonal flux */
index_type sigt_idx{{gd_set.group0+group, 0}};
rhs_z_idx[0] = group;
double psi_z_d_g = (rhs_z(rhs_z_idx)
+ psi_lf_z_d[group] * xcos_dxi
+ psi_fr_z_d[group] * ycos_dyj
+ psi_bo_z_d[group] * zcos_dzk)
/ (xcos_dxi + ycos_dyj + zcos_dzk +
v.sigt()(sigt_idx));
psi_z_idx[0] = group;
psi_z(psi_z_idx) = psi_z_d_g;
/* Apply diamond-difference relationships */
psi_z_d_g *= 2.0;
psi_lf_z_d[group] = psi_z_d_g - psi_lf_z_d[group];
psi_fr_z_d[group] = psi_z_d_g - psi_fr_z_d[group];
psi_bo_z_d[group] = psi_z_d_g - psi_bo_z_d[group];
}
}
}
}
}
result[0] = std::move(i_plane);
result[1] = std::move(j_plane);
result[2] = std::move(k_plane);
return result;
}
#endif
|
broadcast_reduce_customized-inl.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2015-2017 by Contributors
* \file broadcast_reduce_customized-inl.h
* \brief CPU-specific Function definition of broadcast and reduce operators
*/
#ifndef MXNET_OPERATOR_NUMPY_LINALG_BROADCAST_REDUCE_CUSTOMIZED_INL_H_
#define MXNET_OPERATOR_NUMPY_LINALG_BROADCAST_REDUCE_CUSTOMIZED_INL_H_
#include "../../tensor/broadcast_reduce-inl.h"
namespace mxnet {
namespace op {
namespace broadcast {
using namespace mshadow;
using mxnet_op::unravel;
using mxnet_op::ravel;
using mxnet_op::dot;
using mxnet_op::unravel_dot;
template<typename Reducer, int ndim, typename AType, typename DType, typename OType, typename OP>
MSHADOW_XINLINE void seq_reduce_assign_wr(const index_t idx, const size_t M, const bool addto,
const DType* __restrict big, OType *small,
const Shape<ndim>& bshape, const Shape<ndim>& sshape,
const Shape<ndim>& rshape, const Shape<ndim>& rstride,
Reducer* reducer) {
Shape<ndim> coord = unravel(idx, sshape);
index_t j = ravel(coord, bshape);
AType val, residual;
reducer->SetInitValue(val, residual);
for (size_t k = 0; k < M; ++k) {
coord = unravel(k, rshape);
reducer->Reduce(val, AType(OP::Map(big[j + dot(coord, rstride)])), residual);
}
reducer->Finalize(val, residual);
assign(&small[idx], addto, OType(val));
}
template<typename Reducer, int ndim, typename AType, typename DType, typename OType, typename OP>
void seq_reduce_compute_wr(const size_t N, const size_t M, const bool addto,
const DType *big, OType *small, const Shape<ndim> bshape,
const Shape<ndim> sshape, const Shape<ndim> rshape,
const Shape<ndim> rstride,
Reducer* reducer) {
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) {
seq_reduce_assign_wr<Reducer, ndim, AType, DType, OType, OP>(idx, M, addto, big, small,
bshape, sshape, rshape, rstride, reducer);
}
}
template <typename Reducer, int ndim, typename DType, typename OP, bool safe_acc = false>
void ReduceWithReducer(Stream<cpu>* s, const TBlob& small, const OpReqType req,
const Tensor<cpu, 1, char>& workspace, const TBlob& big,
Reducer* reducer) {
if (req == kNullOp) return;
Shape<ndim> rshape, rstride;
diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride);
size_t N = small.shape_.Size(), M = rshape.Size();
if (!safe_acc) {
seq_reduce_compute_wr<Reducer, ndim, DType, DType, DType, OP>(
N, M, req == kAddTo, big.dptr<DType>(), small.dptr<DType>(),
big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride, reducer);
} else {
MXNET_ACC_TYPE_SWITCH(mshadow::DataType<DType>::kFlag, DataType, AType, {
typedef typename std::conditional<safe_acc, AType, DataType>::type AccType;
MSHADOW_TYPE_SWITCH_WITH_BOOL(small.type_flag_, OType, {
typedef typename std::conditional<safe_acc, OType, DataType>::type OutType;
seq_reduce_compute_wr<Reducer, ndim, AccType, DataType, OutType, OP>(
N, M, req == kAddTo, big.dptr<DataType>(), small.dptr<OutType>(),
big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride, reducer);
});
});
}
}
template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2>
MSHADOW_XINLINE void seq_reduce_assign_wr(const index_t idx, const size_t M, const bool addto,
const DType* __restrict big, const DType* __restrict lhs,
const DType* __restrict rhs, DType *small,
const Shape<ndim>& big_shape,
const Shape<ndim>& lhs_shape0,
const Shape<ndim>& rhs_shape0,
const Shape<ndim>& small_shape, const Shape<ndim>& rshape,
const Shape<ndim>& lhs_shape,
const Shape<ndim>& rhs_shape,
const Shape<ndim>& rstride, const Shape<ndim>& lhs_stride,
const Shape<ndim>& rhs_stride,
Reducer* reducer) {
Shape<ndim> coord = unravel(idx, small_shape);
const index_t idx_big0 = ravel(coord, big_shape);
const index_t idx_lhs0 = ravel(coord, lhs_shape0);
const index_t idx_rhs0 = ravel(coord, rhs_shape0);
DType val, residual;
reducer->SetInitValue(val, residual);
for (size_t k = 0; k < M; ++k) {
Shape<ndim> coord_big = unravel(k, rshape);
index_t idx_big = idx_big0 + dot(coord_big, rstride);
Shape<ndim> coord_lhs = unravel(k, lhs_shape);
index_t idx_lhs = idx_lhs0 + dot(coord_lhs, lhs_stride);
Shape<ndim> coord_rhs = unravel(k, rhs_shape);
index_t idx_rhs = idx_rhs0 + dot(coord_rhs, rhs_stride);
reducer->Reduce(val, OP1::Map(big[idx_big], OP2::Map(lhs[idx_lhs], rhs[idx_rhs])), residual);
}
reducer->Finalize(val, residual);
assign(&small[idx], addto, val);
}
template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2>
void seq_reduce_compute_wr(const size_t N, const size_t M, const bool addto,
const DType *big, const DType *lhs, const DType *rhs, DType *small,
const Shape<ndim> big_shape, const Shape<ndim> small_shape,
const Shape<ndim> rshape, const Shape<ndim> rstride,
const Shape<ndim> lhs_shape, const Shape<ndim> lhs_stride,
const Shape<ndim> rhs_shape, const Shape<ndim> rhs_stride,
const Shape<ndim>& lhs_shape0, const Shape<ndim>& rhs_shape0,
Reducer* reducer) {
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) {
seq_reduce_assign_wr<Reducer, ndim, DType, OP1, OP2>(idx, M, addto, big, lhs, rhs, small,
big_shape, lhs_shape0, rhs_shape0, small_shape, rshape, lhs_shape, rhs_shape, rstride,
lhs_stride, rhs_stride, reducer);
}
}
template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2>
void ReduceWithReducer(Stream<cpu> *s, const TBlob& small, const OpReqType req,
const Tensor<cpu, 1, char>& workspace, const TBlob& big, const TBlob& lhs,
const TBlob& rhs, Reducer* reducer) {
if (req == kNullOp) return;
Shape<ndim> rshape, rstride;
diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride);
size_t N = small.shape_.Size();
size_t M = rshape.Size();
Shape<ndim> lhs_shape, lhs_stride;
diff(small.shape_.get<ndim>(), lhs.shape_.get<ndim>(), &lhs_shape, &lhs_stride);
Shape<ndim> rhs_shape, rhs_stride;
diff(small.shape_.get<ndim>(), rhs.shape_.get<ndim>(), &rhs_shape, &rhs_stride);
seq_reduce_compute_wr<Reducer, ndim, DType, OP1, OP2>(
N, M, req == kAddTo,
big.dptr<DType>(), lhs.dptr<DType>(), rhs.dptr<DType>(), small.dptr<DType>(),
big.shape_.get<ndim>(), small.shape_.get<ndim>(),
rshape, rstride,
lhs_shape, lhs_stride,
rhs_shape, rhs_stride,
lhs.shape_.get<ndim>(), rhs.shape_.get<ndim>(),
reducer);
}
} // namespace broadcast
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_NUMPY_LINALG_BROADCAST_REDUCE_CUSTOMIZED_INL_H_
|
3d25pt_var.c | /*
* Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*13);
for(m=0; m<13;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 24;
tile_size[1] = 24;
tile_size[2] = 24;
tile_size[3] = 2048;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<13; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt; t++) {
for (i = 4; i < Nz-4; i++) {
for (j = 4; j < Ny-4; j++) {
for (k = 4; k < Nx-4; k++) {
A[(t+1)%2][i][j][k] =
coef[0][i][j][k] * A[(t)%2][i ][j ][k ] +
coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) +
coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) +
coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) +
coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) +
coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) +
coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) +
coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) +
coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) +
coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) +
coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) +
coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) +
coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ;
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "variable axis-symmetric")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<13;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
scale.c | // Modified from the coop package. Copyright (c) 2015-2017 Drew Schmidt
#include <Rdefines.h>
#include <stdbool.h>
#include "safeomp.h"
#include "Rfloat.h"
#include "unroll.h"
static inline void centerscalevec(const float_len_t j, const float_len_t m, float *restrict x, float *restrict colmean, float *restrict colvar)
{
const float tmp = 1. / ((float) m-1);
const float_len_t mj = m*j;
*colmean = 0;
*colvar = 0;
for (float_len_t i=0; i<m; i++)
{
float dt = x[i + mj] - *colmean;
*colmean += dt/((float) i+1);
*colvar += dt * (x[i + mj] - *colmean);
}
*colvar = sqrt(*colvar * tmp);
// Remove mean and variance
SAFE_FOR_SIMD
for (float_len_t i=0; i<m; i++)
x[i + mj] = (x[i + mj] - *colmean) / *colvar;
}
static inline float centervec(const float_len_t j, const float_len_t m, float *x)
{
const float div = 1. / ((float) m);
const float_len_t mj = m*j;
float colmean = 0;
// Get column mean
SAFE_FOR_SIMD
for (float_len_t i=0; i<m; i++)
colmean += x[i + mj] * div;
// Remove mean from column
SAFE_FOR_SIMD
for (float_len_t i=0; i<m; i++)
x[i + mj] -= colmean;
return colmean;
}
static inline float scalevec(const float_len_t j, const float_len_t m, float *x)
{
const float div = 1./((float) m-1);
const float_len_t mj = m*j;
float colvar = 0;
// Get column variance
SAFE_FOR_SIMD
for (float_len_t i=0; i<m; i++)
{
float tmp = x[i + mj];
colvar += tmp*tmp*div;
}
colvar = sqrt(colvar);
// Remove variance from column
SAFE_FOR_SIMD
for (float_len_t i=0; i<m; i++)
x[i + mj] /= colvar;
return colvar;
}
static inline int scaler(const bool centerx, const bool scalex, const float_len_t m, const float_len_t n, float *restrict x, float *restrict colmeans, float *restrict colvars)
{
if (m == 0 || n == 0)
return 0;
// Doing both at once, if needed, is more performant
if (centerx && scalex)
{
float colmean;
float colvar;
#pragma omp parallel for shared(x) if (m*n > OMP_MIN_SIZE)
for (float_len_t j=0; j<n; j++)
{
centerscalevec(j, m, x, &colmean, &colvar);
colmeans[j] = colmean;
colvars[j] = colvar;
}
}
else if (centerx)
{
#pragma omp parallel for shared(x) if (m*n > OMP_MIN_SIZE)
for (float_len_t j=0; j<n; j++)
colmeans[j] = centervec(j, m, x);
}
else if (scalex) // RMSE
{
#pragma omp parallel for shared(x) if (m*n > OMP_MIN_SIZE)
for (float_len_t j=0; j<n; j++)
colvars[j] = scalevec(j, m, x);
}
return 0;
}
SEXP R_scale_spm(SEXP x, SEXP center_, SEXP scale_)
{
SEXP ret;
SEXP ret_s4_class, cm_s4_class, cv_s4_class;
SEXP ret_s4, cm_s4, cv_s4;
SEXP cm, cv;
const float_len_t m = NROWS(x);
const float_len_t n = NCOLS(x);
const bool center = INTEGER(center_)[0];
const bool scale = INTEGER(scale_)[0];
int ptct = 0;
float *colmeans, *colvars;
PROTECT(ret = newmat(m, n));
ptct++;
memcpy(DATA(ret), DATA(x), (size_t)m*n*sizeof(float));
if (center)
{
PROTECT(cm = newvec(n));
ptct++;
colmeans = DATA(cm);
}
else
{
cm = NULL;
colmeans = NULL;
}
if (scale)
{
PROTECT(cv = newvec(n));
ptct++;
colvars = DATA(cv);
}
else
{
cv = NULL;
colvars = NULL;
}
scaler(center, scale, m, n, DATA(ret), colmeans, colvars);
PROTECT(ret_s4_class = MAKE_CLASS("float32"));
PROTECT(ret_s4 = NEW_OBJECT(ret_s4_class));
ptct += 2;
SET_SLOT(ret_s4, install("Data"), ret);
if (center)
{
PROTECT(cm_s4_class = MAKE_CLASS("float32"));
PROTECT(cm_s4 = NEW_OBJECT(cm_s4_class));
ptct += 2;
SET_SLOT(cm_s4, install("Data"), cm);
setAttrib(ret_s4, install("scaled:center"), cm_s4);
}
if (scale)
{
PROTECT(cv_s4_class = MAKE_CLASS("float32"));
PROTECT(cv_s4 = NEW_OBJECT(cv_s4_class));
ptct += 2;
SET_SLOT(cv_s4, install("Data"), cv);
setAttrib(ret_s4, install("scaled:scale"), cv_s4);
}
UNPROTECT(ptct);
return ret_s4;
}
|
GB_unop__asinh_fp64_fp64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__asinh_fp64_fp64)
// op(A') function: GB (_unop_tran__asinh_fp64_fp64)
// C type: double
// A type: double
// cast: double cij = aij
// unaryop: cij = asinh (aij)
#define GB_ATYPE \
double
#define GB_CTYPE \
double
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = asinh (x) ;
// casting
#define GB_CAST(z, aij) \
double z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
double aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
double z = aij ; \
Cx [pC] = asinh (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_ASINH || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__asinh_fp64_fp64)
(
double *Cx, // Cx and Ax may be aliased
const double *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 (double), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
double aij = Ax [p] ;
double z = aij ;
Cx [p] = asinh (z) ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
double aij = Ax [p] ;
double z = aij ;
Cx [p] = asinh (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__asinh_fp64_fp64)
(
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.